OSDN Git Service

2010-12-09 Steven G. Kargl <kargl@gcc.gnu.org>
[pf3gnuchains/gcc-fork.git] / gcc / ada / gnat_ugn.texi
1 \input texinfo   @c -*-texinfo-*-
2 @c %**start of header
3
4 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
5 @c                                                                            o
6 @c                            GNAT DOCUMENTATION                              o
7 @c                                                                            o
8 @c                             G N A T _ U G N                                o
9 @c                                                                            o
10 @c                     Copyright (C) 1992-2010, AdaCore                       o
11 @c                                                                            o
12 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
13
14 @setfilename gnat_ugn.info
15
16 @copying
17 Copyright @copyright{} 1995-2009 Free Software Foundation,
18 Inc.
19
20 Permission is granted to copy, distribute and/or modify this document
21 under the terms of the GNU Free Documentation License, Version 1.3 or
22 any later version published by the Free Software Foundation; with no
23 Invariant Sections, with no Front-Cover Texts and with no Back-Cover
24 Texts.  A copy of the license is included in the section entitled
25 ``GNU Free Documentation License''.
26 @end copying
27
28 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
29 @c
30 @c                           GNAT_UGN Style Guide
31 @c
32 @c  1. Always put a @noindent on the line before the first paragraph
33 @c     after any of these commands:
34 @c
35 @c          @chapter
36 @c          @section
37 @c          @subsection
38 @c          @subsubsection
39 @c          @subsubsubsection
40 @c
41 @c          @end smallexample
42 @c          @end itemize
43 @c          @end enumerate
44 @c
45 @c  2. DO NOT use @example. Use @smallexample instead.
46 @c     a) DO NOT use highlighting commands (@b{}, @i{}) inside an @smallexample
47 @c        context.  These can interfere with the readability of the texi
48 @c        source file.  Instead, use one of the following annotated
49 @c        @smallexample commands, and preprocess the texi file with the
50 @c        ada2texi tool (which generates appropriate highlighting):
51 @c        @smallexample @c ada
52 @c        @smallexample @c adanocomment
53 @c        @smallexample @c projectfile
54 @c     b) The "@c ada" markup will result in boldface for reserved words
55 @c        and italics for comments
56 @c     c) The "@c adanocomment" markup will result only in boldface for
57 @c        reserved words (comments are left alone)
58 @c     d) The "@c projectfile" markup is like "@c ada" except that the set
59 @c        of reserved words include the new reserved words for project files
60 @c
61 @c  3. Each @chapter, @section, @subsection, @subsubsection, etc.
62 @c     command must be preceded by two empty lines
63 @c
64 @c  4. The @item command should be on a line of its own if it is in an
65 @c     @itemize or @enumerate command.
66 @c
67 @c  5. When talking about ALI files use "ALI" (all uppercase), not "Ali"
68 @c     or "ali".
69 @c
70 @c  6. DO NOT put trailing spaces at the end of a line.  Such spaces will
71 @c     cause the document build to fail.
72 @c
73 @c  7. DO NOT use @cartouche for examples that are longer than around 10 lines.
74 @c     This command inhibits page breaks, so long examples in a @cartouche can
75 @c     lead to large, ugly patches of empty space on a page.
76 @c
77 @c  NOTE: This file should be submitted to xgnatugn with either the vms flag
78 @c        or the unw flag set.  The unw flag covers topics for both Unix and
79 @c        Windows.
80 @c
81 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
82
83 @set NOW January 2007
84 @c This flag is used where the text refers to conditions that exist when the
85 @c text was entered into the document but which may change over time.
86 @c Update the setting for the flag, and (if necessary) the text surrounding,
87 @c the references to the flag, on future doc revisions:
88 @c search for @value{NOW}.
89
90 @set FSFEDITION
91 @set EDITION GNAT
92 @set DEFAULTLANGUAGEVERSION Ada 2005
93 @set NONDEFAULTLANGUAGEVERSION Ada 95
94
95 @ifset unw
96 @set PLATFORM
97 @end ifset
98
99 @ifset vms
100 @set PLATFORM OpenVMS
101 @end ifset
102
103 @c @ovar(ARG)
104 @c ----------
105 @c The ARG is an optional argument.  To be used for macro arguments in
106 @c their documentation (@defmac).
107 @macro ovar{varname}
108 @r{[}@var{\varname\}@r{]}@c
109 @end macro
110 @c Status as of November 2009:
111 @c Unfortunately texi2pdf and texi2html treat the trailing "@c"
112 @c differently, and faulty output is produced by one or the other
113 @c depending on whether the "@c" is present or absent.
114 @c As a result, the @ovar macro is not used, and all invocations
115 @c of the @ovar macro have been expanded inline.
116
117
118 @settitle @value{EDITION} User's Guide @value{PLATFORM}
119 @dircategory GNU Ada tools
120 @direntry
121 * @value{EDITION} User's Guide: (gnat_ugn). @value{PLATFORM}
122 @end direntry
123
124 @include gcc-common.texi
125
126 @setchapternewpage odd
127 @syncodeindex fn cp
128 @c %**end of header
129
130 @titlepage
131 @title @value{EDITION} User's Guide
132 @ifset vms
133 @sp 1
134 @flushright
135 @titlefont{@i{@value{PLATFORM}}}
136 @end flushright
137 @end ifset
138
139 @sp 2
140
141 @subtitle GNAT, The GNU Ada Compiler
142 @versionsubtitle
143 @author AdaCore
144
145 @page
146 @vskip 0pt plus 1filll
147
148 @insertcopying
149
150 @end titlepage
151
152 @ifnottex
153 @node Top, About This Guide, (dir), (dir)
154 @top @value{EDITION} User's Guide
155
156 @noindent
157 @value{EDITION} User's Guide @value{PLATFORM}
158
159 @noindent
160 GNAT, The GNU Ada Compiler@*
161 GCC version @value{version-GCC}@*
162
163 @noindent
164 AdaCore@*
165
166 @menu
167 * About This Guide::
168 * Getting Started with GNAT::
169 * The GNAT Compilation Model::
170 * Compiling Using gcc::
171 * Binding Using gnatbind::
172 * Linking Using gnatlink::
173 * The GNAT Make Program gnatmake::
174 * Improving Performance::
175 * Renaming Files Using gnatchop::
176 * Configuration Pragmas::
177 * Handling Arbitrary File Naming Conventions Using gnatname::
178 * GNAT Project Manager::
179 * Tools Supporting Project Files::
180 * The Cross-Referencing Tools gnatxref and gnatfind::
181 * The GNAT Pretty-Printer gnatpp::
182 * The GNAT Metric Tool gnatmetric::
183 * File Name Krunching Using gnatkr::
184 * Preprocessing Using gnatprep::
185 * The GNAT Library Browser gnatls::
186 * Cleaning Up Using gnatclean::
187 @ifclear vms
188 * GNAT and Libraries::
189 * Using the GNU make Utility::
190 @end ifclear
191 * Memory Management Issues::
192 * Stack Related Facilities::
193 * Verifying Properties Using gnatcheck::
194 * Creating Sample Bodies Using gnatstub::
195 * Generating Ada Bindings for C and C++ headers::
196 * Other Utility Programs::
197 * Running and Debugging Ada Programs::
198 @ifclear vms
199 * Code Coverage and Profiling::
200 @end ifclear
201 @ifset vms
202 * Compatibility with HP Ada::
203 @end ifset
204 * Platform-Specific Information for the Run-Time Libraries::
205 * Example of Binder Output File::
206 * Elaboration Order Handling in GNAT::
207 * Conditional Compilation::
208 * Inline Assembler::
209 * Compatibility and Porting Guide::
210 @ifset unw
211 * Microsoft Windows Topics::
212 @end ifset
213 * GNU Free Documentation License::
214 * Index::
215
216  --- The Detailed Node Listing ---
217
218 About This Guide
219
220 * What This Guide Contains::
221 * What You Should Know before Reading This Guide::
222 * Related Information::
223 * Conventions::
224
225 Getting Started with GNAT
226
227 * Running GNAT::
228 * Running a Simple Ada Program::
229 * Running a Program with Multiple Units::
230 * Using the gnatmake Utility::
231 @ifset vms
232 * Editing with Emacs::
233 @end ifset
234 @ifclear vms
235 * Introduction to GPS::
236 @end ifclear
237
238 The GNAT Compilation Model
239
240 * Source Representation::
241 * Foreign Language Representation::
242 * File Naming Rules::
243 * Using Other File Names::
244 * Alternative File Naming Schemes::
245 * Generating Object Files::
246 * Source Dependencies::
247 * The Ada Library Information Files::
248 * Binding an Ada Program::
249 * Mixed Language Programming::
250 @ifclear vms
251 * Building Mixed Ada & C++ Programs::
252 * Comparison between GNAT and C/C++ Compilation Models::
253 @end ifclear
254 * Comparison between GNAT and Conventional Ada Library Models::
255 @ifset vms
256 * Placement of temporary files::
257 @end ifset
258
259 Foreign Language Representation
260
261 * Latin-1::
262 * Other 8-Bit Codes::
263 * Wide Character Encodings::
264
265 Compiling Ada Programs With gcc
266
267 * Compiling Programs::
268 * Switches for gcc::
269 * Search Paths and the Run-Time Library (RTL)::
270 * Order of Compilation Issues::
271 * Examples::
272
273 Switches for gcc
274
275 * Output and Error Message Control::
276 * Warning Message Control::
277 * Debugging and Assertion Control::
278 * Validity Checking::
279 * Style Checking::
280 * Run-Time Checks::
281 * Using gcc for Syntax Checking::
282 * Using gcc for Semantic Checking::
283 * Compiling Different Versions of Ada::
284 * Character Set Control::
285 * File Naming Control::
286 * Subprogram Inlining Control::
287 * Auxiliary Output Control::
288 * Debugging Control::
289 * Exception Handling Control::
290 * Units to Sources Mapping Files::
291 * Integrated Preprocessing::
292 @ifset vms
293 * Return Codes::
294 @end ifset
295
296 Binding Ada Programs With gnatbind
297
298 * Running gnatbind::
299 * Switches for gnatbind::
300 * Command-Line Access::
301 * Search Paths for gnatbind::
302 * Examples of gnatbind Usage::
303
304 Switches for gnatbind
305
306 * Consistency-Checking Modes::
307 * Binder Error Message Control::
308 * Elaboration Control::
309 * Output Control::
310 * Binding with Non-Ada Main Programs::
311 * Binding Programs with No Main Subprogram::
312
313 Linking Using gnatlink
314
315 * Running gnatlink::
316 * Switches for gnatlink::
317
318 The GNAT Make Program gnatmake
319
320 * Running gnatmake::
321 * Switches for gnatmake::
322 * Mode Switches for gnatmake::
323 * Notes on the Command Line::
324 * How gnatmake Works::
325 * Examples of gnatmake Usage::
326
327 Improving Performance
328 * Performance Considerations::
329 * Text_IO Suggestions::
330 * Reducing Size of Ada Executables with gnatelim::
331 * Reducing Size of Executables with unused subprogram/data elimination::
332
333 Performance Considerations
334 * Controlling Run-Time Checks::
335 * Use of Restrictions::
336 * Optimization Levels::
337 * Debugging Optimized Code::
338 * Inlining of Subprograms::
339 * Other Optimization Switches::
340 * Optimization and Strict Aliasing::
341 @ifset vms
342 * Coverage Analysis::
343 @end ifset
344
345 Reducing Size of Ada Executables with gnatelim
346 * About gnatelim::
347 * Running gnatelim::
348 * Processing Precompiled Libraries::
349 * Correcting the List of Eliminate Pragmas::
350 * Making Your Executables Smaller::
351 * Summary of the gnatelim Usage Cycle::
352
353 Reducing Size of Executables with unused subprogram/data elimination
354 * About unused subprogram/data elimination::
355 * Compilation options::
356
357 Renaming Files Using gnatchop
358
359 * Handling Files with Multiple Units::
360 * Operating gnatchop in Compilation Mode::
361 * Command Line for gnatchop::
362 * Switches for gnatchop::
363 * Examples of gnatchop Usage::
364
365 Configuration Pragmas
366
367 * Handling of Configuration Pragmas::
368 * The Configuration Pragmas Files::
369
370 Handling Arbitrary File Naming Conventions Using gnatname
371
372 * Arbitrary File Naming Conventions::
373 * Running gnatname::
374 * Switches for gnatname::
375 * Examples of gnatname Usage::
376
377 The Cross-Referencing Tools gnatxref and gnatfind
378
379 * Switches for gnatxref::
380 * Switches for gnatfind::
381 * Project Files for gnatxref and gnatfind::
382 * Regular Expressions in gnatfind and gnatxref::
383 * Examples of gnatxref Usage::
384 * Examples of gnatfind Usage::
385
386 The GNAT Pretty-Printer gnatpp
387
388 * Switches for gnatpp::
389 * Formatting Rules::
390
391 The GNAT Metrics Tool gnatmetric
392
393 * Switches for gnatmetric::
394
395 File Name Krunching Using gnatkr
396
397 * About gnatkr::
398 * Using gnatkr::
399 * Krunching Method::
400 * Examples of gnatkr Usage::
401
402 Preprocessing Using gnatprep
403 * Preprocessing Symbols::
404 * Using gnatprep::
405 * Switches for gnatprep::
406 * Form of Definitions File::
407 * Form of Input Text for gnatprep::
408
409 The GNAT Library Browser gnatls
410
411 * Running gnatls::
412 * Switches for gnatls::
413 * Examples of gnatls Usage::
414
415 Cleaning Up Using gnatclean
416
417 * Running gnatclean::
418 * Switches for gnatclean::
419 @c * Examples of gnatclean Usage::
420
421 @ifclear vms
422
423 GNAT and Libraries
424
425 * Introduction to Libraries in GNAT::
426 * General Ada Libraries::
427 * Stand-alone Ada Libraries::
428 * Rebuilding the GNAT Run-Time Library::
429
430 Using the GNU make Utility
431
432 * Using gnatmake in a Makefile::
433 * Automatically Creating a List of Directories::
434 * Generating the Command Line Switches::
435 * Overcoming Command Line Length Limits::
436 @end ifclear
437
438 Memory Management Issues
439
440 * Some Useful Memory Pools::
441 * The GNAT Debug Pool Facility::
442 @ifclear vms
443 * The gnatmem Tool::
444 @end ifclear
445
446 Stack Related Facilities
447
448 * Stack Overflow Checking::
449 * Static Stack Usage Analysis::
450 * Dynamic Stack Usage Analysis::
451
452 Some Useful Memory Pools
453
454 The GNAT Debug Pool Facility
455
456 @ifclear vms
457 The gnatmem Tool
458
459 * Running gnatmem::
460 * Switches for gnatmem::
461 * Example of gnatmem Usage::
462 @end ifclear
463
464 Verifying Properties Using gnatcheck
465
466 Sample Bodies Using gnatstub
467
468 * Running gnatstub::
469 * Switches for gnatstub::
470
471 Other Utility Programs
472
473 * Using Other Utility Programs with GNAT::
474 * The External Symbol Naming Scheme of GNAT::
475 * Converting Ada Files to html with gnathtml::
476
477 @ifclear vms
478 Code Coverage and Profiling
479
480 * Code Coverage of Ada Programs using gcov::
481 * Profiling an Ada Program using gprof::
482 @end ifclear
483
484 Running and Debugging Ada Programs
485
486 * The GNAT Debugger GDB::
487 * Running GDB::
488 * Introduction to GDB Commands::
489 * Using Ada Expressions::
490 * Calling User-Defined Subprograms::
491 * Using the Next Command in a Function::
492 * Ada Exceptions::
493 * Ada Tasks::
494 * Debugging Generic Units::
495 * Remote Debugging using gdbserver::
496 * GNAT Abnormal Termination or Failure to Terminate::
497 * Naming Conventions for GNAT Source Files::
498 * Getting Internal Debugging Information::
499 * Stack Traceback::
500
501 @ifset vms
502 * LSE::
503 @end ifset
504
505 @ifset vms
506 Compatibility with HP Ada
507
508 * Ada Language Compatibility::
509 * Differences in the Definition of Package System::
510 * Language-Related Features::
511 * The Package STANDARD::
512 * The Package SYSTEM::
513 * Tasking and Task-Related Features::
514 * Pragmas and Pragma-Related Features::
515 * Library of Predefined Units::
516 * Bindings::
517 * Main Program Definition::
518 * Implementation-Defined Attributes::
519 * Compiler and Run-Time Interfacing::
520 * Program Compilation and Library Management::
521 * Input-Output::
522 * Implementation Limits::
523 * Tools and Utilities::
524
525 Language-Related Features
526
527 * Integer Types and Representations::
528 * Floating-Point Types and Representations::
529 * Pragmas Float_Representation and Long_Float::
530 * Fixed-Point Types and Representations::
531 * Record and Array Component Alignment::
532 * Address Clauses::
533 * Other Representation Clauses::
534
535 Tasking and Task-Related Features
536
537 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
538 * Assigning Task IDs::
539 * Task IDs and Delays::
540 * Task-Related Pragmas::
541 * Scheduling and Task Priority::
542 * The Task Stack::
543 * External Interrupts::
544
545 Pragmas and Pragma-Related Features
546
547 * Restrictions on the Pragma INLINE::
548 * Restrictions on the Pragma INTERFACE::
549 * Restrictions on the Pragma SYSTEM_NAME::
550
551 Library of Predefined Units
552
553 * Changes to DECLIB::
554
555 Bindings
556
557 * Shared Libraries and Options Files::
558 * Interfaces to C::
559 @end ifset
560
561 Platform-Specific Information for the Run-Time Libraries
562
563 * Summary of Run-Time Configurations::
564 * Specifying a Run-Time Library::
565 * Choosing the Scheduling Policy::
566 * Solaris-Specific Considerations::
567 * Linux-Specific Considerations::
568 * AIX-Specific Considerations::
569 * Irix-Specific Considerations::
570 * RTX-Specific Considerations::
571 * HP-UX-Specific Considerations::
572
573 Example of Binder Output File
574
575 Elaboration Order Handling in GNAT
576
577 * Elaboration Code::
578 * Checking the Elaboration Order::
579 * Controlling the Elaboration Order::
580 * Controlling Elaboration in GNAT - Internal Calls::
581 * Controlling Elaboration in GNAT - External Calls::
582 * Default Behavior in GNAT - Ensuring Safety::
583 * Treatment of Pragma Elaborate::
584 * Elaboration Issues for Library Tasks::
585 * Mixing Elaboration Models::
586 * What to Do If the Default Elaboration Behavior Fails::
587 * Elaboration for Access-to-Subprogram Values::
588 * Summary of Procedures for Elaboration Control::
589 * Other Elaboration Order Considerations::
590
591 Conditional Compilation
592 * Use of Boolean Constants::
593 * Debugging - A Special Case::
594 * Conditionalizing Declarations::
595 * Use of Alternative Implementations::
596 * Preprocessing::
597
598 Inline Assembler
599
600 * Basic Assembler Syntax::
601 * A Simple Example of Inline Assembler::
602 * Output Variables in Inline Assembler::
603 * Input Variables in Inline Assembler::
604 * Inlining Inline Assembler Code::
605 * Other Asm Functionality::
606
607 Compatibility and Porting Guide
608
609 * Compatibility with Ada 83::
610 * Compatibility between Ada 95 and Ada 2005::
611 * Implementation-dependent characteristics::
612 @ifclear vms
613 @c This brief section is only in the non-VMS version
614 @c The complete chapter on HP Ada issues is in the VMS version
615 * Compatibility with HP Ada 83::
616 @end ifclear
617 * Compatibility with Other Ada Systems::
618 * Representation Clauses::
619 @ifset vms
620 * Transitioning to 64-Bit GNAT for OpenVMS::
621 @end ifset
622
623 @ifset unw
624 Microsoft Windows Topics
625
626 * Using GNAT on Windows::
627 * CONSOLE and WINDOWS subsystems::
628 * Temporary Files::
629 * Mixed-Language Programming on Windows::
630 * Windows Calling Conventions::
631 * Introduction to Dynamic Link Libraries (DLLs)::
632 * Using DLLs with GNAT::
633 * Building DLLs with GNAT::
634 * GNAT and Windows Resources::
635 * Debugging a DLL::
636 * Setting Stack Size from gnatlink::
637 * Setting Heap Size from gnatlink::
638 @end ifset
639
640 * Index::
641 @end menu
642 @end ifnottex
643
644 @node About This Guide
645 @unnumbered About This Guide
646
647 @noindent
648 @ifset vms
649 This guide describes the use of @value{EDITION},
650 a compiler and software development toolset for the full Ada
651 programming language, implemented on OpenVMS for HP's Alpha and
652 Integrity server (I64) platforms.
653 @end ifset
654 @ifclear vms
655 This guide describes the use of @value{EDITION},
656 a compiler and software development
657 toolset for the full Ada programming language.
658 @end ifclear
659 It documents the features of the compiler and tools, and explains
660 how to use them to build Ada applications.
661
662 @value{EDITION} implements Ada 95 and Ada 2005, and it may also be invoked in
663 Ada 83 compatibility mode.
664 By default, @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION},
665 but you can override with a compiler switch
666 (@pxref{Compiling Different Versions of Ada})
667 to explicitly specify the language version.
668 Throughout this manual, references to ``Ada'' without a year suffix
669 apply to both the Ada 95 and Ada 2005 versions of the language.
670
671
672 @ifclear FSFEDITION
673 For ease of exposition, ``@value{EDITION}'' will be referred to simply as
674 ``GNAT'' in the remainder of this document.
675 @end ifclear
676
677
678
679
680 @menu
681 * What This Guide Contains::
682 * What You Should Know before Reading This Guide::
683 * Related Information::
684 * Conventions::
685 @end menu
686
687 @node What This Guide Contains
688 @unnumberedsec What This Guide Contains
689
690 @noindent
691 This guide contains the following chapters:
692 @itemize @bullet
693
694 @item
695 @ref{Getting Started with GNAT}, describes how to get started compiling
696 and running Ada programs with the GNAT Ada programming environment.
697 @item
698 @ref{The GNAT Compilation Model}, describes the compilation model used
699 by GNAT.
700
701 @item
702 @ref{Compiling Using gcc}, describes how to compile
703 Ada programs with @command{gcc}, the Ada compiler.
704
705 @item
706 @ref{Binding Using gnatbind}, describes how to
707 perform binding of Ada programs with @code{gnatbind}, the GNAT binding
708 utility.
709
710 @item
711 @ref{Linking Using gnatlink},
712 describes @command{gnatlink}, a
713 program that provides for linking using the GNAT run-time library to
714 construct a program. @command{gnatlink} can also incorporate foreign language
715 object units into the executable.
716
717 @item
718 @ref{The GNAT Make Program gnatmake}, describes @command{gnatmake}, a
719 utility that automatically determines the set of sources
720 needed by an Ada compilation unit, and executes the necessary compilations
721 binding and link.
722
723 @item
724 @ref{Improving Performance}, shows various techniques for making your
725 Ada program run faster or take less space.
726 It discusses the effect of the compiler's optimization switch and
727 also describes the @command{gnatelim} tool and unused subprogram/data
728 elimination.
729
730 @item
731 @ref{Renaming Files Using gnatchop}, describes
732 @code{gnatchop}, a utility that allows you to preprocess a file that
733 contains Ada source code, and split it into one or more new files, one
734 for each compilation unit.
735
736 @item
737 @ref{Configuration Pragmas}, describes the configuration pragmas
738 handled by GNAT.
739
740 @item
741 @ref{Handling Arbitrary File Naming Conventions Using gnatname},
742 shows how to override the default GNAT file naming conventions,
743 either for an individual unit or globally.
744
745 @item
746 @ref{GNAT Project Manager}, describes how to use project files
747 to organize large projects.
748
749 @item
750 @ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses
751 @code{gnatxref} and @code{gnatfind}, two tools that provide an easy
752 way to navigate through sources.
753
754 @item
755 @ref{The GNAT Pretty-Printer gnatpp}, shows how to produce a reformatted
756 version of an Ada source file with control over casing, indentation,
757 comment placement, and other elements of program presentation style.
758
759 @item
760 @ref{The GNAT Metric Tool gnatmetric}, shows how to compute various
761 metrics for an Ada source file, such as the number of types and subprograms,
762 and assorted complexity measures.
763
764 @item
765 @ref{File Name Krunching Using gnatkr}, describes the @code{gnatkr}
766 file name krunching utility, used to handle shortened
767 file names on operating systems with a limit on the length of names.
768
769 @item
770 @ref{Preprocessing Using gnatprep}, describes @code{gnatprep}, a
771 preprocessor utility that allows a single source file to be used to
772 generate multiple or parameterized source files by means of macro
773 substitution.
774
775 @item
776 @ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a
777 utility that displays information about compiled units, including dependences
778 on the corresponding sources files, and consistency of compilations.
779
780 @item
781 @ref{Cleaning Up Using gnatclean}, describes @code{gnatclean}, a utility
782 to delete files that are produced by the compiler, binder and linker.
783
784 @ifclear vms
785 @item
786 @ref{GNAT and Libraries}, describes the process of creating and using
787 Libraries with GNAT. It also describes how to recompile the GNAT run-time
788 library.
789
790 @item
791 @ref{Using the GNU make Utility}, describes some techniques for using
792 the GNAT toolset in Makefiles.
793 @end ifclear
794
795 @item
796 @ref{Memory Management Issues}, describes some useful predefined storage pools
797 and in particular the GNAT Debug Pool facility, which helps detect incorrect
798 memory references.
799 @ifclear vms
800 It also describes @command{gnatmem}, a utility that monitors dynamic
801 allocation and deallocation and helps detect ``memory leaks''.
802 @end ifclear
803
804 @item
805 @ref{Stack Related Facilities}, describes some useful tools associated with
806 stack checking and analysis.
807
808 @item
809 @ref{Verifying Properties Using gnatcheck}, discusses @code{gnatcheck},
810 a utility that checks Ada code against a set of rules.
811
812 @item
813 @ref{Creating Sample Bodies Using gnatstub}, discusses @code{gnatstub},
814 a utility that generates empty but compilable bodies for library units.
815
816 @item
817 @ref{Generating Ada Bindings for C and C++ headers}, describes how to
818 generate automatically Ada bindings from C and C++ headers.
819
820 @item
821 @ref{Other Utility Programs}, discusses several other GNAT utilities,
822 including @code{gnathtml}.
823
824 @ifclear vms
825 @item
826 @ref{Code Coverage and Profiling}, describes how to perform a structural
827 coverage and profile the execution of Ada programs.
828 @end ifclear
829
830 @item
831 @ref{Running and Debugging Ada Programs}, describes how to run and debug
832 Ada programs.
833
834 @ifset vms
835 @item
836 @ref{Compatibility with HP Ada}, details the compatibility of GNAT with
837 HP Ada 83 @footnote{``HP Ada'' refers to the legacy product originally
838 developed by Digital Equipment Corporation and currently supported by HP.}
839 for OpenVMS Alpha. This product was formerly known as DEC Ada,
840 @cindex DEC Ada
841 and for
842 historical compatibility reasons, the relevant libraries still use the
843 DEC prefix.
844 @end ifset
845
846 @item
847 @ref{Platform-Specific Information for the Run-Time Libraries},
848 describes the various run-time
849 libraries supported by GNAT on various platforms and explains how to
850 choose a particular library.
851
852 @item
853 @ref{Example of Binder Output File}, shows the source code for the binder
854 output file for a sample program.
855
856 @item
857 @ref{Elaboration Order Handling in GNAT}, describes how GNAT helps
858 you deal with elaboration order issues.
859
860 @item
861 @ref{Conditional Compilation}, describes how to model conditional compilation,
862 both with Ada in general and with GNAT facilities in particular.
863
864 @item
865 @ref{Inline Assembler}, shows how to use the inline assembly facility
866 in an Ada program.
867
868 @item
869 @ref{Compatibility and Porting Guide}, contains sections on compatibility
870 of GNAT with other Ada development environments (including Ada 83 systems),
871 to assist in porting code from those environments.
872
873 @ifset unw
874 @item
875 @ref{Microsoft Windows Topics}, presents information relevant to the
876 Microsoft Windows platform.
877 @end ifset
878 @end itemize
879
880 @c *************************************************
881 @node What You Should Know before Reading This Guide
882 @c *************************************************
883 @unnumberedsec What You Should Know before Reading This Guide
884
885 @cindex Ada 95 Language Reference Manual
886 @cindex Ada 2005 Language Reference Manual
887 @noindent
888 This guide assumes a basic familiarity with the Ada 95 language, as
889 described in the International Standard ANSI/ISO/IEC-8652:1995, January
890 1995.
891 It does not require knowledge of the new features introduced by Ada 2005,
892 (officially known as ISO/IEC 8652:1995 with Technical Corrigendum 1
893 and Amendment 1).
894 Both reference manuals are included in the GNAT documentation
895 package.
896
897 @node Related Information
898 @unnumberedsec Related Information
899
900 @noindent
901 For further information about related tools, refer to the following
902 documents:
903
904 @itemize @bullet
905 @item
906 @xref{Top, GNAT Reference Manual, About This Guide, gnat_rm, GNAT
907 Reference Manual}, which contains all reference material for the GNAT
908 implementation of Ada.
909
910 @ifset unw
911 @item
912 @cite{Using the GNAT Programming Studio}, which describes the GPS
913 Integrated Development Environment.
914
915 @item
916 @cite{GNAT Programming Studio Tutorial}, which introduces the
917 main GPS features through examples.
918 @end ifset
919
920 @item
921 @cite{Ada 95 Reference Manual}, which contains reference
922 material for the Ada 95 programming language.
923
924 @item
925 @cite{Ada 2005 Reference Manual}, which contains reference
926 material for the Ada 2005 programming language.
927
928 @item
929 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
930 @ifset vms
931 in the GNU:[DOCS] directory,
932 @end ifset
933 for all details on the use of the GNU source-level debugger.
934
935 @item
936 @xref{Top,, The extensible self-documenting text editor, emacs,
937 GNU Emacs Manual},
938 @ifset vms
939 located in the GNU:[DOCS] directory if the EMACS kit is installed,
940 @end ifset
941 for full information on the extensible editor and programming
942 environment Emacs.
943
944 @end itemize
945
946 @c **************
947 @node Conventions
948 @unnumberedsec Conventions
949 @cindex Conventions
950 @cindex Typographical conventions
951
952 @noindent
953 Following are examples of the typographical and graphic conventions used
954 in this guide:
955
956 @itemize @bullet
957 @item
958 @code{Functions}, @command{utility program names}, @code{standard names},
959 and @code{classes}.
960
961 @item
962 @option{Option flags}
963
964 @item
965 @file{File names}, @samp{button names}, and @samp{field names}.
966
967 @item
968 @code{Variables}, @env{environment variables}, and @var{metasyntactic
969 variables}.
970
971 @item
972 @emph{Emphasis}.
973
974 @item
975 @r{[}optional information or parameters@r{]}
976
977 @item
978 Examples are described by text
979 @smallexample
980 and then shown this way.
981 @end smallexample
982 @end itemize
983
984 @noindent
985 Commands that are entered by the user are preceded in this manual by the
986 characters @w{``@code{$ }''} (dollar sign followed by space). If your system
987 uses this sequence as a prompt, then the commands will appear exactly as
988 you see them in the manual. If your system uses some other prompt, then
989 the command will appear with the @code{$} replaced by whatever prompt
990 character you are using.
991
992 @ifset unw
993 Full file names are shown with the ``@code{/}'' character
994 as the directory separator; e.g., @file{parent-dir/subdir/myfile.adb}.
995 If you are using GNAT on a Windows platform, please note that
996 the ``@code{\}'' character should be used instead.
997 @end ifset
998
999 @c ****************************
1000 @node Getting Started with GNAT
1001 @chapter Getting Started with GNAT
1002
1003 @noindent
1004 This chapter describes some simple ways of using GNAT to build
1005 executable Ada programs.
1006 @ifset unw
1007 @ref{Running GNAT}, through @ref{Using the gnatmake Utility},
1008 show how to use the command line environment.
1009 @ref{Introduction to GPS}, provides a brief
1010 introduction to the GNAT Programming Studio, a visually-oriented
1011 Integrated Development Environment for GNAT.
1012 GPS offers a graphical ``look and feel'', support for development in
1013 other programming languages, comprehensive browsing features, and
1014 many other capabilities.
1015 For information on GPS please refer to
1016 @cite{Using the GNAT Programming Studio}.
1017 @end ifset
1018
1019 @menu
1020 * Running GNAT::
1021 * Running a Simple Ada Program::
1022 * Running a Program with Multiple Units::
1023 * Using the gnatmake Utility::
1024 @ifset vms
1025 * Editing with Emacs::
1026 @end ifset
1027 @ifclear vms
1028 * Introduction to GPS::
1029 @end ifclear
1030 @end menu
1031
1032 @node Running GNAT
1033 @section Running GNAT
1034
1035 @noindent
1036 Three steps are needed to create an executable file from an Ada source
1037 file:
1038
1039 @enumerate
1040 @item
1041 The source file(s) must be compiled.
1042 @item
1043 The file(s) must be bound using the GNAT binder.
1044 @item
1045 All appropriate object files must be linked to produce an executable.
1046 @end enumerate
1047
1048 @noindent
1049 All three steps are most commonly handled by using the @command{gnatmake}
1050 utility program that, given the name of the main program, automatically
1051 performs the necessary compilation, binding and linking steps.
1052
1053 @node Running a Simple Ada Program
1054 @section Running a Simple Ada Program
1055
1056 @noindent
1057 Any text editor may be used to prepare an Ada program.
1058 (If @code{Emacs} is
1059 used, the optional Ada mode may be helpful in laying out the program.)
1060 The
1061 program text is a normal text file. We will assume in our initial
1062 example that you have used your editor to prepare the following
1063 standard format text file:
1064
1065 @smallexample @c ada
1066 @cartouche
1067 with Ada.Text_IO; use Ada.Text_IO;
1068 procedure Hello is
1069 begin
1070    Put_Line ("Hello WORLD!");
1071 end Hello;
1072 @end cartouche
1073 @end smallexample
1074
1075 @noindent
1076 This file should be named @file{hello.adb}.
1077 With the normal default file naming conventions, GNAT requires
1078 that each file
1079 contain a single compilation unit whose file name is the
1080 unit name,
1081 with periods replaced by hyphens; the
1082 extension is @file{ads} for a
1083 spec and @file{adb} for a body.
1084 You can override this default file naming convention by use of the
1085 special pragma @code{Source_File_Name} (@pxref{Using Other File Names}).
1086 Alternatively, if you want to rename your files according to this default
1087 convention, which is probably more convenient if you will be using GNAT
1088 for all your compilations, then the @code{gnatchop} utility
1089 can be used to generate correctly-named source files
1090 (@pxref{Renaming Files Using gnatchop}).
1091
1092 You can compile the program using the following command (@code{$} is used
1093 as the command prompt in the examples in this document):
1094
1095 @smallexample
1096 $ gcc -c hello.adb
1097 @end smallexample
1098
1099 @noindent
1100 @command{gcc} is the command used to run the compiler. This compiler is
1101 capable of compiling programs in several languages, including Ada and
1102 C. It assumes that you have given it an Ada program if the file extension is
1103 either @file{.ads} or @file{.adb}, and it will then call
1104 the GNAT compiler to compile the specified file.
1105
1106 @ifclear vms
1107 The @option{-c} switch is required. It tells @command{gcc} to only do a
1108 compilation. (For C programs, @command{gcc} can also do linking, but this
1109 capability is not used directly for Ada programs, so the @option{-c}
1110 switch must always be present.)
1111 @end ifclear
1112
1113 This compile command generates a file
1114 @file{hello.o}, which is the object
1115 file corresponding to your Ada program. It also generates
1116 an ``Ada Library Information'' file @file{hello.ali},
1117 which contains additional information used to check
1118 that an Ada program is consistent.
1119 To build an executable file,
1120 use @code{gnatbind} to bind the program
1121 and @command{gnatlink} to link it. The
1122 argument to both @code{gnatbind} and @command{gnatlink} is the name of the
1123 @file{ALI} file, but the default extension of @file{.ali} can
1124 be omitted. This means that in the most common case, the argument
1125 is simply the name of the main program:
1126
1127 @smallexample
1128 $ gnatbind hello
1129 $ gnatlink hello
1130 @end smallexample
1131
1132 @noindent
1133 A simpler method of carrying out these steps is to use
1134 @command{gnatmake},
1135 a master program that invokes all the required
1136 compilation, binding and linking tools in the correct order. In particular,
1137 @command{gnatmake} automatically recompiles any sources that have been
1138 modified since they were last compiled, or sources that depend
1139 on such modified sources, so that ``version skew'' is avoided.
1140 @cindex Version skew (avoided by @command{gnatmake})
1141
1142 @smallexample
1143 $ gnatmake hello.adb
1144 @end smallexample
1145
1146 @noindent
1147 The result is an executable program called @file{hello}, which can be
1148 run by entering:
1149
1150 @smallexample
1151 $ ^hello^RUN HELLO^
1152 @end smallexample
1153
1154 @noindent
1155 assuming that the current directory is on the search path
1156 for executable programs.
1157
1158 @noindent
1159 and, if all has gone well, you will see
1160
1161 @smallexample
1162 Hello WORLD!
1163 @end smallexample
1164
1165 @noindent
1166 appear in response to this command.
1167
1168 @c ****************************************
1169 @node Running a Program with Multiple Units
1170 @section Running a Program with Multiple Units
1171
1172 @noindent
1173 Consider a slightly more complicated example that has three files: a
1174 main program, and the spec and body of a package:
1175
1176 @smallexample @c ada
1177 @cartouche
1178 @group
1179 package Greetings is
1180    procedure Hello;
1181    procedure Goodbye;
1182 end Greetings;
1183
1184 with Ada.Text_IO; use Ada.Text_IO;
1185 package body Greetings is
1186    procedure Hello is
1187    begin
1188       Put_Line ("Hello WORLD!");
1189    end Hello;
1190
1191    procedure Goodbye is
1192    begin
1193       Put_Line ("Goodbye WORLD!");
1194    end Goodbye;
1195 end Greetings;
1196 @end group
1197
1198 @group
1199 with Greetings;
1200 procedure Gmain is
1201 begin
1202    Greetings.Hello;
1203    Greetings.Goodbye;
1204 end Gmain;
1205 @end group
1206 @end cartouche
1207 @end smallexample
1208
1209 @noindent
1210 Following the one-unit-per-file rule, place this program in the
1211 following three separate files:
1212
1213 @table @file
1214 @item greetings.ads
1215 spec of package @code{Greetings}
1216
1217 @item greetings.adb
1218 body of package @code{Greetings}
1219
1220 @item gmain.adb
1221 body of main program
1222 @end table
1223
1224 @noindent
1225 To build an executable version of
1226 this program, we could use four separate steps to compile, bind, and link
1227 the program, as follows:
1228
1229 @smallexample
1230 $ gcc -c gmain.adb
1231 $ gcc -c greetings.adb
1232 $ gnatbind gmain
1233 $ gnatlink gmain
1234 @end smallexample
1235
1236 @noindent
1237 Note that there is no required order of compilation when using GNAT.
1238 In particular it is perfectly fine to compile the main program first.
1239 Also, it is not necessary to compile package specs in the case where
1240 there is an accompanying body; you only need to compile the body. If you want
1241 to submit these files to the compiler for semantic checking and not code
1242 generation, then use the
1243 @option{-gnatc} switch:
1244
1245 @smallexample
1246 $ gcc -c greetings.ads -gnatc
1247 @end smallexample
1248
1249 @noindent
1250 Although the compilation can be done in separate steps as in the
1251 above example, in practice it is almost always more convenient
1252 to use the @command{gnatmake} tool. All you need to know in this case
1253 is the name of the main program's source file. The effect of the above four
1254 commands can be achieved with a single one:
1255
1256 @smallexample
1257 $ gnatmake gmain.adb
1258 @end smallexample
1259
1260 @noindent
1261 In the next section we discuss the advantages of using @command{gnatmake} in
1262 more detail.
1263
1264 @c *****************************
1265 @node Using the gnatmake Utility
1266 @section Using the @command{gnatmake} Utility
1267
1268 @noindent
1269 If you work on a program by compiling single components at a time using
1270 @command{gcc}, you typically keep track of the units you modify. In order to
1271 build a consistent system, you compile not only these units, but also any
1272 units that depend on the units you have modified.
1273 For example, in the preceding case,
1274 if you edit @file{gmain.adb}, you only need to recompile that file. But if
1275 you edit @file{greetings.ads}, you must recompile both
1276 @file{greetings.adb} and @file{gmain.adb}, because both files contain
1277 units that depend on @file{greetings.ads}.
1278
1279 @code{gnatbind} will warn you if you forget one of these compilation
1280 steps, so that it is impossible to generate an inconsistent program as a
1281 result of forgetting to do a compilation. Nevertheless it is tedious and
1282 error-prone to keep track of dependencies among units.
1283 One approach to handle the dependency-bookkeeping is to use a
1284 makefile. However, makefiles present maintenance problems of their own:
1285 if the dependencies change as you change the program, you must make
1286 sure that the makefile is kept up-to-date manually, which is also an
1287 error-prone process.
1288
1289 The @command{gnatmake} utility takes care of these details automatically.
1290 Invoke it using either one of the following forms:
1291
1292 @smallexample
1293 $ gnatmake gmain.adb
1294 $ gnatmake ^gmain^GMAIN^
1295 @end smallexample
1296
1297 @noindent
1298 The argument is the name of the file containing the main program;
1299 you may omit the extension. @command{gnatmake}
1300 examines the environment, automatically recompiles any files that need
1301 recompiling, and binds and links the resulting set of object files,
1302 generating the executable file, @file{^gmain^GMAIN.EXE^}.
1303 In a large program, it
1304 can be extremely helpful to use @command{gnatmake}, because working out by hand
1305 what needs to be recompiled can be difficult.
1306
1307 Note that @command{gnatmake}
1308 takes into account all the Ada rules that
1309 establish dependencies among units. These include dependencies that result
1310 from inlining subprogram bodies, and from
1311 generic instantiation. Unlike some other
1312 Ada make tools, @command{gnatmake} does not rely on the dependencies that were
1313 found by the compiler on a previous compilation, which may possibly
1314 be wrong when sources change. @command{gnatmake} determines the exact set of
1315 dependencies from scratch each time it is run.
1316
1317 @ifset vms
1318 @node Editing with Emacs
1319 @section Editing with Emacs
1320 @cindex Emacs
1321
1322 @noindent
1323 Emacs is an extensible self-documenting text editor that is available in a
1324 separate VMSINSTAL kit.
1325
1326 Invoke Emacs by typing @kbd{Emacs} at the command prompt. To get started,
1327 click on the Emacs Help menu and run the Emacs Tutorial.
1328 In a character cell terminal, Emacs help is invoked with @kbd{Ctrl-h} (also
1329 written as @kbd{C-h}), and the tutorial by @kbd{C-h t}.
1330
1331 Documentation on Emacs and other tools is available in Emacs under the
1332 pull-down menu button: @code{Help - Info}. After selecting @code{Info},
1333 use the middle mouse button to select a topic (e.g.@: Emacs).
1334
1335 In a character cell terminal, do @kbd{C-h i} to invoke info, and then @kbd{m}
1336 (stands for menu) followed by the menu item desired, as in @kbd{m Emacs}, to
1337 get to the Emacs manual.
1338 Help on Emacs is also available by typing @kbd{HELP EMACS} at the DCL command
1339 prompt.
1340
1341 The tutorial is highly recommended in order to learn the intricacies of Emacs,
1342 which is sufficiently extensible to provide for a complete programming
1343 environment and shell for the sophisticated user.
1344 @end ifset
1345
1346 @ifclear vms
1347 @node Introduction to GPS
1348 @section Introduction to GPS
1349 @cindex GPS (GNAT Programming Studio)
1350 @cindex GNAT Programming Studio (GPS)
1351 @noindent
1352 Although the command line interface (@command{gnatmake}, etc.) alone
1353 is sufficient, a graphical Interactive Development
1354 Environment can make it easier for you to compose, navigate, and debug
1355 programs.  This section describes the main features of GPS
1356 (``GNAT Programming Studio''), the GNAT graphical IDE.
1357 You will see how to use GPS to build and debug an executable, and
1358 you will also learn some of the basics of the GNAT ``project'' facility.
1359
1360 GPS enables you to do much more than is presented here;
1361 e.g., you can produce a call graph, interface to a third-party
1362 Version Control System, and inspect the generated assembly language
1363 for a program.
1364 Indeed, GPS also supports languages other than Ada.
1365 Such additional information, and an explanation of all of the GPS menu
1366 items. may be found in the on-line help, which includes
1367 a user's guide and a tutorial (these are also accessible from the GNAT
1368 startup menu).
1369
1370 @menu
1371 * Building a New Program with GPS::
1372 * Simple Debugging with GPS::
1373 @end menu
1374
1375 @node Building a New Program with GPS
1376 @subsection Building a New Program with GPS
1377 @noindent
1378 GPS invokes the GNAT compilation tools using information
1379 contained in a @emph{project} (also known as a @emph{project file}):
1380 a collection of properties such
1381 as source directories, identities of main subprograms, tool switches, etc.,
1382 and their associated values.
1383 See @ref{GNAT Project Manager} for details.
1384 In order to run GPS, you will need to either create a new project
1385 or else open an existing one.
1386
1387 This section will explain how you can use GPS to create a project,
1388 to associate Ada source files with a project, and to build and run
1389 programs.
1390
1391 @enumerate
1392 @item @emph{Creating a project}
1393
1394 Invoke GPS, either from the command line or the platform's IDE.
1395 After it starts, GPS will display a ``Welcome'' screen with three
1396 radio buttons:
1397
1398 @itemize @bullet
1399 @item
1400 @code{Start with default project in directory}
1401
1402 @item
1403 @code{Create new project with wizard}
1404
1405 @item
1406 @code{Open existing project}
1407 @end itemize
1408
1409 @noindent
1410 Select @code{Create new project with wizard} and press @code{OK}.
1411 A new window will appear.  In the text box labeled with
1412 @code{Enter the name of the project to create}, type @file{sample}
1413 as the project name.
1414 In the next box, browse to choose the directory in which you
1415 would like to create the project file.
1416 After selecting an appropriate directory, press @code{Forward}.
1417
1418 A window will appear with the title
1419 @code{Version Control System Configuration}.
1420 Simply press @code{Forward}.
1421
1422 A window will appear with the title
1423 @code{Please select the source directories for this project}.
1424 The directory that you specified for the project file will be selected
1425 by default as the one to use for sources; simply press @code{Forward}.
1426
1427 A window will appear with the title
1428 @code{Please select the build directory for this project}.
1429 The directory that you specified for the project file will be selected
1430 by default for object files and executables;
1431 simply press @code{Forward}.
1432
1433 A window will appear with the title
1434 @code{Please select the main units for this project}.
1435 You will supply this information later, after creating the source file.
1436 Simply press @code{Forward} for now.
1437
1438 A window will appear with the title
1439 @code{Please select the switches to build the project}.
1440 Press @code{Apply}.  This will create a project file named
1441 @file{sample.prj} in the directory that you had specified.
1442
1443 @item @emph{Creating and saving the source file}
1444
1445 After you create the new project, a GPS window will appear, which is
1446 partitioned into two main sections:
1447
1448 @itemize @bullet
1449 @item
1450 A @emph{Workspace area}, initially greyed out, which you will use for
1451 creating and editing source files
1452
1453 @item
1454 Directly below, a @emph{Messages area}, which initially displays a
1455 ``Welcome'' message.
1456 (If the Messages area is not visible, drag its border upward to expand it.)
1457 @end itemize
1458
1459 @noindent
1460 Select @code{File} on the menu bar, and then the @code{New} command.
1461 The Workspace area will become white, and you can now
1462 enter the source program explicitly.
1463 Type the following text
1464
1465 @smallexample @c ada
1466 @group
1467 with Ada.Text_IO; use Ada.Text_IO;
1468 procedure Hello is
1469 begin
1470   Put_Line("Hello from GPS!");
1471 end Hello;
1472 @end group
1473 @end smallexample
1474
1475 @noindent
1476 Select @code{File}, then @code{Save As}, and enter the source file name
1477 @file{hello.adb}.
1478 The file will be saved in the same directory you specified as the
1479 location of the default project file.
1480
1481 @item @emph{Updating the project file}
1482
1483 You need to add the new source file to the project.
1484 To do this, select
1485 the @code{Project} menu and then @code{Edit project properties}.
1486 Click the @code{Main files} tab on the left, and then the
1487 @code{Add} button.
1488 Choose @file{hello.adb} from the list, and press @code{Open}.
1489 The project settings window will reflect this action.
1490 Click @code{OK}.
1491
1492 @item @emph{Building and running the program}
1493
1494 In the main GPS window, now choose the @code{Build} menu, then @code{Make},
1495 and select @file{hello.adb}.
1496 The Messages window will display the resulting invocations of @command{gcc},
1497 @command{gnatbind}, and @command{gnatlink}
1498 (reflecting the default switch settings from the
1499 project file that you created) and then a ``successful compilation/build''
1500 message.
1501
1502 To run the program, choose the @code{Build} menu, then @code{Run}, and
1503 select @command{hello}.
1504 An @emph{Arguments Selection} window will appear.
1505 There are no command line arguments, so just click @code{OK}.
1506
1507 The Messages window will now display the program's output (the string
1508 @code{Hello from GPS}), and at the bottom of the GPS window a status
1509 update is displayed (@code{Run: hello}).
1510 Close the GPS window (or select @code{File}, then @code{Exit}) to
1511 terminate this GPS session.
1512 @end enumerate
1513
1514 @node Simple Debugging with GPS
1515 @subsection Simple Debugging with GPS
1516 @noindent
1517 This section illustrates basic debugging techniques (setting breakpoints,
1518 examining/modifying variables, single stepping).
1519
1520 @enumerate
1521 @item @emph{Opening a project}
1522
1523 Start GPS and select @code{Open existing project}; browse to
1524 specify the project file @file{sample.prj} that you had created in the
1525 earlier example.
1526
1527 @item @emph{Creating a source file}
1528
1529 Select @code{File}, then @code{New}, and type in the following program:
1530
1531 @smallexample @c ada
1532 @group
1533 with Ada.Text_IO; use Ada.Text_IO;
1534 procedure Example is
1535    Line : String (1..80);
1536    N    : Natural;
1537 begin
1538    Put_Line("Type a line of text at each prompt; an empty line to exit");
1539    loop
1540       Put(": ");
1541       Get_Line (Line, N);
1542       Put_Line (Line (1..N) );
1543       exit when N=0;
1544    end loop;
1545 end Example;
1546 @end group
1547 @end smallexample
1548
1549 @noindent
1550 Select @code{File}, then @code{Save as}, and enter the file name
1551 @file{example.adb}.
1552
1553 @item @emph{Updating the project file}
1554
1555 Add @code{Example} as a new main unit for the project:
1556 @enumerate a
1557 @item
1558 Select @code{Project}, then @code{Edit Project Properties}.
1559
1560 @item
1561 Select the @code{Main files} tab, click @code{Add}, then
1562 select the file @file{example.adb} from the list, and
1563 click @code{Open}.
1564 You will see the file name appear in the list of main units
1565
1566 @item
1567 Click @code{OK}
1568 @end enumerate
1569
1570 @item @emph{Building/running the executable}
1571
1572 To build the executable
1573 select @code{Build}, then @code{Make}, and then choose @file{example.adb}.
1574
1575 Run the program to see its effect (in the Messages area).
1576 Each line that you enter is displayed; an empty line will
1577 cause the loop to exit and the program to terminate.
1578
1579 @item @emph{Debugging the program}
1580
1581 Note that the @option{-g} switches to @command{gcc} and @command{gnatlink},
1582 which are required for debugging, are on by default when you create
1583 a new project.
1584 Thus unless you intentionally remove these settings, you will be able
1585 to debug any program that you develop using GPS.
1586
1587 @enumerate a
1588 @item @emph{Initializing}
1589
1590 Select @code{Debug}, then @code{Initialize}, then @file{example}
1591
1592 @item @emph{Setting a breakpoint}
1593
1594 After performing the initialization step, you will observe a small
1595 icon to the right of each line number.
1596 This serves as a toggle for breakpoints; clicking the icon will
1597 set a breakpoint at the corresponding line (the icon will change to
1598 a red circle with an ``x''), and clicking it again
1599 will remove the breakpoint / reset the icon.
1600
1601 For purposes of this example, set a breakpoint at line 10 (the
1602 statement @code{Put_Line@ (Line@ (1..N));}
1603
1604 @item @emph{Starting program execution}
1605
1606 Select @code{Debug}, then @code{Run}.  When the
1607 @code{Program Arguments} window appears, click @code{OK}.
1608 A console window will appear; enter some line of text,
1609 e.g.@: @code{abcde}, at the prompt.
1610 The program will pause execution when it gets to the
1611 breakpoint, and the corresponding line is highlighted.
1612
1613 @item @emph{Examining a variable}
1614
1615 Move the mouse over one of the occurrences of the variable @code{N}.
1616 You will see the value (5) displayed, in ``tool tip'' fashion.
1617 Right click on @code{N}, select @code{Debug}, then select @code{Display N}.
1618 You will see information about @code{N} appear in the @code{Debugger Data}
1619 pane, showing the value as 5.
1620
1621 @item @emph{Assigning a new value to a variable}
1622
1623 Right click on the @code{N} in the @code{Debugger Data} pane, and
1624 select @code{Set value of N}.
1625 When the input window appears, enter the value @code{4} and click
1626 @code{OK}.
1627 This value does not automatically appear in the @code{Debugger Data}
1628 pane; to see it, right click again on the @code{N} in the
1629 @code{Debugger Data} pane and select @code{Update value}.
1630 The new value, 4, will appear in red.
1631
1632 @item @emph{Single stepping}
1633
1634 Select @code{Debug}, then @code{Next}.
1635 This will cause the next statement to be executed, in this case the
1636 call of @code{Put_Line} with the string slice.
1637 Notice in the console window that the displayed string is simply
1638 @code{abcd} and not @code{abcde} which you had entered.
1639 This is because the upper bound of the slice is now 4 rather than 5.
1640
1641 @item @emph{Removing a breakpoint}
1642
1643 Toggle the breakpoint icon at line 10.
1644
1645 @item @emph{Resuming execution from a breakpoint}
1646
1647 Select @code{Debug}, then @code{Continue}.
1648 The program will reach the next iteration of the loop, and
1649 wait for input after displaying the prompt.
1650 This time, just hit the @kbd{Enter} key.
1651 The value of @code{N} will be 0, and the program will terminate.
1652 The console window will disappear.
1653 @end enumerate
1654 @end enumerate
1655 @end ifclear
1656
1657 @node The GNAT Compilation Model
1658 @chapter The GNAT Compilation Model
1659 @cindex GNAT compilation model
1660 @cindex Compilation model
1661
1662 @menu
1663 * Source Representation::
1664 * Foreign Language Representation::
1665 * File Naming Rules::
1666 * Using Other File Names::
1667 * Alternative File Naming Schemes::
1668 * Generating Object Files::
1669 * Source Dependencies::
1670 * The Ada Library Information Files::
1671 * Binding an Ada Program::
1672 * Mixed Language Programming::
1673 @ifclear vms
1674 * Building Mixed Ada & C++ Programs::
1675 * Comparison between GNAT and C/C++ Compilation Models::
1676 @end ifclear
1677 * Comparison between GNAT and Conventional Ada Library Models::
1678 @ifset vms
1679 * Placement of temporary files::
1680 @end ifset
1681 @end menu
1682
1683 @noindent
1684 This chapter describes the compilation model used by GNAT. Although
1685 similar to that used by other languages, such as C and C++, this model
1686 is substantially different from the traditional Ada compilation models,
1687 which are based on a library. The model is initially described without
1688 reference to the library-based model. If you have not previously used an
1689 Ada compiler, you need only read the first part of this chapter. The
1690 last section describes and discusses the differences between the GNAT
1691 model and the traditional Ada compiler models. If you have used other
1692 Ada compilers, this section will help you to understand those
1693 differences, and the advantages of the GNAT model.
1694
1695 @node Source Representation
1696 @section Source Representation
1697 @cindex Latin-1
1698
1699 @noindent
1700 Ada source programs are represented in standard text files, using
1701 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1702 7-bit ASCII set, plus additional characters used for
1703 representing foreign languages (@pxref{Foreign Language Representation}
1704 for support of non-USA character sets). The format effector characters
1705 are represented using their standard ASCII encodings, as follows:
1706
1707 @table @code
1708 @item VT
1709 @findex VT
1710 Vertical tab, @code{16#0B#}
1711
1712 @item HT
1713 @findex HT
1714 Horizontal tab, @code{16#09#}
1715
1716 @item CR
1717 @findex CR
1718 Carriage return, @code{16#0D#}
1719
1720 @item LF
1721 @findex LF
1722 Line feed, @code{16#0A#}
1723
1724 @item FF
1725 @findex FF
1726 Form feed, @code{16#0C#}
1727 @end table
1728
1729 @noindent
1730 Source files are in standard text file format. In addition, GNAT will
1731 recognize a wide variety of stream formats, in which the end of
1732 physical lines is marked by any of the following sequences:
1733 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1734 in accommodating files that are imported from other operating systems.
1735
1736 @cindex End of source file
1737 @cindex Source file, end
1738 @findex SUB
1739 The end of a source file is normally represented by the physical end of
1740 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1741 recognized as signalling the end of the source file. Again, this is
1742 provided for compatibility with other operating systems where this
1743 code is used to represent the end of file.
1744
1745 Each file contains a single Ada compilation unit, including any pragmas
1746 associated with the unit. For example, this means you must place a
1747 package declaration (a package @dfn{spec}) and the corresponding body in
1748 separate files. An Ada @dfn{compilation} (which is a sequence of
1749 compilation units) is represented using a sequence of files. Similarly,
1750 you will place each subunit or child unit in a separate file.
1751
1752 @node Foreign Language Representation
1753 @section Foreign Language Representation
1754
1755 @noindent
1756 GNAT supports the standard character sets defined in Ada as well as
1757 several other non-standard character sets for use in localized versions
1758 of the compiler (@pxref{Character Set Control}).
1759 @menu
1760 * Latin-1::
1761 * Other 8-Bit Codes::
1762 * Wide Character Encodings::
1763 @end menu
1764
1765 @node Latin-1
1766 @subsection Latin-1
1767 @cindex Latin-1
1768
1769 @noindent
1770 The basic character set is Latin-1. This character set is defined by ISO
1771 standard 8859, part 1. The lower half (character codes @code{16#00#}
1772 @dots{} @code{16#7F#)} is identical to standard ASCII coding, but the upper
1773 half is used to represent additional characters. These include extended letters
1774 used by European languages, such as French accents, the vowels with umlauts
1775 used in German, and the extra letter A-ring used in Swedish.
1776
1777 @findex Ada.Characters.Latin_1
1778 For a complete list of Latin-1 codes and their encodings, see the source
1779 file of library unit @code{Ada.Characters.Latin_1} in file
1780 @file{a-chlat1.ads}.
1781 You may use any of these extended characters freely in character or
1782 string literals. In addition, the extended characters that represent
1783 letters can be used in identifiers.
1784
1785 @node Other 8-Bit Codes
1786 @subsection Other 8-Bit Codes
1787
1788 @noindent
1789 GNAT also supports several other 8-bit coding schemes:
1790
1791 @table @asis
1792 @item ISO 8859-2 (Latin-2)
1793 @cindex Latin-2
1794 @cindex ISO 8859-2
1795 Latin-2 letters allowed in identifiers, with uppercase and lowercase
1796 equivalence.
1797
1798 @item ISO 8859-3 (Latin-3)
1799 @cindex Latin-3
1800 @cindex ISO 8859-3
1801 Latin-3 letters allowed in identifiers, with uppercase and lowercase
1802 equivalence.
1803
1804 @item ISO 8859-4 (Latin-4)
1805 @cindex Latin-4
1806 @cindex ISO 8859-4
1807 Latin-4 letters allowed in identifiers, with uppercase and lowercase
1808 equivalence.
1809
1810 @item ISO 8859-5 (Cyrillic)
1811 @cindex ISO 8859-5
1812 @cindex Cyrillic
1813 ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
1814 lowercase equivalence.
1815
1816 @item ISO 8859-15 (Latin-9)
1817 @cindex ISO 8859-15
1818 @cindex Latin-9
1819 ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
1820 lowercase equivalence
1821
1822 @item IBM PC (code page 437)
1823 @cindex code page 437
1824 This code page is the normal default for PCs in the U.S. It corresponds
1825 to the original IBM PC character set. This set has some, but not all, of
1826 the extended Latin-1 letters, but these letters do not have the same
1827 encoding as Latin-1. In this mode, these letters are allowed in
1828 identifiers with uppercase and lowercase equivalence.
1829
1830 @item IBM PC (code page 850)
1831 @cindex code page 850
1832 This code page is a modification of 437 extended to include all the
1833 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
1834 mode, all these letters are allowed in identifiers with uppercase and
1835 lowercase equivalence.
1836
1837 @item Full Upper 8-bit
1838 Any character in the range 80-FF allowed in identifiers, and all are
1839 considered distinct. In other words, there are no uppercase and lowercase
1840 equivalences in this range. This is useful in conjunction with
1841 certain encoding schemes used for some foreign character sets (e.g.,
1842 the typical method of representing Chinese characters on the PC).
1843
1844 @item No Upper-Half
1845 No upper-half characters in the range 80-FF are allowed in identifiers.
1846 This gives Ada 83 compatibility for identifier names.
1847 @end table
1848
1849 @noindent
1850 For precise data on the encodings permitted, and the uppercase and lowercase
1851 equivalences that are recognized, see the file @file{csets.adb} in
1852 the GNAT compiler sources. You will need to obtain a full source release
1853 of GNAT to obtain this file.
1854
1855 @node Wide Character Encodings
1856 @subsection Wide Character Encodings
1857
1858 @noindent
1859 GNAT allows wide character codes to appear in character and string
1860 literals, and also optionally in identifiers, by means of the following
1861 possible encoding schemes:
1862
1863 @table @asis
1864
1865 @item Hex Coding
1866 In this encoding, a wide character is represented by the following five
1867 character sequence:
1868
1869 @smallexample
1870 ESC a b c d
1871 @end smallexample
1872
1873 @noindent
1874 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1875 characters (using uppercase letters) of the wide character code. For
1876 example, ESC A345 is used to represent the wide character with code
1877 @code{16#A345#}.
1878 This scheme is compatible with use of the full Wide_Character set.
1879
1880 @item Upper-Half Coding
1881 @cindex Upper-Half Coding
1882 The wide character with encoding @code{16#abcd#} where the upper bit is on
1883 (in other words, ``a'' is in the range 8-F) is represented as two bytes,
1884 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
1885 character, but is not required to be in the upper half. This method can
1886 be also used for shift-JIS or EUC, where the internal coding matches the
1887 external coding.
1888
1889 @item Shift JIS Coding
1890 @cindex Shift JIS Coding
1891 A wide character is represented by a two-character sequence,
1892 @code{16#ab#} and
1893 @code{16#cd#}, with the restrictions described for upper-half encoding as
1894 described above. The internal character code is the corresponding JIS
1895 character according to the standard algorithm for Shift-JIS
1896 conversion. Only characters defined in the JIS code set table can be
1897 used with this encoding method.
1898
1899 @item EUC Coding
1900 @cindex EUC Coding
1901 A wide character is represented by a two-character sequence
1902 @code{16#ab#} and
1903 @code{16#cd#}, with both characters being in the upper half. The internal
1904 character code is the corresponding JIS character according to the EUC
1905 encoding algorithm. Only characters defined in the JIS code set table
1906 can be used with this encoding method.
1907
1908 @item UTF-8 Coding
1909 A wide character is represented using
1910 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1911 10646-1/Am.2. Depending on the character value, the representation
1912 is a one, two, or three byte sequence:
1913 @smallexample
1914 @iftex
1915 @leftskip=.7cm
1916 @end iftex
1917 16#0000#-16#007f#: 2#0@var{xxxxxxx}#
1918 16#0080#-16#07ff#: 2#110@var{xxxxx}# 2#10@var{xxxxxx}#
1919 16#0800#-16#ffff#: 2#1110@var{xxxx}# 2#10@var{xxxxxx}# 2#10@var{xxxxxx}#
1920
1921 @end smallexample
1922
1923 @noindent
1924 where the @var{xxx} bits correspond to the left-padded bits of the
1925 16-bit character value. Note that all lower half ASCII characters
1926 are represented as ASCII bytes and all upper half characters and
1927 other wide characters are represented as sequences of upper-half
1928 (The full UTF-8 scheme allows for encoding 31-bit characters as
1929 6-byte sequences, but in this implementation, all UTF-8 sequences
1930 of four or more bytes length will be treated as illegal).
1931 @item Brackets Coding
1932 In this encoding, a wide character is represented by the following eight
1933 character sequence:
1934
1935 @smallexample
1936 [ " a b c d " ]
1937 @end smallexample
1938
1939 @noindent
1940 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1941 characters (using uppercase letters) of the wide character code. For
1942 example, [``A345''] is used to represent the wide character with code
1943 @code{16#A345#}. It is also possible (though not required) to use the
1944 Brackets coding for upper half characters. For example, the code
1945 @code{16#A3#} can be represented as @code{[``A3'']}.
1946
1947 This scheme is compatible with use of the full Wide_Character set,
1948 and is also the method used for wide character encoding in the standard
1949 ACVC (Ada Compiler Validation Capability) test suite distributions.
1950
1951 @end table
1952
1953 @noindent
1954 Note: Some of these coding schemes do not permit the full use of the
1955 Ada character set. For example, neither Shift JIS, nor EUC allow the
1956 use of the upper half of the Latin-1 set.
1957
1958 @node File Naming Rules
1959 @section File Naming Rules
1960
1961 @noindent
1962 The default file name is determined by the name of the unit that the
1963 file contains. The name is formed by taking the full expanded name of
1964 the unit and replacing the separating dots with hyphens and using
1965 ^lowercase^uppercase^ for all letters.
1966
1967 An exception arises if the file name generated by the above rules starts
1968 with one of the characters
1969 @ifset vms
1970 @samp{A}, @samp{G}, @samp{I}, or @samp{S},
1971 @end ifset
1972 @ifclear vms
1973 @samp{a}, @samp{g}, @samp{i}, or @samp{s},
1974 @end ifclear
1975 and the second character is a
1976 minus. In this case, the character ^tilde^dollar sign^ is used in place
1977 of the minus. The reason for this special rule is to avoid clashes with
1978 the standard names for child units of the packages System, Ada,
1979 Interfaces, and GNAT, which use the prefixes
1980 @ifset vms
1981 @samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},
1982 @end ifset
1983 @ifclear vms
1984 @samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},
1985 @end ifclear
1986 respectively.
1987
1988 The file extension is @file{.ads} for a spec and
1989 @file{.adb} for a body. The following list shows some
1990 examples of these rules.
1991
1992 @table @file
1993 @item main.ads
1994 Main (spec)
1995 @item main.adb
1996 Main (body)
1997 @item arith_functions.ads
1998 Arith_Functions (package spec)
1999 @item arith_functions.adb
2000 Arith_Functions (package body)
2001 @item func-spec.ads
2002 Func.Spec (child package spec)
2003 @item func-spec.adb
2004 Func.Spec (child package body)
2005 @item main-sub.adb
2006 Sub (subunit of Main)
2007 @item ^a~bad.adb^A$BAD.ADB^
2008 A.Bad (child package body)
2009 @end table
2010
2011 @noindent
2012 Following these rules can result in excessively long
2013 file names if corresponding
2014 unit names are long (for example, if child units or subunits are
2015 heavily nested). An option is available to shorten such long file names
2016 (called file name ``krunching''). This may be particularly useful when
2017 programs being developed with GNAT are to be used on operating systems
2018 with limited file name lengths. @xref{Using gnatkr}.
2019
2020 Of course, no file shortening algorithm can guarantee uniqueness over
2021 all possible unit names; if file name krunching is used, it is your
2022 responsibility to ensure no name clashes occur. Alternatively you
2023 can specify the exact file names that you want used, as described
2024 in the next section. Finally, if your Ada programs are migrating from a
2025 compiler with a different naming convention, you can use the gnatchop
2026 utility to produce source files that follow the GNAT naming conventions.
2027 (For details @pxref{Renaming Files Using gnatchop}.)
2028
2029 Note: in the case of @code{Windows NT/XP} or @code{OpenVMS} operating
2030 systems, case is not significant. So for example on @code{Windows XP}
2031 if the canonical name is @code{main-sub.adb}, you can use the file name
2032 @code{Main-Sub.adb} instead. However, case is significant for other
2033 operating systems, so for example, if you want to use other than
2034 canonically cased file names on a Unix system, you need to follow
2035 the procedures described in the next section.
2036
2037 @node Using Other File Names
2038 @section Using Other File Names
2039 @cindex File names
2040
2041 @noindent
2042 In the previous section, we have described the default rules used by
2043 GNAT to determine the file name in which a given unit resides. It is
2044 often convenient to follow these default rules, and if you follow them,
2045 the compiler knows without being explicitly told where to find all
2046 the files it needs.
2047
2048 However, in some cases, particularly when a program is imported from
2049 another Ada compiler environment, it may be more convenient for the
2050 programmer to specify which file names contain which units. GNAT allows
2051 arbitrary file names to be used by means of the Source_File_Name pragma.
2052 The form of this pragma is as shown in the following examples:
2053 @cindex Source_File_Name pragma
2054
2055 @smallexample @c ada
2056 @cartouche
2057 pragma Source_File_Name (My_Utilities.Stacks,
2058   Spec_File_Name => "myutilst_a.ada");
2059 pragma Source_File_name (My_Utilities.Stacks,
2060   Body_File_Name => "myutilst.ada");
2061 @end cartouche
2062 @end smallexample
2063
2064 @noindent
2065 As shown in this example, the first argument for the pragma is the unit
2066 name (in this example a child unit). The second argument has the form
2067 of a named association. The identifier
2068 indicates whether the file name is for a spec or a body;
2069 the file name itself is given by a string literal.
2070
2071 The source file name pragma is a configuration pragma, which means that
2072 normally it will be placed in the @file{gnat.adc}
2073 file used to hold configuration
2074 pragmas that apply to a complete compilation environment.
2075 For more details on how the @file{gnat.adc} file is created and used
2076 see @ref{Handling of Configuration Pragmas}.
2077 @cindex @file{gnat.adc}
2078
2079 @ifclear vms
2080 GNAT allows completely arbitrary file names to be specified using the
2081 source file name pragma. However, if the file name specified has an
2082 extension other than @file{.ads} or @file{.adb} it is necessary to use
2083 a special syntax when compiling the file. The name in this case must be
2084 preceded by the special sequence @option{-x} followed by a space and the name
2085 of the language, here @code{ada}, as in:
2086
2087 @smallexample
2088 $ gcc -c -x ada peculiar_file_name.sim
2089 @end smallexample
2090 @end ifclear
2091
2092 @noindent
2093 @command{gnatmake} handles non-standard file names in the usual manner (the
2094 non-standard file name for the main program is simply used as the
2095 argument to gnatmake). Note that if the extension is also non-standard,
2096 then it must be included in the @command{gnatmake} command, it may not
2097 be omitted.
2098
2099 @node Alternative File Naming Schemes
2100 @section Alternative File Naming Schemes
2101 @cindex File naming schemes, alternative
2102 @cindex File names
2103
2104 In the previous section, we described the use of the @code{Source_File_Name}
2105 pragma to allow arbitrary names to be assigned to individual source files.
2106 However, this approach requires one pragma for each file, and especially in
2107 large systems can result in very long @file{gnat.adc} files, and also create
2108 a maintenance problem.
2109
2110 GNAT also provides a facility for specifying systematic file naming schemes
2111 other than the standard default naming scheme previously described. An
2112 alternative scheme for naming is specified by the use of
2113 @code{Source_File_Name} pragmas having the following format:
2114 @cindex Source_File_Name pragma
2115
2116 @smallexample @c ada
2117 pragma Source_File_Name (
2118    Spec_File_Name  => FILE_NAME_PATTERN
2119  @r{[},Casing          => CASING_SPEC@r{]}
2120  @r{[},Dot_Replacement => STRING_LITERAL@r{]});
2121
2122 pragma Source_File_Name (
2123    Body_File_Name  => FILE_NAME_PATTERN
2124  @r{[},Casing          => CASING_SPEC@r{]}
2125  @r{[},Dot_Replacement => STRING_LITERAL@r{]});
2126
2127 pragma Source_File_Name (
2128    Subunit_File_Name  => FILE_NAME_PATTERN
2129  @r{[},Casing             => CASING_SPEC@r{]}
2130  @r{[},Dot_Replacement    => STRING_LITERAL@r{]});
2131
2132 FILE_NAME_PATTERN ::= STRING_LITERAL
2133 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
2134 @end smallexample
2135
2136 @noindent
2137 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
2138 It contains a single asterisk character, and the unit name is substituted
2139 systematically for this asterisk. The optional parameter
2140 @code{Casing} indicates
2141 whether the unit name is to be all upper-case letters, all lower-case letters,
2142 or mixed-case. If no
2143 @code{Casing} parameter is used, then the default is all
2144 ^lower-case^upper-case^.
2145
2146 The optional @code{Dot_Replacement} string is used to replace any periods
2147 that occur in subunit or child unit names. If no @code{Dot_Replacement}
2148 argument is used then separating dots appear unchanged in the resulting
2149 file name.
2150 Although the above syntax indicates that the
2151 @code{Casing} argument must appear
2152 before the @code{Dot_Replacement} argument, but it
2153 is also permissible to write these arguments in the opposite order.
2154
2155 As indicated, it is possible to specify different naming schemes for
2156 bodies, specs, and subunits. Quite often the rule for subunits is the
2157 same as the rule for bodies, in which case, there is no need to give
2158 a separate @code{Subunit_File_Name} rule, and in this case the
2159 @code{Body_File_name} rule is used for subunits as well.
2160
2161 The separate rule for subunits can also be used to implement the rather
2162 unusual case of a compilation environment (e.g.@: a single directory) which
2163 contains a subunit and a child unit with the same unit name. Although
2164 both units cannot appear in the same partition, the Ada Reference Manual
2165 allows (but does not require) the possibility of the two units coexisting
2166 in the same environment.
2167
2168 The file name translation works in the following steps:
2169
2170 @itemize @bullet
2171
2172 @item
2173 If there is a specific @code{Source_File_Name} pragma for the given unit,
2174 then this is always used, and any general pattern rules are ignored.
2175
2176 @item
2177 If there is a pattern type @code{Source_File_Name} pragma that applies to
2178 the unit, then the resulting file name will be used if the file exists. If
2179 more than one pattern matches, the latest one will be tried first, and the
2180 first attempt resulting in a reference to a file that exists will be used.
2181
2182 @item
2183 If no pattern type @code{Source_File_Name} pragma that applies to the unit
2184 for which the corresponding file exists, then the standard GNAT default
2185 naming rules are used.
2186
2187 @end itemize
2188
2189 @noindent
2190 As an example of the use of this mechanism, consider a commonly used scheme
2191 in which file names are all lower case, with separating periods copied
2192 unchanged to the resulting file name, and specs end with @file{.1.ada}, and
2193 bodies end with @file{.2.ada}. GNAT will follow this scheme if the following
2194 two pragmas appear:
2195
2196 @smallexample @c ada
2197 pragma Source_File_Name
2198   (Spec_File_Name => "*.1.ada");
2199 pragma Source_File_Name
2200   (Body_File_Name => "*.2.ada");
2201 @end smallexample
2202
2203 @noindent
2204 The default GNAT scheme is actually implemented by providing the following
2205 default pragmas internally:
2206
2207 @smallexample @c ada
2208 pragma Source_File_Name
2209   (Spec_File_Name => "*.ads", Dot_Replacement => "-");
2210 pragma Source_File_Name
2211   (Body_File_Name => "*.adb", Dot_Replacement => "-");
2212 @end smallexample
2213
2214 @noindent
2215 Our final example implements a scheme typically used with one of the
2216 Ada 83 compilers, where the separator character for subunits was ``__''
2217 (two underscores), specs were identified by adding @file{_.ADA}, bodies
2218 by adding @file{.ADA}, and subunits by
2219 adding @file{.SEP}. All file names were
2220 upper case. Child units were not present of course since this was an
2221 Ada 83 compiler, but it seems reasonable to extend this scheme to use
2222 the same double underscore separator for child units.
2223
2224 @smallexample @c ada
2225 pragma Source_File_Name
2226   (Spec_File_Name => "*_.ADA",
2227    Dot_Replacement => "__",
2228    Casing = Uppercase);
2229 pragma Source_File_Name
2230   (Body_File_Name => "*.ADA",
2231    Dot_Replacement => "__",
2232    Casing = Uppercase);
2233 pragma Source_File_Name
2234   (Subunit_File_Name => "*.SEP",
2235    Dot_Replacement => "__",
2236    Casing = Uppercase);
2237 @end smallexample
2238
2239 @node Generating Object Files
2240 @section Generating Object Files
2241
2242 @noindent
2243 An Ada program consists of a set of source files, and the first step in
2244 compiling the program is to generate the corresponding object files.
2245 These are generated by compiling a subset of these source files.
2246 The files you need to compile are the following:
2247
2248 @itemize @bullet
2249 @item
2250 If a package spec has no body, compile the package spec to produce the
2251 object file for the package.
2252
2253 @item
2254 If a package has both a spec and a body, compile the body to produce the
2255 object file for the package. The source file for the package spec need
2256 not be compiled in this case because there is only one object file, which
2257 contains the code for both the spec and body of the package.
2258
2259 @item
2260 For a subprogram, compile the subprogram body to produce the object file
2261 for the subprogram. The spec, if one is present, is as usual in a
2262 separate file, and need not be compiled.
2263
2264 @item
2265 @cindex Subunits
2266 In the case of subunits, only compile the parent unit. A single object
2267 file is generated for the entire subunit tree, which includes all the
2268 subunits.
2269
2270 @item
2271 Compile child units independently of their parent units
2272 (though, of course, the spec of all the ancestor unit must be present in order
2273 to compile a child unit).
2274
2275 @item
2276 @cindex Generics
2277 Compile generic units in the same manner as any other units. The object
2278 files in this case are small dummy files that contain at most the
2279 flag used for elaboration checking. This is because GNAT always handles generic
2280 instantiation by means of macro expansion. However, it is still necessary to
2281 compile generic units, for dependency checking and elaboration purposes.
2282 @end itemize
2283
2284 @noindent
2285 The preceding rules describe the set of files that must be compiled to
2286 generate the object files for a program. Each object file has the same
2287 name as the corresponding source file, except that the extension is
2288 @file{.o} as usual.
2289
2290 You may wish to compile other files for the purpose of checking their
2291 syntactic and semantic correctness. For example, in the case where a
2292 package has a separate spec and body, you would not normally compile the
2293 spec. However, it is convenient in practice to compile the spec to make
2294 sure it is error-free before compiling clients of this spec, because such
2295 compilations will fail if there is an error in the spec.
2296
2297 GNAT provides an option for compiling such files purely for the
2298 purposes of checking correctness; such compilations are not required as
2299 part of the process of building a program. To compile a file in this
2300 checking mode, use the @option{-gnatc} switch.
2301
2302 @node Source Dependencies
2303 @section Source Dependencies
2304
2305 @noindent
2306 A given object file clearly depends on the source file which is compiled
2307 to produce it. Here we are using @dfn{depends} in the sense of a typical
2308 @code{make} utility; in other words, an object file depends on a source
2309 file if changes to the source file require the object file to be
2310 recompiled.
2311 In addition to this basic dependency, a given object may depend on
2312 additional source files as follows:
2313
2314 @itemize @bullet
2315 @item
2316 If a file being compiled @code{with}'s a unit @var{X}, the object file
2317 depends on the file containing the spec of unit @var{X}. This includes
2318 files that are @code{with}'ed implicitly either because they are parents
2319 of @code{with}'ed child units or they are run-time units required by the
2320 language constructs used in a particular unit.
2321
2322 @item
2323 If a file being compiled instantiates a library level generic unit, the
2324 object file depends on both the spec and body files for this generic
2325 unit.
2326
2327 @item
2328 If a file being compiled instantiates a generic unit defined within a
2329 package, the object file depends on the body file for the package as
2330 well as the spec file.
2331
2332 @item
2333 @findex Inline
2334 @cindex @option{-gnatn} switch
2335 If a file being compiled contains a call to a subprogram for which
2336 pragma @code{Inline} applies and inlining is activated with the
2337 @option{-gnatn} switch, the object file depends on the file containing the
2338 body of this subprogram as well as on the file containing the spec. Note
2339 that for inlining to actually occur as a result of the use of this switch,
2340 it is necessary to compile in optimizing mode.
2341
2342 @cindex @option{-gnatN} switch
2343 The use of @option{-gnatN} activates  inlining optimization
2344 that is performed by the front end of the compiler. This inlining does
2345 not require that the code generation be optimized. Like @option{-gnatn},
2346 the use of this switch generates additional dependencies.
2347
2348 When using a gcc-based back end (in practice this means using any version
2349 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
2350 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
2351 Historically front end inlining was more extensive than the gcc back end
2352 inlining, but that is no longer the case.
2353
2354 @item
2355 If an object file @file{O} depends on the proper body of a subunit through
2356 inlining or instantiation, it depends on the parent unit of the subunit.
2357 This means that any modification of the parent unit or one of its subunits
2358 affects the compilation of @file{O}.
2359
2360 @item
2361 The object file for a parent unit depends on all its subunit body files.
2362
2363 @item
2364 The previous two rules meant that for purposes of computing dependencies and
2365 recompilation, a body and all its subunits are treated as an indivisible whole.
2366
2367 @noindent
2368 These rules are applied transitively: if unit @code{A} @code{with}'s
2369 unit @code{B}, whose elaboration calls an inlined procedure in package
2370 @code{C}, the object file for unit @code{A} will depend on the body of
2371 @code{C}, in file @file{c.adb}.
2372
2373 The set of dependent files described by these rules includes all the
2374 files on which the unit is semantically dependent, as dictated by the
2375 Ada language standard. However, it is a superset of what the
2376 standard describes, because it includes generic, inline, and subunit
2377 dependencies.
2378
2379 An object file must be recreated by recompiling the corresponding source
2380 file if any of the source files on which it depends are modified. For
2381 example, if the @code{make} utility is used to control compilation,
2382 the rule for an Ada object file must mention all the source files on
2383 which the object file depends, according to the above definition.
2384 The determination of the necessary
2385 recompilations is done automatically when one uses @command{gnatmake}.
2386 @end itemize
2387
2388 @node The Ada Library Information Files
2389 @section The Ada Library Information Files
2390 @cindex Ada Library Information files
2391 @cindex @file{ALI} files
2392
2393 @noindent
2394 Each compilation actually generates two output files. The first of these
2395 is the normal object file that has a @file{.o} extension. The second is a
2396 text file containing full dependency information. It has the same
2397 name as the source file, but an @file{.ali} extension.
2398 This file is known as the Ada Library Information (@file{ALI}) file.
2399 The following information is contained in the @file{ALI} file.
2400
2401 @itemize @bullet
2402 @item
2403 Version information (indicates which version of GNAT was used to compile
2404 the unit(s) in question)
2405
2406 @item
2407 Main program information (including priority and time slice settings,
2408 as well as the wide character encoding used during compilation).
2409
2410 @item
2411 List of arguments used in the @command{gcc} command for the compilation
2412
2413 @item
2414 Attributes of the unit, including configuration pragmas used, an indication
2415 of whether the compilation was successful, exception model used etc.
2416
2417 @item
2418 A list of relevant restrictions applying to the unit (used for consistency)
2419 checking.
2420
2421 @item
2422 Categorization information (e.g.@: use of pragma @code{Pure}).
2423
2424 @item
2425 Information on all @code{with}'ed units, including presence of
2426 @code{Elaborate} or @code{Elaborate_All} pragmas.
2427
2428 @item
2429 Information from any @code{Linker_Options} pragmas used in the unit
2430
2431 @item
2432 Information on the use of @code{Body_Version} or @code{Version}
2433 attributes in the unit.
2434
2435 @item
2436 Dependency information. This is a list of files, together with
2437 time stamp and checksum information. These are files on which
2438 the unit depends in the sense that recompilation is required
2439 if any of these units are modified.
2440
2441 @item
2442 Cross-reference data. Contains information on all entities referenced
2443 in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
2444 provide cross-reference information.
2445
2446 @end itemize
2447
2448 @noindent
2449 For a full detailed description of the format of the @file{ALI} file,
2450 see the source of the body of unit @code{Lib.Writ}, contained in file
2451 @file{lib-writ.adb} in the GNAT compiler sources.
2452
2453 @node Binding an Ada Program
2454 @section Binding an Ada Program
2455
2456 @noindent
2457 When using languages such as C and C++, once the source files have been
2458 compiled the only remaining step in building an executable program
2459 is linking the object modules together. This means that it is possible to
2460 link an inconsistent version of a program, in which two units have
2461 included different versions of the same header.
2462
2463 The rules of Ada do not permit such an inconsistent program to be built.
2464 For example, if two clients have different versions of the same package,
2465 it is illegal to build a program containing these two clients.
2466 These rules are enforced by the GNAT binder, which also determines an
2467 elaboration order consistent with the Ada rules.
2468
2469 The GNAT binder is run after all the object files for a program have
2470 been created. It is given the name of the main program unit, and from
2471 this it determines the set of units required by the program, by reading the
2472 corresponding ALI files. It generates error messages if the program is
2473 inconsistent or if no valid order of elaboration exists.
2474
2475 If no errors are detected, the binder produces a main program, in Ada by
2476 default, that contains calls to the elaboration procedures of those
2477 compilation unit that require them, followed by
2478 a call to the main program. This Ada program is compiled to generate the
2479 object file for the main program. The name of
2480 the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec
2481 @file{b~@var{xxx}.ads}) where @var{xxx} is the name of the
2482 main program unit.
2483
2484 Finally, the linker is used to build the resulting executable program,
2485 using the object from the main program from the bind step as well as the
2486 object files for the Ada units of the program.
2487
2488 @node Mixed Language Programming
2489 @section Mixed Language Programming
2490 @cindex Mixed Language Programming
2491
2492 @noindent
2493 This section describes how to develop a mixed-language program,
2494 specifically one that comprises units in both Ada and C.
2495
2496 @menu
2497 * Interfacing to C::
2498 * Calling Conventions::
2499 @end menu
2500
2501 @node Interfacing to C
2502 @subsection Interfacing to C
2503 @noindent
2504 Interfacing Ada with a foreign language such as C involves using
2505 compiler directives to import and/or export entity definitions in each
2506 language---using @code{extern} statements in C, for instance, and the
2507 @code{Import}, @code{Export}, and @code{Convention} pragmas in Ada.
2508 A full treatment of these topics is provided in Appendix B, section 1
2509 of the Ada Reference Manual.
2510
2511 There are two ways to build a program using GNAT that contains some Ada
2512 sources and some foreign language sources, depending on whether or not
2513 the main subprogram is written in Ada.  Here is a source example with
2514 the main subprogram in Ada:
2515
2516 @smallexample
2517 /* file1.c */
2518 #include <stdio.h>
2519
2520 void print_num (int num)
2521 @{
2522   printf ("num is %d.\n", num);
2523   return;
2524 @}
2525
2526 /* file2.c */
2527
2528 /* num_from_Ada is declared in my_main.adb */
2529 extern int num_from_Ada;
2530
2531 int get_num (void)
2532 @{
2533   return num_from_Ada;
2534 @}
2535 @end smallexample
2536
2537 @smallexample @c ada
2538 --  my_main.adb
2539 procedure My_Main is
2540
2541    --  Declare then export an Integer entity called num_from_Ada
2542    My_Num : Integer := 10;
2543    pragma Export (C, My_Num, "num_from_Ada");
2544
2545    --  Declare an Ada function spec for Get_Num, then use
2546    --  C function get_num for the implementation.
2547    function Get_Num return Integer;
2548    pragma Import (C, Get_Num, "get_num");
2549
2550    --  Declare an Ada procedure spec for Print_Num, then use
2551    --  C function print_num for the implementation.
2552    procedure Print_Num (Num : Integer);
2553    pragma Import (C, Print_Num, "print_num");
2554
2555 begin
2556    Print_Num (Get_Num);
2557 end My_Main;
2558 @end smallexample
2559
2560 @enumerate
2561 @item
2562 To build this example, first compile the foreign language files to
2563 generate object files:
2564 @smallexample
2565 ^gcc -c file1.c^gcc -c FILE1.C^
2566 ^gcc -c file2.c^gcc -c FILE2.C^
2567 @end smallexample
2568
2569 @item
2570 Then, compile the Ada units to produce a set of object files and ALI
2571 files:
2572 @smallexample
2573 gnatmake ^-c^/ACTIONS=COMPILE^ my_main.adb
2574 @end smallexample
2575
2576 @item
2577 Run the Ada binder on the Ada main program:
2578 @smallexample
2579 gnatbind my_main.ali
2580 @end smallexample
2581
2582 @item
2583 Link the Ada main program, the Ada objects and the other language
2584 objects:
2585 @smallexample
2586 gnatlink my_main.ali file1.o file2.o
2587 @end smallexample
2588 @end enumerate
2589
2590 The last three steps can be grouped in a single command:
2591 @smallexample
2592 gnatmake my_main.adb -largs file1.o file2.o
2593 @end smallexample
2594
2595 @cindex Binder output file
2596 @noindent
2597 If the main program is in a language other than Ada, then you may have
2598 more than one entry point into the Ada subsystem. You must use a special
2599 binder option to generate callable routines that initialize and
2600 finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}).
2601 Calls to the initialization and finalization routines must be inserted
2602 in the main program, or some other appropriate point in the code. The
2603 call to initialize the Ada units must occur before the first Ada
2604 subprogram is called, and the call to finalize the Ada units must occur
2605 after the last Ada subprogram returns. The binder will place the
2606 initialization and finalization subprograms into the
2607 @file{b~@var{xxx}.adb} file where they can be accessed by your C
2608 sources.  To illustrate, we have the following example:
2609
2610 @smallexample
2611 /* main.c */
2612 extern void adainit (void);
2613 extern void adafinal (void);
2614 extern int add (int, int);
2615 extern int sub (int, int);
2616
2617 int main (int argc, char *argv[])
2618 @{
2619   int a = 21, b = 7;
2620
2621   adainit();
2622
2623   /* Should print "21 + 7 = 28" */
2624   printf ("%d + %d = %d\n", a, b, add (a, b));
2625   /* Should print "21 - 7 = 14" */
2626   printf ("%d - %d = %d\n", a, b, sub (a, b));
2627
2628   adafinal();
2629 @}
2630 @end smallexample
2631
2632 @smallexample @c ada
2633 --  unit1.ads
2634 package Unit1 is
2635    function Add (A, B : Integer) return Integer;
2636    pragma Export (C, Add, "add");
2637 end Unit1;
2638
2639 --  unit1.adb
2640 package body Unit1 is
2641    function Add (A, B : Integer) return Integer is
2642    begin
2643       return A + B;
2644    end Add;
2645 end Unit1;
2646
2647 --  unit2.ads
2648 package Unit2 is
2649    function Sub (A, B : Integer) return Integer;
2650    pragma Export (C, Sub, "sub");
2651 end Unit2;
2652
2653 --  unit2.adb
2654 package body Unit2 is
2655    function Sub (A, B : Integer) return Integer is
2656    begin
2657       return A - B;
2658    end Sub;
2659 end Unit2;
2660 @end smallexample
2661
2662 @enumerate
2663 @item
2664 The build procedure for this application is similar to the last
2665 example's.  First, compile the foreign language files to generate object
2666 files:
2667 @smallexample
2668 ^gcc -c main.c^gcc -c main.c^
2669 @end smallexample
2670
2671 @item
2672 Next, compile the Ada units to produce a set of object files and ALI
2673 files:
2674 @smallexample
2675 gnatmake ^-c^/ACTIONS=COMPILE^ unit1.adb
2676 gnatmake ^-c^/ACTIONS=COMPILE^ unit2.adb
2677 @end smallexample
2678
2679 @item
2680 Run the Ada binder on every generated ALI file.  Make sure to use the
2681 @option{-n} option to specify a foreign main program:
2682 @smallexample
2683 gnatbind ^-n^/NOMAIN^ unit1.ali unit2.ali
2684 @end smallexample
2685
2686 @item
2687 Link the Ada main program, the Ada objects and the foreign language
2688 objects. You need only list the last ALI file here:
2689 @smallexample
2690 gnatlink unit2.ali main.o -o exec_file
2691 @end smallexample
2692
2693 This procedure yields a binary executable called @file{exec_file}.
2694 @end enumerate
2695
2696 @noindent
2697 Depending on the circumstances (for example when your non-Ada main object
2698 does not provide symbol @code{main}), you may also need to instruct the
2699 GNAT linker not to include the standard startup objects by passing the
2700 @option{^-nostartfiles^/NOSTART_FILES^} switch to @command{gnatlink}.
2701
2702 @node Calling Conventions
2703 @subsection Calling Conventions
2704 @cindex Foreign Languages
2705 @cindex Calling Conventions
2706 GNAT follows standard calling sequence conventions and will thus interface
2707 to any other language that also follows these conventions. The following
2708 Convention identifiers are recognized by GNAT:
2709
2710 @table @code
2711 @cindex Interfacing to Ada
2712 @cindex Other Ada compilers
2713 @cindex Convention Ada
2714 @item Ada
2715 This indicates that the standard Ada calling sequence will be
2716 used and all Ada data items may be passed without any limitations in the
2717 case where GNAT is used to generate both the caller and callee. It is also
2718 possible to mix GNAT generated code and code generated by another Ada
2719 compiler. In this case, the data types should be restricted to simple
2720 cases, including primitive types. Whether complex data types can be passed
2721 depends on the situation. Probably it is safe to pass simple arrays, such
2722 as arrays of integers or floats. Records may or may not work, depending
2723 on whether both compilers lay them out identically. Complex structures
2724 involving variant records, access parameters, tasks, or protected types,
2725 are unlikely to be able to be passed.
2726
2727 Note that in the case of GNAT running
2728 on a platform that supports HP Ada 83, a higher degree of compatibility
2729 can be guaranteed, and in particular records are layed out in an identical
2730 manner in the two compilers. Note also that if output from two different
2731 compilers is mixed, the program is responsible for dealing with elaboration
2732 issues. Probably the safest approach is to write the main program in the
2733 version of Ada other than GNAT, so that it takes care of its own elaboration
2734 requirements, and then call the GNAT-generated adainit procedure to ensure
2735 elaboration of the GNAT components. Consult the documentation of the other
2736 Ada compiler for further details on elaboration.
2737
2738 However, it is not possible to mix the tasking run time of GNAT and
2739 HP Ada 83, All the tasking operations must either be entirely within
2740 GNAT compiled sections of the program, or entirely within HP Ada 83
2741 compiled sections of the program.
2742
2743 @cindex Interfacing to Assembly
2744 @cindex Convention Assembler
2745 @item Assembler
2746 Specifies assembler as the convention. In practice this has the
2747 same effect as convention Ada (but is not equivalent in the sense of being
2748 considered the same convention).
2749
2750 @cindex Convention Asm
2751 @findex Asm
2752 @item Asm
2753 Equivalent to Assembler.
2754
2755 @cindex Interfacing to COBOL
2756 @cindex Convention COBOL
2757 @findex COBOL
2758 @item COBOL
2759 Data will be passed according to the conventions described
2760 in section B.4 of the Ada Reference Manual.
2761
2762 @findex C
2763 @cindex Interfacing to C
2764 @cindex Convention C
2765 @item C
2766 Data will be passed according to the conventions described
2767 in section B.3 of the Ada Reference Manual.
2768
2769 A note on interfacing to a C ``varargs'' function:
2770 @findex C varargs function
2771 @cindex Interfacing to C varargs function
2772 @cindex varargs function interfaces
2773
2774 @itemize @bullet
2775 @item
2776 In C, @code{varargs} allows a function to take a variable number of
2777 arguments. There is no direct equivalent in this to Ada. One
2778 approach that can be used is to create a C wrapper for each
2779 different profile and then interface to this C wrapper. For
2780 example, to print an @code{int} value using @code{printf},
2781 create a C function @code{printfi} that takes two arguments, a
2782 pointer to a string and an int, and calls @code{printf}.
2783 Then in the Ada program, use pragma @code{Import} to
2784 interface to @code{printfi}.
2785
2786 @item
2787 It may work on some platforms to directly interface to
2788 a @code{varargs} function by providing a specific Ada profile
2789 for a particular call. However, this does not work on
2790 all platforms, since there is no guarantee that the
2791 calling sequence for a two argument normal C function
2792 is the same as for calling a @code{varargs} C function with
2793 the same two arguments.
2794 @end itemize
2795
2796 @cindex Convention Default
2797 @findex Default
2798 @item Default
2799 Equivalent to C.
2800
2801 @cindex Convention External
2802 @findex External
2803 @item External
2804 Equivalent to C.
2805
2806 @ifclear vms
2807 @findex C++
2808 @cindex Interfacing to C++
2809 @cindex Convention C++
2810 @item C_Plus_Plus (or CPP)
2811 This stands for C++. For most purposes this is identical to C.
2812 See the separate description of the specialized GNAT pragmas relating to
2813 C++ interfacing for further details.
2814 @end ifclear
2815
2816 @findex Fortran
2817 @cindex Interfacing to Fortran
2818 @cindex Convention Fortran
2819 @item Fortran
2820 Data will be passed according to the conventions described
2821 in section B.5 of the Ada Reference Manual.
2822
2823 @item Intrinsic
2824 This applies to an intrinsic operation, as defined in the Ada
2825 Reference Manual. If a pragma Import (Intrinsic) applies to a subprogram,
2826 this means that the body of the subprogram is provided by the compiler itself,
2827 usually by means of an efficient code sequence, and that the user does not
2828 supply an explicit body for it. In an application program, the pragma may
2829 be applied to the following sets of names:
2830
2831 @itemize @bullet
2832 @item
2833 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right,
2834 Shift_Right_Arithmetic.  The corresponding subprogram declaration must have
2835 two formal parameters. The
2836 first one must be a signed integer type or a modular type with a binary
2837 modulus, and the second parameter must be of type Natural.
2838 The return type must be the same as the type of the first argument. The size
2839 of this type can only be 8, 16, 32, or 64.
2840
2841 @item
2842 Binary arithmetic operators: ``+'', ``-'', ``*'', ``/''
2843 The corresponding operator declaration must have parameters and result type
2844 that have the same root numeric type (for example, all three are long_float
2845 types). This simplifies the definition of operations that use type checking
2846 to perform dimensional checks:
2847
2848 @smallexample @c ada
2849 type Distance is new Long_Float;
2850 type Time     is new Long_Float;
2851 type Velocity is new Long_Float;
2852 function "/" (D : Distance; T : Time)
2853   return Velocity;
2854 pragma Import (Intrinsic, "/");
2855 @end smallexample
2856
2857 @noindent
2858 This common idiom is often programmed with a generic definition and an
2859 explicit body. The pragma makes it simpler to introduce such declarations.
2860 It incurs no overhead in compilation time or code size, because it is
2861 implemented as a single machine instruction.
2862
2863 @item
2864 General subprogram entities, to bind an Ada subprogram declaration to
2865 a compiler builtin by name with back-ends where such interfaces are
2866 available. A typical example is the set of ``__builtin'' functions
2867 exposed by the GCC back-end, as in the following example:
2868
2869 @smallexample @c ada
2870    function builtin_sqrt (F : Float) return Float;
2871    pragma Import (Intrinsic, builtin_sqrt, "__builtin_sqrtf");
2872 @end smallexample
2873
2874 Most of the GCC builtins are accessible this way, and as for other
2875 import conventions (e.g. C), it is the user's responsibility to ensure
2876 that the Ada subprogram profile matches the underlying builtin
2877 expectations.
2878 @end itemize
2879
2880 @noindent
2881
2882 @ifset unw
2883 @findex Stdcall
2884 @cindex Convention Stdcall
2885 @item Stdcall
2886 This is relevant only to Windows XP/2000/NT implementations of GNAT,
2887 and specifies that the @code{Stdcall} calling sequence will be used,
2888 as defined by the NT API. Nevertheless, to ease building
2889 cross-platform bindings this convention will be handled as a @code{C} calling
2890 convention on non-Windows platforms.
2891
2892 @findex DLL
2893 @cindex Convention DLL
2894 @item DLL
2895 This is equivalent to @code{Stdcall}.
2896
2897 @findex Win32
2898 @cindex Convention Win32
2899 @item Win32
2900 This is equivalent to @code{Stdcall}.
2901 @end ifset
2902
2903 @findex Stubbed
2904 @cindex Convention Stubbed
2905 @item Stubbed
2906 This is a special convention that indicates that the compiler
2907 should provide a stub body that raises @code{Program_Error}.
2908 @end table
2909
2910 @noindent
2911 GNAT additionally provides a useful pragma @code{Convention_Identifier}
2912 that can be used to parameterize conventions and allow additional synonyms
2913 to be specified. For example if you have legacy code in which the convention
2914 identifier Fortran77 was used for Fortran, you can use the configuration
2915 pragma:
2916
2917 @smallexample @c ada
2918 pragma Convention_Identifier (Fortran77, Fortran);
2919 @end smallexample
2920
2921 @noindent
2922 And from now on the identifier Fortran77 may be used as a convention
2923 identifier (for example in an @code{Import} pragma) with the same
2924 meaning as Fortran.
2925
2926 @ifclear vms
2927 @node Building Mixed Ada & C++ Programs
2928 @section Building Mixed Ada and C++ Programs
2929
2930 @noindent
2931 A programmer inexperienced with mixed-language development may find that
2932 building an application containing both Ada and C++ code can be a
2933 challenge.  This section gives a few
2934 hints that should make this task easier. The first section addresses
2935 the differences between interfacing with C and interfacing with C++.
2936 The second section
2937 looks into the delicate problem of linking the complete application from
2938 its Ada and C++ parts. The last section gives some hints on how the GNAT
2939 run-time library can be adapted in order to allow inter-language dispatching
2940 with a new C++ compiler.
2941
2942 @menu
2943 * Interfacing to C++::
2944 * Linking a Mixed C++ & Ada Program::
2945 * A Simple Example::
2946 * Interfacing with C++ constructors::
2947 * Interfacing with C++ at the Class Level::
2948 @end menu
2949
2950 @node Interfacing to C++
2951 @subsection Interfacing to C++
2952
2953 @noindent
2954 GNAT supports interfacing with the G++ compiler (or any C++ compiler
2955 generating code that is compatible with the G++ Application Binary
2956 Interface ---see http://www.codesourcery.com/archives/cxx-abi).
2957
2958 @noindent
2959 Interfacing can be done at 3 levels: simple data, subprograms, and
2960 classes. In the first two cases, GNAT offers a specific @code{Convention
2961 C_Plus_Plus} (or @code{CPP}) that behaves exactly like @code{Convention C}.
2962 Usually, C++ mangles the names of subprograms. To generate proper mangled
2963 names automatically, see @ref{Generating Ada Bindings for C and C++ headers}).
2964 This problem can also be addressed manually in two ways:
2965
2966 @itemize @bullet
2967 @item
2968 by modifying the C++ code in order to force a C convention using
2969 the @code{extern "C"} syntax.
2970
2971 @item
2972 by figuring out the mangled name (using e.g. @command{nm}) and using it as the
2973 Link_Name argument of the pragma import.
2974 @end itemize
2975
2976 @noindent
2977 Interfacing at the class level can be achieved by using the GNAT specific
2978 pragmas such as @code{CPP_Constructor}.  @xref{Interfacing to C++,,,
2979 gnat_rm, GNAT Reference Manual}, for additional information.
2980
2981 @node Linking a Mixed C++ & Ada Program
2982 @subsection Linking a Mixed C++ & Ada Program
2983
2984 @noindent
2985 Usually the linker of the C++ development system must be used to link
2986 mixed applications because most C++ systems will resolve elaboration
2987 issues (such as calling constructors on global class instances)
2988 transparently during the link phase. GNAT has been adapted to ease the
2989 use of a foreign linker for the last phase. Three cases can be
2990 considered:
2991 @enumerate
2992
2993 @item
2994 Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
2995 The C++ linker can simply be called by using the C++ specific driver
2996 called @code{g++}.
2997
2998 Note that if the C++ code uses inline functions, you will need to
2999 compile your C++ code with the @code{-fkeep-inline-functions} switch in
3000 order to provide an existing function implementation that the Ada code can
3001 link with.
3002
3003 @smallexample
3004 $ g++ -c -fkeep-inline-functions file1.C
3005 $ g++ -c -fkeep-inline-functions file2.C
3006 $ gnatmake ada_unit -largs file1.o file2.o --LINK=g++
3007 @end smallexample
3008
3009 @item
3010 Using GNAT and G++ from two different GCC installations: If both
3011 compilers are on the @env{PATH}, the previous method may be used. It is
3012 important to note that environment variables such as
3013 @env{C_INCLUDE_PATH}, @env{GCC_EXEC_PREFIX}, @env{BINUTILS_ROOT}, and
3014 @env{GCC_ROOT} will affect both compilers
3015 at the same time and may make one of the two compilers operate
3016 improperly if set during invocation of the wrong compiler.  It is also
3017 very important that the linker uses the proper @file{libgcc.a} GCC
3018 library -- that is, the one from the C++ compiler installation. The
3019 implicit link command as suggested in the @command{gnatmake} command
3020 from the former example can be replaced by an explicit link command with
3021 the full-verbosity option in order to verify which library is used:
3022 @smallexample
3023 $ gnatbind ada_unit
3024 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
3025 @end smallexample
3026 If there is a problem due to interfering environment variables, it can
3027 be worked around by using an intermediate script. The following example
3028 shows the proper script to use when GNAT has not been installed at its
3029 default location and g++ has been installed at its default location:
3030
3031 @smallexample
3032 $ cat ./my_script
3033 #!/bin/sh
3034 unset BINUTILS_ROOT
3035 unset GCC_ROOT
3036 c++ $*
3037 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
3038 @end smallexample
3039
3040 @item
3041 Using a non-GNU C++ compiler: The commands previously described can be
3042 used to insure that the C++ linker is used. Nonetheless, you need to add
3043 a few more parameters to the link command line, depending on the exception
3044 mechanism used.
3045
3046 If the @code{setjmp/longjmp} exception mechanism is used, only the paths
3047 to the libgcc libraries are required:
3048
3049 @smallexample
3050 $ cat ./my_script
3051 #!/bin/sh
3052 CC $* `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a`
3053 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3054 @end smallexample
3055
3056 Where CC is the name of the non-GNU C++ compiler.
3057
3058 If the @code{zero cost} exception mechanism is used, and the platform
3059 supports automatic registration of exception tables (e.g.@: Solaris or IRIX),
3060 paths to more objects are required:
3061
3062 @smallexample
3063 $ cat ./my_script
3064 #!/bin/sh
3065 CC `gcc -print-file-name=crtbegin.o` $* \
3066 `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a` \
3067 `gcc -print-file-name=crtend.o`
3068 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3069 @end smallexample
3070
3071 If the @code{zero cost} exception mechanism is used, and the platform
3072 doesn't support automatic registration of exception tables (e.g.@: HP-UX,
3073 Tru64 or AIX), the simple approach described above will not work and
3074 a pre-linking phase using GNAT will be necessary.
3075
3076 @end enumerate
3077
3078 Another alternative is to use the @command{gprbuild} multi-language builder
3079 which has a large knowledge base and knows how to link Ada and C++ code
3080 together automatically in most cases.
3081
3082 @node A Simple Example
3083 @subsection  A Simple Example
3084 @noindent
3085 The following example, provided as part of the GNAT examples, shows how
3086 to achieve procedural interfacing between Ada and C++ in both
3087 directions. The C++ class A has two methods. The first method is exported
3088 to Ada by the means of an extern C wrapper function. The second method
3089 calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
3090 a limited record with a layout comparable to the C++ class. The Ada
3091 subprogram, in turn, calls the C++ method. So, starting from the C++
3092 main program, the process passes back and forth between the two
3093 languages.
3094
3095 @noindent
3096 Here are the compilation commands:
3097 @smallexample
3098 $ gnatmake -c simple_cpp_interface
3099 $ g++ -c cpp_main.C
3100 $ g++ -c ex7.C
3101 $ gnatbind -n simple_cpp_interface
3102 $ gnatlink simple_cpp_interface -o cpp_main --LINK=g++
3103       -lstdc++ ex7.o cpp_main.o
3104 @end smallexample
3105
3106 @noindent
3107 Here are the corresponding sources:
3108 @smallexample
3109
3110 //cpp_main.C
3111
3112 #include "ex7.h"
3113
3114 extern "C" @{
3115   void adainit (void);
3116   void adafinal (void);
3117   void method1 (A *t);
3118 @}
3119
3120 void method1 (A *t)
3121 @{
3122   t->method1 ();
3123 @}
3124
3125 int main ()
3126 @{
3127   A obj;
3128   adainit ();
3129   obj.method2 (3030);
3130   adafinal ();
3131 @}
3132
3133 //ex7.h
3134
3135 class Origin @{
3136  public:
3137   int o_value;
3138 @};
3139 class A : public Origin @{
3140  public:
3141   void method1 (void);
3142   void method2 (int v);
3143   A();
3144   int   a_value;
3145 @};
3146
3147 //ex7.C
3148
3149 #include "ex7.h"
3150 #include <stdio.h>
3151
3152 extern "C" @{ void ada_method2 (A *t, int v);@}
3153
3154 void A::method1 (void)
3155 @{
3156   a_value = 2020;
3157   printf ("in A::method1, a_value = %d \n",a_value);
3158
3159 @}
3160
3161 void A::method2 (int v)
3162 @{
3163    ada_method2 (this, v);
3164    printf ("in A::method2, a_value = %d \n",a_value);
3165
3166 @}
3167
3168 A::A(void)
3169 @{
3170    a_value = 1010;
3171   printf ("in A::A, a_value = %d \n",a_value);
3172 @}
3173 @end smallexample
3174
3175 @smallexample @c ada
3176 -- Ada sources
3177 package body Simple_Cpp_Interface is
3178
3179    procedure Ada_Method2 (This : in out A; V : Integer) is
3180    begin
3181       Method1 (This);
3182       This.A_Value := V;
3183    end Ada_Method2;
3184
3185 end Simple_Cpp_Interface;
3186
3187 with System;
3188 package Simple_Cpp_Interface is
3189    type A is limited
3190       record
3191          Vptr    : System.Address;
3192          O_Value : Integer;
3193          A_Value : Integer;
3194       end record;
3195    pragma Convention (C, A);
3196
3197    procedure Method1 (This : in out A);
3198    pragma Import (C, Method1);
3199
3200    procedure Ada_Method2 (This : in out A; V : Integer);
3201    pragma Export (C, Ada_Method2);
3202
3203 end Simple_Cpp_Interface;
3204 @end smallexample
3205
3206 @node Interfacing with C++ constructors
3207 @subsection Interfacing with C++ constructors
3208 @noindent
3209
3210 In order to interface with C++ constructors GNAT provides the
3211 @code{pragma CPP_Constructor} (@xref{Interfacing to C++,,,
3212 gnat_rm, GNAT Reference Manual}, for additional information).
3213 In this section we present some common uses of C++ constructors
3214 in mixed-languages programs in GNAT.
3215
3216 Let us assume that we need to interface with the following
3217 C++ class:
3218
3219 @smallexample
3220 @b{class} Root @{
3221 @b{public}:
3222   int  a_value;
3223   int  b_value;
3224   @b{virtual} int Get_Value ();
3225   Root();              // Default constructor
3226   Root(int v);         // 1st non-default constructor
3227   Root(int v, int w);  // 2nd non-default constructor
3228 @};
3229 @end smallexample
3230
3231 For this purpose we can write the following package spec (further
3232 information on how to build this spec is available in
3233 @ref{Interfacing with C++ at the Class Level} and
3234 @ref{Generating Ada Bindings for C and C++ headers}).
3235
3236 @smallexample @c ada
3237 with Interfaces.C; use Interfaces.C;
3238 package Pkg_Root is
3239   type Root is tagged limited record
3240      A_Value : int;
3241      B_Value : int;
3242   end record;
3243   pragma Import (CPP, Root);
3244
3245   function Get_Value (Obj : Root) return int;
3246   pragma Import (CPP, Get_Value);
3247
3248   function Constructor return Root;
3249   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ev");
3250
3251   function Constructor (v : Integer) return Root;
3252   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ei");
3253
3254   function Constructor (v, w : Integer) return Root;
3255   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Eii");
3256 end Pkg_Root;
3257 @end smallexample
3258
3259 On the Ada side the constructor is represented by a function (whose
3260 name is arbitrary) that returns the classwide type corresponding to
3261 the imported C++ class. Although the constructor is described as a
3262 function, it is typically a procedure with an extra implicit argument
3263 (the object being initialized) at the implementation level. GNAT
3264 issues the appropriate call, whatever it is, to get the object
3265 properly initialized.
3266
3267 Constructors can only appear in the following contexts:
3268
3269 @itemize @bullet
3270 @item
3271 On the right side of an initialization of an object of type @var{T}.
3272 @item
3273 On the right side of an initialization of a record component of type @var{T}.
3274 @item
3275 In an Ada 2005 limited aggregate.
3276 @item
3277 In an Ada 2005 nested limited aggregate.
3278 @item
3279 In an Ada 2005 limited aggregate that initializes an object built in
3280 place by an extended return statement.
3281 @end itemize
3282
3283 @noindent
3284 In a declaration of an object whose type is a class imported from C++,
3285 either the default C++ constructor is implicitly called by GNAT, or
3286 else the required C++ constructor must be explicitly called in the
3287 expression that initializes the object. For example:
3288
3289 @smallexample @c ada
3290   Obj1 : Root;
3291   Obj2 : Root := Constructor;
3292   Obj3 : Root := Constructor (v => 10);
3293   Obj4 : Root := Constructor (30, 40);
3294 @end smallexample
3295
3296 The first two declarations are equivalent: in both cases the default C++
3297 constructor is invoked (in the former case the call to the constructor is
3298 implicit, and in the latter case the call is explicit in the object
3299 declaration). @code{Obj3} is initialized by the C++ non-default constructor
3300 that takes an integer argument, and @code{Obj4} is initialized by the
3301 non-default C++ constructor that takes two integers.
3302
3303 Let us derive the imported C++ class in the Ada side. For example:
3304
3305 @smallexample @c ada
3306   type DT is new Root with record
3307      C_Value : Natural := 2009;
3308   end record;
3309 @end smallexample
3310
3311 In this case the components DT inherited from the C++ side must be
3312 initialized by a C++ constructor, and the additional Ada components
3313 of type DT are initialized by GNAT. The initialization of such an
3314 object is done either by default, or by means of a function returning
3315 an aggregate of type DT, or by means of an extension aggregate.
3316
3317 @smallexample @c ada
3318   Obj5 : DT;
3319   Obj6 : DT := Function_Returning_DT (50);
3320   Obj7 : DT := (Constructor (30,40) with C_Value => 50);
3321 @end smallexample
3322
3323 The declaration of @code{Obj5} invokes the default constructors: the
3324 C++ default constructor of the parent type takes care of the initialization
3325 of the components inherited from Root, and GNAT takes care of the default
3326 initialization of the additional Ada components of type DT (that is,
3327 @code{C_Value} is initialized to value 2009). The order of invocation of
3328 the constructors is consistent with the order of elaboration required by
3329 Ada and C++. That is, the constructor of the parent type is always called
3330 before the constructor of the derived type.
3331
3332 Let us now consider a record that has components whose type is imported
3333 from C++. For example:
3334
3335 @smallexample @c ada
3336   type Rec1 is limited record
3337      Data1 : Root := Constructor (10);
3338      Value : Natural := 1000;
3339   end record;
3340
3341   type Rec2 (D : Integer := 20) is limited record
3342      Rec   : Rec1;
3343      Data2 : Root := Constructor (D, 30);
3344   end record;
3345 @end smallexample
3346
3347 The initialization of an object of type @code{Rec2} will call the
3348 non-default C++ constructors specified for the imported components.
3349 For example:
3350
3351 @smallexample @c ada
3352   Obj8 : Rec2 (40);
3353 @end smallexample
3354
3355 Using Ada 2005 we can use limited aggregates to initialize an object
3356 invoking C++ constructors that differ from those specified in the type
3357 declarations. For example:
3358
3359 @smallexample @c ada
3360   Obj9 : Rec2 := (Rec => (Data1 => Constructor (15, 16),
3361                           others => <>),
3362                   others => <>);
3363 @end smallexample
3364
3365 The above declaration uses an Ada 2005 limited aggregate to
3366 initialize @code{Obj9}, and the C++ constructor that has two integer
3367 arguments is invoked to initialize the @code{Data1} component instead
3368 of the constructor specified in the declaration of type @code{Rec1}. In
3369 Ada 2005 the box in the aggregate indicates that unspecified components
3370 are initialized using the expression (if any) available in the component
3371 declaration. That is, in this case discriminant @code{D} is initialized
3372 to value @code{20}, @code{Value} is initialized to value 1000, and the
3373 non-default C++ constructor that handles two integers takes care of
3374 initializing component @code{Data2} with values @code{20,30}.
3375
3376 In Ada 2005 we can use the extended return statement to build the Ada
3377 equivalent to C++ non-default constructors. For example:
3378
3379 @smallexample @c ada
3380   function Constructor (V : Integer) return Rec2 is
3381   begin
3382      return Obj : Rec2 := (Rec => (Data1  => Constructor (V, 20),
3383                                    others => <>),
3384                            others => <>) do
3385         --  Further actions required for construction of
3386         --  objects of type Rec2
3387         ...
3388      end record;
3389   end Constructor;
3390 @end smallexample
3391
3392 In this example the extended return statement construct is used to
3393 build in place the returned object whose components are initialized
3394 by means of a limited aggregate. Any further action associated with
3395 the constructor can be placed inside the construct.
3396
3397 @node Interfacing with C++ at the Class Level
3398 @subsection Interfacing with C++ at the Class Level
3399 @noindent
3400 In this section we demonstrate the GNAT features for interfacing with
3401 C++ by means of an example making use of Ada 2005 abstract interface
3402 types. This example consists of a classification of animals; classes
3403 have been used to model our main classification of animals, and
3404 interfaces provide support for the management of secondary
3405 classifications. We first demonstrate a case in which the types and
3406 constructors are defined on the C++ side and imported from the Ada
3407 side, and latter the reverse case.
3408
3409 The root of our derivation will be the @code{Animal} class, with a
3410 single private attribute (the @code{Age} of the animal) and two public
3411 primitives to set and get the value of this attribute.
3412
3413 @smallexample
3414 @b{class} Animal @{
3415  @b{public}:
3416    @b{virtual} void Set_Age (int New_Age);
3417    @b{virtual} int Age ();
3418  @b{private}:
3419    int Age_Count;
3420 @};
3421 @end smallexample
3422
3423 Abstract interface types are defined in C++ by means of classes with pure
3424 virtual functions and no data members. In our example we will use two
3425 interfaces that provide support for the common management of @code{Carnivore}
3426 and @code{Domestic} animals:
3427
3428 @smallexample
3429 @b{class} Carnivore @{
3430 @b{public}:
3431    @b{virtual} int Number_Of_Teeth () = 0;
3432 @};
3433
3434 @b{class} Domestic @{
3435 @b{public}:
3436    @b{virtual void} Set_Owner (char* Name) = 0;
3437 @};
3438 @end smallexample
3439
3440 Using these declarations, we can now say that a @code{Dog} is an animal that is
3441 both Carnivore and Domestic, that is:
3442
3443 @smallexample
3444 @b{class} Dog : Animal, Carnivore, Domestic @{
3445  @b{public}:
3446    @b{virtual} int  Number_Of_Teeth ();
3447    @b{virtual} void Set_Owner (char* Name);
3448
3449    Dog(); // Constructor
3450  @b{private}:
3451    int  Tooth_Count;
3452    char *Owner;
3453 @};
3454 @end smallexample
3455
3456 In the following examples we will assume that the previous declarations are
3457 located in a file named @code{animals.h}. The following package demonstrates
3458 how to import these C++ declarations from the Ada side:
3459
3460 @smallexample @c ada
3461 with Interfaces.C.Strings; use Interfaces.C.Strings;
3462 package Animals is
3463   type Carnivore is interface;
3464   pragma Convention (C_Plus_Plus, Carnivore);
3465   function Number_Of_Teeth (X : Carnivore)
3466      return Natural is abstract;
3467
3468   type Domestic is interface;
3469   pragma Convention (C_Plus_Plus, Set_Owner);
3470   procedure Set_Owner
3471     (X    : in out Domestic;
3472      Name : Chars_Ptr) is abstract;
3473
3474   type Animal is tagged record
3475     Age : Natural := 0;
3476   end record;
3477   pragma Import (C_Plus_Plus, Animal);
3478
3479   procedure Set_Age (X : in out Animal; Age : Integer);
3480   pragma Import (C_Plus_Plus, Set_Age);
3481
3482   function Age (X : Animal) return Integer;
3483   pragma Import (C_Plus_Plus, Age);
3484
3485   type Dog is new Animal and Carnivore and Domestic with record
3486     Tooth_Count : Natural;
3487     Owner       : String (1 .. 30);
3488   end record;
3489   pragma Import (C_Plus_Plus, Dog);
3490
3491   function Number_Of_Teeth (A : Dog) return Integer;
3492   pragma Import (C_Plus_Plus, Number_Of_Teeth);
3493
3494   procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3495   pragma Import (C_Plus_Plus, Set_Owner);
3496
3497   function New_Dog return Dog;
3498   pragma CPP_Constructor (New_Dog);
3499   pragma Import (CPP, New_Dog, "_ZN3DogC2Ev");
3500 end Animals;
3501 @end smallexample
3502
3503 Thanks to the compatibility between GNAT run-time structures and the C++ ABI,
3504 interfacing with these C++ classes is easy. The only requirement is that all
3505 the primitives and components must be declared exactly in the same order in
3506 the two languages.
3507
3508 Regarding the abstract interfaces, we must indicate to the GNAT compiler by
3509 means of a @code{pragma Convention (C_Plus_Plus)}, the convention used to pass
3510 the arguments to the called primitives will be the same as for C++. For the
3511 imported classes we use @code{pragma Import} with convention @code{C_Plus_Plus}
3512 to indicate that they have been defined on the C++ side; this is required
3513 because the dispatch table associated with these tagged types will be built
3514 in the C++ side and therefore will not contain the predefined Ada primitives
3515 which Ada would otherwise expect.
3516
3517 As the reader can see there is no need to indicate the C++ mangled names
3518 associated with each subprogram because it is assumed that all the calls to
3519 these primitives will be dispatching calls. The only exception is the
3520 constructor, which must be registered with the compiler by means of
3521 @code{pragma CPP_Constructor} and needs to provide its associated C++
3522 mangled name because the Ada compiler generates direct calls to it.
3523
3524 With the above packages we can now declare objects of type Dog on the Ada side
3525 and dispatch calls to the corresponding subprograms on the C++ side. We can
3526 also extend the tagged type Dog with further fields and primitives, and
3527 override some of its C++ primitives on the Ada side. For example, here we have
3528 a type derivation defined on the Ada side that inherits all the dispatching
3529 primitives of the ancestor from the C++ side.
3530
3531 @smallexample
3532 @b{with} Animals; @b{use} Animals;
3533 @b{package} Vaccinated_Animals @b{is}
3534   @b{type} Vaccinated_Dog @b{is new} Dog @b{with null record};
3535   @b{function} Vaccination_Expired (A : Vaccinated_Dog) @b{return} Boolean;
3536 @b{end} Vaccinated_Animals;
3537 @end smallexample
3538
3539 It is important to note that, because of the ABI compatibility, the programmer
3540 does not need to add any further information to indicate either the object
3541 layout or the dispatch table entry associated with each dispatching operation.
3542
3543 Now let us define all the types and constructors on the Ada side and export
3544 them to C++, using the same hierarchy of our previous example:
3545
3546 @smallexample @c ada
3547 with Interfaces.C.Strings;
3548 use Interfaces.C.Strings;
3549 package Animals is
3550   type Carnivore is interface;
3551   pragma Convention (C_Plus_Plus, Carnivore);
3552   function Number_Of_Teeth (X : Carnivore)
3553      return Natural is abstract;
3554
3555   type Domestic is interface;
3556   pragma Convention (C_Plus_Plus, Set_Owner);
3557   procedure Set_Owner
3558     (X    : in out Domestic;
3559      Name : Chars_Ptr) is abstract;
3560
3561   type Animal is tagged record
3562     Age : Natural := 0;
3563   end record;
3564   pragma Convention (C_Plus_Plus, Animal);
3565
3566   procedure Set_Age (X : in out Animal; Age : Integer);
3567   pragma Export (C_Plus_Plus, Set_Age);
3568
3569   function Age (X : Animal) return Integer;
3570   pragma Export (C_Plus_Plus, Age);
3571
3572   type Dog is new Animal and Carnivore and Domestic with record
3573     Tooth_Count : Natural;
3574     Owner       : String (1 .. 30);
3575   end record;
3576   pragma Convention (C_Plus_Plus, Dog);
3577
3578   function Number_Of_Teeth (A : Dog) return Integer;
3579   pragma Export (C_Plus_Plus, Number_Of_Teeth);
3580
3581   procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3582   pragma Export (C_Plus_Plus, Set_Owner);
3583
3584   function New_Dog return Dog'Class;
3585   pragma Export (C_Plus_Plus, New_Dog);
3586 end Animals;
3587 @end smallexample
3588
3589 Compared with our previous example the only difference is the use of
3590 @code{pragma Export} to indicate to the GNAT compiler that the primitives will
3591 be available to C++. Thanks to the ABI compatibility, on the C++ side there is
3592 nothing else to be done; as explained above, the only requirement is that all
3593 the primitives and components are declared in exactly the same order.
3594
3595 For completeness, let us see a brief C++ main program that uses the
3596 declarations available in @code{animals.h} (presented in our first example) to
3597 import and use the declarations from the Ada side, properly initializing and
3598 finalizing the Ada run-time system along the way:
3599
3600 @smallexample
3601 @b{#include} "animals.h"
3602 @b{#include} <iostream>
3603 @b{using namespace} std;
3604
3605 void Check_Carnivore (Carnivore *obj) @{@dots{}@}
3606 void Check_Domestic (Domestic *obj)   @{@dots{}@}
3607 void Check_Animal (Animal *obj)       @{@dots{}@}
3608 void Check_Dog (Dog *obj)             @{@dots{}@}
3609
3610 @b{extern} "C" @{
3611   void adainit (void);
3612   void adafinal (void);
3613   Dog* new_dog ();
3614 @}
3615
3616 void test ()
3617 @{
3618   Dog *obj = new_dog();  // Ada constructor
3619   Check_Carnivore (obj); // Check secondary DT
3620   Check_Domestic (obj);  // Check secondary DT
3621   Check_Animal (obj);    // Check primary DT
3622   Check_Dog (obj);       // Check primary DT
3623 @}
3624
3625 int main ()
3626 @{
3627   adainit ();  test();  adafinal ();
3628   return 0;
3629 @}
3630 @end smallexample
3631
3632 @node Comparison between GNAT and C/C++ Compilation Models
3633 @section Comparison between GNAT and C/C++ Compilation Models
3634
3635 @noindent
3636 The GNAT model of compilation is close to the C and C++ models. You can
3637 think of Ada specs as corresponding to header files in C. As in C, you
3638 don't need to compile specs; they are compiled when they are used. The
3639 Ada @code{with} is similar in effect to the @code{#include} of a C
3640 header.
3641
3642 One notable difference is that, in Ada, you may compile specs separately
3643 to check them for semantic and syntactic accuracy. This is not always
3644 possible with C headers because they are fragments of programs that have
3645 less specific syntactic or semantic rules.
3646
3647 The other major difference is the requirement for running the binder,
3648 which performs two important functions. First, it checks for
3649 consistency. In C or C++, the only defense against assembling
3650 inconsistent programs lies outside the compiler, in a makefile, for
3651 example. The binder satisfies the Ada requirement that it be impossible
3652 to construct an inconsistent program when the compiler is used in normal
3653 mode.
3654
3655 @cindex Elaboration order control
3656 The other important function of the binder is to deal with elaboration
3657 issues. There are also elaboration issues in C++ that are handled
3658 automatically. This automatic handling has the advantage of being
3659 simpler to use, but the C++ programmer has no control over elaboration.
3660 Where @code{gnatbind} might complain there was no valid order of
3661 elaboration, a C++ compiler would simply construct a program that
3662 malfunctioned at run time.
3663 @end ifclear
3664
3665 @node Comparison between GNAT and Conventional Ada Library Models
3666 @section Comparison between GNAT and Conventional Ada Library Models
3667
3668 @noindent
3669 This section is intended for Ada programmers who have
3670 used an Ada compiler implementing the traditional Ada library
3671 model, as described in the Ada Reference Manual.
3672
3673 @cindex GNAT library
3674 In GNAT, there is no ``library'' in the normal sense. Instead, the set of
3675 source files themselves acts as the library. Compiling Ada programs does
3676 not generate any centralized information, but rather an object file and
3677 a ALI file, which are of interest only to the binder and linker.
3678 In a traditional system, the compiler reads information not only from
3679 the source file being compiled, but also from the centralized library.
3680 This means that the effect of a compilation depends on what has been
3681 previously compiled. In particular:
3682
3683 @itemize @bullet
3684 @item
3685 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3686 to the version of the unit most recently compiled into the library.
3687
3688 @item
3689 Inlining is effective only if the necessary body has already been
3690 compiled into the library.
3691
3692 @item
3693 Compiling a unit may obsolete other units in the library.
3694 @end itemize
3695
3696 @noindent
3697 In GNAT, compiling one unit never affects the compilation of any other
3698 units because the compiler reads only source files. Only changes to source
3699 files can affect the results of a compilation. In particular:
3700
3701 @itemize @bullet
3702 @item
3703 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3704 to the source version of the unit that is currently accessible to the
3705 compiler.
3706
3707 @item
3708 @cindex Inlining
3709 Inlining requires the appropriate source files for the package or
3710 subprogram bodies to be available to the compiler. Inlining is always
3711 effective, independent of the order in which units are complied.
3712
3713 @item
3714 Compiling a unit never affects any other compilations. The editing of
3715 sources may cause previous compilations to be out of date if they
3716 depended on the source file being modified.
3717 @end itemize
3718
3719 @noindent
3720 The most important result of these differences is that order of compilation
3721 is never significant in GNAT. There is no situation in which one is
3722 required to do one compilation before another. What shows up as order of
3723 compilation requirements in the traditional Ada library becomes, in
3724 GNAT, simple source dependencies; in other words, there is only a set
3725 of rules saying what source files must be present when a file is
3726 compiled.
3727
3728 @ifset vms
3729 @node Placement of temporary files
3730 @section Placement of temporary files
3731 @cindex Temporary files (user control over placement)
3732
3733 @noindent
3734 GNAT creates temporary files in the directory designated by the environment
3735 variable @env{TMPDIR}.
3736 (See the HP @emph{C RTL Reference Manual} on the function @code{getenv()}
3737 for detailed information on how environment variables are resolved.
3738 For most users the easiest way to make use of this feature is to simply
3739 define @env{TMPDIR} as a job level logical name).
3740 For example, if you wish to use a Ramdisk (assuming DECRAM is installed)
3741 for compiler temporary files, then you can include something like the
3742 following command in your @file{LOGIN.COM} file:
3743
3744 @smallexample
3745 $ define/job TMPDIR "/disk$scratchram/000000/temp/"
3746 @end smallexample
3747
3748 @noindent
3749 If @env{TMPDIR} is not defined, then GNAT uses the directory designated by
3750 @env{TMP}; if @env{TMP} is not defined, then GNAT uses the directory
3751 designated by @env{TEMP}.
3752 If none of these environment variables are defined then GNAT uses the
3753 directory designated by the logical name @code{SYS$SCRATCH:}
3754 (by default the user's home directory). If all else fails
3755 GNAT uses the current directory for temporary files.
3756 @end ifset
3757
3758 @c *************************
3759 @node Compiling Using gcc
3760 @chapter Compiling Using @command{gcc}
3761
3762 @noindent
3763 This chapter discusses how to compile Ada programs using the @command{gcc}
3764 command. It also describes the set of switches
3765 that can be used to control the behavior of the compiler.
3766 @menu
3767 * Compiling Programs::
3768 * Switches for gcc::
3769 * Search Paths and the Run-Time Library (RTL)::
3770 * Order of Compilation Issues::
3771 * Examples::
3772 @end menu
3773
3774 @node Compiling Programs
3775 @section Compiling Programs
3776
3777 @noindent
3778 The first step in creating an executable program is to compile the units
3779 of the program using the @command{gcc} command. You must compile the
3780 following files:
3781
3782 @itemize @bullet
3783 @item
3784 the body file (@file{.adb}) for a library level subprogram or generic
3785 subprogram
3786
3787 @item
3788 the spec file (@file{.ads}) for a library level package or generic
3789 package that has no body
3790
3791 @item
3792 the body file (@file{.adb}) for a library level package
3793 or generic package that has a body
3794
3795 @end itemize
3796
3797 @noindent
3798 You need @emph{not} compile the following files
3799
3800 @itemize @bullet
3801
3802 @item
3803 the spec of a library unit which has a body
3804
3805 @item
3806 subunits
3807 @end itemize
3808
3809 @noindent
3810 because they are compiled as part of compiling related units. GNAT
3811 package specs
3812 when the corresponding body is compiled, and subunits when the parent is
3813 compiled.
3814
3815 @cindex cannot generate code
3816 If you attempt to compile any of these files, you will get one of the
3817 following error messages (where @var{fff} is the name of the file you
3818 compiled):
3819
3820 @smallexample
3821 cannot generate code for file @var{fff} (package spec)
3822 to check package spec, use -gnatc
3823
3824 cannot generate code for file @var{fff} (missing subunits)
3825 to check parent unit, use -gnatc
3826
3827 cannot generate code for file @var{fff} (subprogram spec)
3828 to check subprogram spec, use -gnatc
3829
3830 cannot generate code for file @var{fff} (subunit)
3831 to check subunit, use -gnatc
3832 @end smallexample
3833
3834 @noindent
3835 As indicated by the above error messages, if you want to submit
3836 one of these files to the compiler to check for correct semantics
3837 without generating code, then use the @option{-gnatc} switch.
3838
3839 The basic command for compiling a file containing an Ada unit is
3840
3841 @smallexample
3842 @c $ gcc -c @ovar{switches} @file{file name}
3843 @c Expanding @ovar macro inline (explanation in macro def comments)
3844 $ gcc -c @r{[}@var{switches}@r{]} @file{file name}
3845 @end smallexample
3846
3847 @noindent
3848 where @var{file name} is the name of the Ada file (usually
3849 having an extension
3850 @file{.ads} for a spec or @file{.adb} for a body).
3851 @ifclear vms
3852 You specify the
3853 @option{-c} switch to tell @command{gcc} to compile, but not link, the file.
3854 @end ifclear
3855 The result of a successful compilation is an object file, which has the
3856 same name as the source file but an extension of @file{.o} and an Ada
3857 Library Information (ALI) file, which also has the same name as the
3858 source file, but with @file{.ali} as the extension. GNAT creates these
3859 two output files in the current directory, but you may specify a source
3860 file in any directory using an absolute or relative path specification
3861 containing the directory information.
3862
3863 @findex gnat1
3864 @command{gcc} is actually a driver program that looks at the extensions of
3865 the file arguments and loads the appropriate compiler. For example, the
3866 GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}.
3867 These programs are in directories known to the driver program (in some
3868 configurations via environment variables you set), but need not be in
3869 your path. The @command{gcc} driver also calls the assembler and any other
3870 utilities needed to complete the generation of the required object
3871 files.
3872
3873 It is possible to supply several file names on the same @command{gcc}
3874 command. This causes @command{gcc} to call the appropriate compiler for
3875 each file. For example, the following command lists three separate
3876 files to be compiled:
3877
3878 @smallexample
3879 $ gcc -c x.adb y.adb z.c
3880 @end smallexample
3881
3882 @noindent
3883 calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and
3884 @file{y.adb}, and @code{cc1} (the C compiler) once to compile @file{z.c}.
3885 The compiler generates three object files @file{x.o}, @file{y.o} and
3886 @file{z.o} and the two ALI files @file{x.ali} and @file{y.ali} from the
3887 Ada compilations. Any switches apply to all the files ^listed,^listed.^
3888 @ifclear vms
3889 except for
3890 @option{-gnat@var{x}} switches, which apply only to Ada compilations.
3891 @end ifclear
3892
3893 @node Switches for gcc
3894 @section Switches for @command{gcc}
3895
3896 @noindent
3897 The @command{gcc} command accepts switches that control the
3898 compilation process. These switches are fully described in this section.
3899 First we briefly list all the switches, in alphabetical order, then we
3900 describe the switches in more detail in functionally grouped sections.
3901
3902 More switches exist for GCC than those documented here, especially
3903 for specific targets. However, their use is not recommended as
3904 they may change code generation in ways that are incompatible with
3905 the Ada run-time library, or can cause inconsistencies between
3906 compilation units.
3907
3908 @menu
3909 * Output and Error Message Control::
3910 * Warning Message Control::
3911 * Debugging and Assertion Control::
3912 * Validity Checking::
3913 * Style Checking::
3914 * Run-Time Checks::
3915 * Using gcc for Syntax Checking::
3916 * Using gcc for Semantic Checking::
3917 * Compiling Different Versions of Ada::
3918 * Character Set Control::
3919 * File Naming Control::
3920 * Subprogram Inlining Control::
3921 * Auxiliary Output Control::
3922 * Debugging Control::
3923 * Exception Handling Control::
3924 * Units to Sources Mapping Files::
3925 * Integrated Preprocessing::
3926 * Code Generation Control::
3927 @ifset vms
3928 * Return Codes::
3929 @end ifset
3930 @end menu
3931
3932 @table @option
3933 @c !sort!
3934 @ifclear vms
3935 @cindex @option{-b} (@command{gcc})
3936 @item -b @var{target}
3937 Compile your program to run on @var{target}, which is the name of a
3938 system configuration. You must have a GNAT cross-compiler built if
3939 @var{target} is not the same as your host system.
3940
3941 @item -B@var{dir}
3942 @cindex @option{-B} (@command{gcc})
3943 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
3944 from @var{dir} instead of the default location. Only use this switch
3945 when multiple versions of the GNAT compiler are available.
3946 @xref{Directory Options,, Options for Directory Search, gcc, Using the
3947 GNU Compiler Collection (GCC)}, for further details. You would normally
3948 use the @option{-b} or @option{-V} switch instead.
3949
3950 @item -c
3951 @cindex @option{-c} (@command{gcc})
3952 Compile. Always use this switch when compiling Ada programs.
3953
3954 Note: for some other languages when using @command{gcc}, notably in
3955 the case of C and C++, it is possible to use
3956 use @command{gcc} without a @option{-c} switch to
3957 compile and link in one step. In the case of GNAT, you
3958 cannot use this approach, because the binder must be run
3959 and @command{gcc} cannot be used to run the GNAT binder.
3960 @end ifclear
3961
3962 @item -fno-inline
3963 @cindex @option{-fno-inline} (@command{gcc})
3964 Suppresses all back-end inlining, even if other optimization or inlining
3965 switches are set.
3966 This includes suppression of inlining that results
3967 from the use of the pragma @code{Inline_Always}.
3968 Any occurrences of pragma @code{Inline} or @code{Inline_Always}
3969 are ignored, and @option{-gnatn} and @option{-gnatN} have no
3970 effect if this switch is present.
3971
3972 @item -fno-inline-functions
3973 @cindex @option{-fno-inline-functions} (@command{gcc})
3974 Suppresses automatic inlining of subprograms, which is enabled
3975 if @option{-O3} is used.
3976
3977 @item -fno-inline-small-functions
3978 @cindex @option{-fno-inline-small-functions} (@command{gcc})
3979 Suppresses automatic inlining of small subprograms, which is enabled
3980 if @option{-O2} is used.
3981
3982 @item -fno-inline-functions-called-once
3983 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
3984 Suppresses inlining of subprograms local to the unit and called once
3985 from within it, which is enabled if @option{-O1} is used.
3986
3987 @item -fno-ivopts
3988 @cindex @option{-fno-ivopts} (@command{gcc})
3989 Suppresses high-level loop induction variable optimizations, which are
3990 enabled if @option{-O1} is used. These optimizations are generally
3991 profitable but, for some specific cases of loops with numerous uses
3992 of the iteration variable that follow a common pattern, they may end
3993 up destroying the regularity that could be exploited at a lower level
3994 and thus producing inferior code.
3995
3996 @item -fno-strict-aliasing
3997 @cindex @option{-fno-strict-aliasing} (@command{gcc})
3998 Causes the compiler to avoid assumptions regarding non-aliasing
3999 of objects of different types. See
4000 @ref{Optimization and Strict Aliasing} for details.
4001
4002 @item -fstack-check
4003 @cindex @option{-fstack-check} (@command{gcc})
4004 Activates stack checking.
4005 See @ref{Stack Overflow Checking} for details.
4006
4007 @item -fstack-usage
4008 @cindex @option{-fstack-usage} (@command{gcc})
4009 Makes the compiler output stack usage information for the program, on a
4010 per-function basis. See @ref{Static Stack Usage Analysis} for details.
4011
4012 @item -fcallgraph-info@r{[}=su@r{]}
4013 @cindex @option{-fcallgraph-info} (@command{gcc})
4014 Makes the compiler output callgraph information for the program, on a
4015 per-file basis.  The information is generated in the VCG format.  It can
4016 be decorated with stack-usage per-node information.
4017
4018 @item ^-g^/DEBUG^
4019 @cindex @option{^-g^/DEBUG^} (@command{gcc})
4020 Generate debugging information. This information is stored in the object
4021 file and copied from there to the final executable file by the linker,
4022 where it can be read by the debugger. You must use the
4023 @option{^-g^/DEBUG^} switch if you plan on using the debugger.
4024
4025 @item -gnat83
4026 @cindex @option{-gnat83} (@command{gcc})
4027 Enforce Ada 83 restrictions.
4028
4029 @item -gnat95
4030 @cindex @option{-gnat95} (@command{gcc})
4031 Enforce Ada 95 restrictions.
4032
4033 @item -gnat05
4034 @cindex @option{-gnat05} (@command{gcc})
4035 Allow full Ada 2005 features.
4036
4037 @item -gnat2005
4038 @cindex @option{-gnat2005} (@command{gcc})
4039 Allow full Ada 2005 features (same as @option{-gnat05})
4040
4041 @item -gnat12
4042 @cindex @option{-gnat12} (@command{gcc})
4043
4044 @item -gnat2012
4045 @cindex @option{-gnat2012} (@command{gcc})
4046 Allow full Ada 2012 features (same as @option{-gnat12})
4047
4048 @item -gnata
4049 @cindex @option{-gnata} (@command{gcc})
4050 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
4051 activated. Note that these pragmas can also be controlled using the
4052 configuration pragmas @code{Assertion_Policy} and @code{Debug_Policy}.
4053 It also activates pragmas @code{Check}, @code{Precondition}, and
4054 @code{Postcondition}. Note that these pragmas can also be controlled
4055 using the configuration pragma @code{Check_Policy}.
4056
4057 @item -gnatA
4058 @cindex @option{-gnatA} (@command{gcc})
4059 Avoid processing @file{gnat.adc}. If a @file{gnat.adc} file is present,
4060 it will be ignored.
4061
4062 @item -gnatb
4063 @cindex @option{-gnatb} (@command{gcc})
4064 Generate brief messages to @file{stderr} even if verbose mode set.
4065
4066 @item -gnatB
4067 @cindex @option{-gnatB} (@command{gcc})
4068 Assume no invalid (bad) values except for 'Valid attribute use
4069 (@pxref{Validity Checking}).
4070
4071 @item -gnatc
4072 @cindex @option{-gnatc} (@command{gcc})
4073 Check syntax and semantics only (no code generation attempted).
4074
4075 @item -gnatC
4076 @cindex @option{-gnatC} (@command{gcc})
4077 Generate CodePeer information (no code generation attempted).
4078 This switch will generate an intermediate representation suitable for
4079 use by CodePeer (@file{.scil} files). This switch is not compatible with
4080 code generation (it will, among other things, disable some switches such
4081 as -gnatn, and enable others such as -gnata).
4082
4083 @item -gnatd
4084 @cindex @option{-gnatd} (@command{gcc})
4085 Specify debug options for the compiler. The string of characters after
4086 the @option{-gnatd} specify the specific debug options. The possible
4087 characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
4088 compiler source file @file{debug.adb} for details of the implemented
4089 debug options. Certain debug options are relevant to applications
4090 programmers, and these are documented at appropriate points in this
4091 users guide.
4092
4093 @ifclear vms
4094 @item -gnatD
4095 @cindex @option{-gnatD[nn]} (@command{gcc})
4096 @end ifclear
4097 @ifset vms
4098 @item /XDEBUG /LXDEBUG=nnn
4099 @end ifset
4100 Create expanded source files for source level debugging. This switch
4101 also suppress generation of cross-reference information
4102 (see @option{-gnatx}).
4103
4104 @item -gnatec=@var{path}
4105 @cindex @option{-gnatec} (@command{gcc})
4106 Specify a configuration pragma file
4107 @ifclear vms
4108 (the equal sign is optional)
4109 @end ifclear
4110 (@pxref{The Configuration Pragmas Files}).
4111
4112 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=@var{value}@r{]}
4113 @cindex @option{-gnateD} (@command{gcc})
4114 Defines a symbol, associated with @var{value}, for preprocessing.
4115 (@pxref{Integrated Preprocessing}).
4116
4117 @item -gnateE
4118 @cindex @option{-gnateE} (@command{gcc})
4119 Generate extra information in exception messages, in particular display
4120 extra column information and the value and range associated with index and
4121 range check failures, and extra column information for access checks.
4122
4123 @item -gnatef
4124 @cindex @option{-gnatef} (@command{gcc})
4125 Display full source path name in brief error messages.
4126
4127 @item -gnateG
4128 @cindex @option{-gnateG} (@command{gcc})
4129 Save result of preprocessing in a text file.
4130
4131 @item -gnatem=@var{path}
4132 @cindex @option{-gnatem} (@command{gcc})
4133 Specify a mapping file
4134 @ifclear vms
4135 (the equal sign is optional)
4136 @end ifclear
4137 (@pxref{Units to Sources Mapping Files}).
4138
4139 @item -gnatep=@var{file}
4140 @cindex @option{-gnatep} (@command{gcc})
4141 Specify a preprocessing data file
4142 @ifclear vms
4143 (the equal sign is optional)
4144 @end ifclear
4145 (@pxref{Integrated Preprocessing}).
4146
4147 @item -gnateP
4148 @cindex @option{-gnateP} (@command{gcc})
4149 Turn categorization dependency errors into warnings.
4150 Ada requires that units that WITH one another have compatible categories, for
4151 example a Pure unit cannto WITH a Preelaborate unit. If this switch is used,
4152 these errors become warnings (which can be ignored, or suppressed in the usual
4153 manner). This can be useful in some specialized circumstances such as the
4154 temporary use of special test software.
4155 @item -gnateS
4156 @cindex @option{-gnateS} (@command{gcc})
4157 Generate SCO (Source Coverage Obligation) information in the ALI
4158 file. This information is used by advanced coverage tools. See
4159 unit @file{SCOs} in the compiler sources for details in files
4160 @file{scos.ads} and @file{scos.adb}.
4161
4162 @item -gnatE
4163 @cindex @option{-gnatE} (@command{gcc})
4164 Full dynamic elaboration checks.
4165
4166 @item -gnatf
4167 @cindex @option{-gnatf} (@command{gcc})
4168 Full errors. Multiple errors per line, all undefined references, do not
4169 attempt to suppress cascaded errors.
4170
4171 @item -gnatF
4172 @cindex @option{-gnatF} (@command{gcc})
4173 Externals names are folded to all uppercase.
4174
4175 @item ^-gnatg^/GNAT_INTERNAL^
4176 @cindex @option{^-gnatg^/GNAT_INTERNAL^} (@command{gcc})
4177 Internal GNAT implementation mode. This should not be used for
4178 applications programs, it is intended only for use by the compiler
4179 and its run-time library. For documentation, see the GNAT sources.
4180 Note that @option{^-gnatg^/GNAT_INTERNAL^} implies
4181 @option{^-gnatwae^/WARNINGS=ALL,ERRORS^} and
4182 @option{^-gnatyg^/STYLE_CHECKS=GNAT^}
4183 so that all standard warnings and all standard style options are turned on.
4184 All warnings and style messages are treated as errors.
4185
4186 @ifclear vms
4187 @item -gnatG=nn
4188 @cindex @option{-gnatG[nn]} (@command{gcc})
4189 @end ifclear
4190 @ifset vms
4191 @item /EXPAND_SOURCE, /LEXPAND_SOURCE=nnn
4192 @end ifset
4193 List generated expanded code in source form.
4194
4195 @item ^-gnath^/HELP^
4196 @cindex @option{^-gnath^/HELP^} (@command{gcc})
4197 Output usage information. The output is written to @file{stdout}.
4198
4199 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
4200 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
4201 Identifier character set
4202 @ifclear vms
4203 (@var{c}=1/2/3/4/8/9/p/f/n/w).
4204 @end ifclear
4205 For details of the possible selections for @var{c},
4206 see @ref{Character Set Control}.
4207
4208 @item ^-gnatI^/IGNORE_REP_CLAUSES^
4209 @cindex @option{^-gnatI^IGNORE_REP_CLAUSES^} (@command{gcc})
4210 Ignore representation clauses. When this switch is used,
4211 representation clauses are treated as comments. This is useful
4212 when initially porting code where you want to ignore rep clause
4213 problems, and also for compiling foreign code (particularly
4214 for use with ASIS). The representation clauses that are ignored
4215 are: enumeration_representation_clause, record_representation_clause,
4216 and attribute_definition_clause for the following attributes:
4217 Address, Alignment, Bit_Order, Component_Size, Machine_Radix,
4218 Object_Size, Size, Small, Stream_Size, and Value_Size.
4219 Note that this option should be used only for compiling -- the
4220 code is likely to malfunction at run time.
4221
4222 @item -gnatjnn
4223 @cindex @option{-gnatjnn} (@command{gcc})
4224 Reformat error messages to fit on nn character lines
4225
4226 @item -gnatk=@var{n}
4227 @cindex @option{-gnatk} (@command{gcc})
4228 Limit file names to @var{n} (1-999) characters ^(@code{k} = krunch)^^.
4229
4230 @item -gnatl
4231 @cindex @option{-gnatl} (@command{gcc})
4232 Output full source listing with embedded error messages.
4233
4234 @item -gnatL
4235 @cindex @option{-gnatL} (@command{gcc})
4236 Used in conjunction with -gnatG or -gnatD to intersperse original
4237 source lines (as comment lines with line numbers) in the expanded
4238 source output.
4239
4240 @item -gnatm=@var{n}
4241 @cindex @option{-gnatm} (@command{gcc})
4242 Limit number of detected error or warning messages to @var{n}
4243 where @var{n} is in the range 1..999999. The default setting if
4244 no switch is given is 9999. If the number of warnings reaches this
4245 limit, then a message is output and further warnings are suppressed,
4246 but the compilation is continued. If the number of error messages
4247 reaches this limit, then a message is output and the compilation
4248 is abandoned. The equal sign here is optional. A value of zero
4249 means that no limit applies.
4250
4251 @item -gnatn
4252 @cindex @option{-gnatn} (@command{gcc})
4253 Activate inlining for subprograms for which
4254 pragma @code{Inline} is specified. This inlining is performed
4255 by the GCC back-end.
4256
4257 @item -gnatN
4258 @cindex @option{-gnatN} (@command{gcc})
4259 Activate front end inlining for subprograms for which
4260 pragma @code{Inline} is specified. This inlining is performed
4261 by the front end and will be visible in the
4262 @option{-gnatG} output.
4263
4264 When using a gcc-based back end (in practice this means using any version
4265 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
4266 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
4267 Historically front end inlining was more extensive than the gcc back end
4268 inlining, but that is no longer the case.
4269
4270 @item -gnato
4271 @cindex @option{-gnato} (@command{gcc})
4272 Enable numeric overflow checking (which is not normally enabled by
4273 default). Note that division by zero is a separate check that is not
4274 controlled by this switch (division by zero checking is on by default).
4275
4276 @item -gnatp
4277 @cindex @option{-gnatp} (@command{gcc})
4278 Suppress all checks. See @ref{Run-Time Checks} for details. This switch
4279 has no effect if cancelled by a subsequent @option{-gnat-p} switch.
4280
4281 @item -gnat-p
4282 @cindex @option{-gnat-p} (@command{gcc})
4283 Cancel effect of previous @option{-gnatp} switch.
4284
4285 @item -gnatP
4286 @cindex @option{-gnatP} (@command{gcc})
4287 Enable polling. This is required on some systems (notably Windows NT) to
4288 obtain asynchronous abort and asynchronous transfer of control capability.
4289 @xref{Pragma Polling,,, gnat_rm, GNAT Reference Manual}, for full
4290 details.
4291
4292 @item -gnatq
4293 @cindex @option{-gnatq} (@command{gcc})
4294 Don't quit. Try semantics, even if parse errors.
4295
4296 @item -gnatQ
4297 @cindex @option{-gnatQ} (@command{gcc})
4298 Don't quit. Generate @file{ALI} and tree files even if illegalities.
4299
4300 @item -gnatr
4301 @cindex @option{-gnatr} (@command{gcc})
4302 Treat pragma Restrictions as Restriction_Warnings.
4303
4304 @item ^-gnatR@r{[}0@r{/}1@r{/}2@r{/}3@r{[}s@r{]]}^/REPRESENTATION_INFO^
4305 @cindex @option{-gnatR} (@command{gcc})
4306 Output representation information for declared types and objects.
4307
4308 @item -gnats
4309 @cindex @option{-gnats} (@command{gcc})
4310 Syntax check only.
4311
4312 @item -gnatS
4313 @cindex @option{-gnatS} (@command{gcc})
4314 Print package Standard.
4315
4316 @item -gnatt
4317 @cindex @option{-gnatt} (@command{gcc})
4318 Generate tree output file.
4319
4320 @item ^-gnatT^/TABLE_MULTIPLIER=^@var{nnn}
4321 @cindex @option{^-gnatT^/TABLE_MULTIPLIER^} (@command{gcc})
4322 All compiler tables start at @var{nnn} times usual starting size.
4323
4324 @item -gnatu
4325 @cindex @option{-gnatu} (@command{gcc})
4326 List units for this compilation.
4327
4328 @item -gnatU
4329 @cindex @option{-gnatU} (@command{gcc})
4330 Tag all error messages with the unique string ``error:''
4331
4332 @item -gnatv
4333 @cindex @option{-gnatv} (@command{gcc})
4334 Verbose mode. Full error output with source lines to @file{stdout}.
4335
4336 @item -gnatV
4337 @cindex @option{-gnatV} (@command{gcc})
4338 Control level of validity checking (@pxref{Validity Checking}).
4339
4340 @item ^-gnatw@var{xxx}^/WARNINGS=(@var{option}@r{[},@dots{}@r{]})^
4341 @cindex @option{^-gnatw^/WARNINGS^} (@command{gcc})
4342 Warning mode where
4343 ^@var{xxx} is a string of option letters that^the list of options^ denotes
4344 the exact warnings that
4345 are enabled or disabled (@pxref{Warning Message Control}).
4346
4347 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
4348 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
4349 Wide character encoding method
4350 @ifclear vms
4351 (@var{e}=n/h/u/s/e/8).
4352 @end ifclear
4353 @ifset vms
4354 (@var{e}=@code{BRACKETS, NONE, HEX, UPPER, SHIFT_JIS, EUC, UTF8})
4355 @end ifset
4356
4357 @item -gnatx
4358 @cindex @option{-gnatx} (@command{gcc})
4359 Suppress generation of cross-reference information.
4360
4361 @item -gnatX
4362 @cindex @option{-gnatX} (@command{gcc})
4363 Enable GNAT implementation extensions and latest Ada version.
4364
4365 @item ^-gnaty^/STYLE_CHECKS=(option,option@dots{})^
4366 @cindex @option{^-gnaty^/STYLE_CHECKS^} (@command{gcc})
4367 Enable built-in style checks (@pxref{Style Checking}).
4368
4369 @item ^-gnatz^/DISTRIBUTION_STUBS=^@var{m}
4370 @cindex @option{^-gnatz^/DISTRIBUTION_STUBS^} (@command{gcc})
4371 Distribution stub generation and compilation
4372 @ifclear vms
4373 (@var{m}=r/c for receiver/caller stubs).
4374 @end ifclear
4375 @ifset vms
4376 (@var{m}=@code{RECEIVER} or @code{CALLER} to specify the type of stubs
4377 to be generated and compiled).
4378 @end ifset
4379
4380 @item ^-I^/SEARCH=^@var{dir}
4381 @cindex @option{^-I^/SEARCH^} (@command{gcc})
4382 @cindex RTL
4383 Direct GNAT to search the @var{dir} directory for source files needed by
4384 the current compilation
4385 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4386
4387 @item ^-I-^/NOCURRENT_DIRECTORY^
4388 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gcc})
4389 @cindex RTL
4390 Except for the source file named in the command line, do not look for source
4391 files in the directory containing the source file named in the command line
4392 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4393
4394 @ifclear vms
4395 @item -mbig-switch
4396 @cindex @option{-mbig-switch} (@command{gcc})
4397 @cindex @code{case} statement (effect of @option{-mbig-switch} option)
4398 This standard gcc switch causes the compiler to use larger offsets in its
4399 jump table representation for @code{case} statements.
4400 This may result in less efficient code, but is sometimes necessary
4401 (for example on HP-UX targets)
4402 @cindex HP-UX and @option{-mbig-switch} option
4403 in order to compile large and/or nested @code{case} statements.
4404
4405 @item -o @var{file}
4406 @cindex @option{-o} (@command{gcc})
4407 This switch is used in @command{gcc} to redirect the generated object file
4408 and its associated ALI file. Beware of this switch with GNAT, because it may
4409 cause the object file and ALI file to have different names which in turn
4410 may confuse the binder and the linker.
4411 @end ifclear
4412
4413 @item -nostdinc
4414 @cindex @option{-nostdinc} (@command{gcc})
4415 Inhibit the search of the default location for the GNAT Run Time
4416 Library (RTL) source files.
4417
4418 @item -nostdlib
4419 @cindex @option{-nostdlib} (@command{gcc})
4420 Inhibit the search of the default location for the GNAT Run Time
4421 Library (RTL) ALI files.
4422
4423 @ifclear vms
4424 @c @item -O@ovar{n}
4425 @c Expanding @ovar macro inline (explanation in macro def comments)
4426 @item -O@r{[}@var{n}@r{]}
4427 @cindex @option{-O} (@command{gcc})
4428 @var{n} controls the optimization level.
4429
4430 @table @asis
4431 @item n = 0
4432 No optimization, the default setting if no @option{-O} appears
4433
4434 @item n = 1
4435 Normal optimization, the default if you specify @option{-O} without
4436 an operand. A good compromise between code quality and compilation
4437 time.
4438
4439 @item n = 2
4440 Extensive optimization, may improve execution time, possibly at the cost of
4441 substantially increased compilation time.
4442
4443 @item n = 3
4444 Same as @option{-O2}, and also includes inline expansion for small subprograms
4445 in the same unit.
4446
4447 @item n = s
4448 Optimize space usage
4449 @end table
4450
4451 @noindent
4452 See also @ref{Optimization Levels}.
4453 @end ifclear
4454
4455 @ifset vms
4456 @item  /NOOPTIMIZE
4457 @cindex @option{/NOOPTIMIZE} (@code{GNAT COMPILE})
4458 Equivalent to @option{/OPTIMIZE=NONE}.
4459 This is the default behavior in the absence of an @option{/OPTIMIZE}
4460 qualifier.
4461
4462 @item /OPTIMIZE@r{[}=(keyword@r{[},@dots{}@r{]})@r{]}
4463 @cindex @option{/OPTIMIZE} (@code{GNAT COMPILE})
4464 Selects the level of optimization for your program. The supported
4465 keywords are as follows:
4466 @table @code
4467 @item   ALL
4468 Perform most optimizations, including those that
4469 are expensive.
4470 This is the default if the @option{/OPTIMIZE} qualifier is supplied
4471 without keyword options.
4472
4473 @item   NONE
4474 Do not do any optimizations. Same as @code{/NOOPTIMIZE}.
4475
4476 @item SOME
4477 Perform some optimizations, but omit ones that are costly.
4478
4479 @item   DEVELOPMENT
4480 Same as @code{SOME}.
4481
4482 @item INLINING
4483 Full optimization as in @option{/OPTIMIZE=ALL}, and also attempts
4484 automatic inlining of small subprograms within a unit
4485
4486 @item   UNROLL_LOOPS
4487 Try to unroll loops. This keyword may be specified together with
4488 any keyword above other than @code{NONE}. Loop unrolling
4489 usually, but not always, improves the performance of programs.
4490
4491 @item SPACE
4492 Optimize space usage
4493 @end table
4494
4495 @noindent
4496 See also @ref{Optimization Levels}.
4497 @end ifset
4498
4499 @ifclear vms
4500 @item -pass-exit-codes
4501 @cindex @option{-pass-exit-codes} (@command{gcc})
4502 Catch exit codes from the compiler and use the most meaningful as
4503 exit status.
4504 @end ifclear
4505
4506 @item --RTS=@var{rts-path}
4507 @cindex @option{--RTS} (@command{gcc})
4508 Specifies the default location of the runtime library. Same meaning as the
4509 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
4510
4511 @item ^-S^/ASM^
4512 @cindex @option{^-S^/ASM^} (@command{gcc})
4513 ^Used in place of @option{-c} to^Used to^
4514 cause the assembler source file to be
4515 generated, using @file{^.s^.S^} as the extension,
4516 instead of the object file.
4517 This may be useful if you need to examine the generated assembly code.
4518
4519 @item ^-fverbose-asm^/VERBOSE_ASM^
4520 @cindex @option{^-fverbose-asm^/VERBOSE_ASM^} (@command{gcc})
4521 ^Used in conjunction with @option{-S}^Used in place of @option{/ASM}^
4522 to cause the generated assembly code file to be annotated with variable
4523 names, making it significantly easier to follow.
4524
4525 @item ^-v^/VERBOSE^
4526 @cindex @option{^-v^/VERBOSE^} (@command{gcc})
4527 Show commands generated by the @command{gcc} driver. Normally used only for
4528 debugging purposes or if you need to be sure what version of the
4529 compiler you are executing.
4530
4531 @ifclear vms
4532 @item -V @var{ver}
4533 @cindex @option{-V} (@command{gcc})
4534 Execute @var{ver} version of the compiler. This is the @command{gcc}
4535 version, not the GNAT version.
4536 @end ifclear
4537
4538 @item ^-w^/NO_BACK_END_WARNINGS^
4539 @cindex @option{-w} (@command{gcc})
4540 Turn off warnings generated by the back end of the compiler. Use of
4541 this switch also causes the default for front end warnings to be set
4542 to suppress (as though @option{-gnatws} had appeared at the start of
4543 the options).
4544
4545 @end table
4546
4547 @ifclear vms
4548 @c Combining qualifiers does not work on VMS
4549 You may combine a sequence of GNAT switches into a single switch. For
4550 example, the combined switch
4551
4552 @cindex Combining GNAT switches
4553 @smallexample
4554 -gnatofi3
4555 @end smallexample
4556
4557 @noindent
4558 is equivalent to specifying the following sequence of switches:
4559
4560 @smallexample
4561 -gnato -gnatf -gnati3
4562 @end smallexample
4563 @end ifclear
4564
4565 @noindent
4566 The following restrictions apply to the combination of switches
4567 in this manner:
4568
4569 @itemize @bullet
4570 @item
4571 The switch @option{-gnatc} if combined with other switches must come
4572 first in the string.
4573
4574 @item
4575 The switch @option{-gnats} if combined with other switches must come
4576 first in the string.
4577
4578 @item
4579 The switches
4580 ^^@option{/DISTRIBUTION_STUBS=},^
4581 @option{-gnatzc} and @option{-gnatzr} may not be combined with any other
4582 switches, and only one of them may appear in the command line.
4583
4584 @item
4585 The switch @option{-gnat-p} may not be combined with any other switch.
4586
4587 @ifclear vms
4588 @item
4589 Once a ``y'' appears in the string (that is a use of the @option{-gnaty}
4590 switch), then all further characters in the switch are interpreted
4591 as style modifiers (see description of @option{-gnaty}).
4592
4593 @item
4594 Once a ``d'' appears in the string (that is a use of the @option{-gnatd}
4595 switch), then all further characters in the switch are interpreted
4596 as debug flags (see description of @option{-gnatd}).
4597
4598 @item
4599 Once a ``w'' appears in the string (that is a use of the @option{-gnatw}
4600 switch), then all further characters in the switch are interpreted
4601 as warning mode modifiers (see description of @option{-gnatw}).
4602
4603 @item
4604 Once a ``V'' appears in the string (that is a use of the @option{-gnatV}
4605 switch), then all further characters in the switch are interpreted
4606 as validity checking options (@pxref{Validity Checking}).
4607
4608 @item
4609 Option ``em'', ``ec'', ``ep'', ``l='' and ``R'' must be the last options in
4610 a combined list of options.
4611 @end ifclear
4612 @end itemize
4613
4614 @node Output and Error Message Control
4615 @subsection Output and Error Message Control
4616 @findex stderr
4617
4618 @noindent
4619 The standard default format for error messages is called ``brief format''.
4620 Brief format messages are written to @file{stderr} (the standard error
4621 file) and have the following form:
4622
4623 @smallexample
4624 e.adb:3:04: Incorrect spelling of keyword "function"
4625 e.adb:4:20: ";" should be "is"
4626 @end smallexample
4627
4628 @noindent
4629 The first integer after the file name is the line number in the file,
4630 and the second integer is the column number within the line.
4631 @ifclear vms
4632 @code{GPS} can parse the error messages
4633 and point to the referenced character.
4634 @end ifclear
4635 The following switches provide control over the error message
4636 format:
4637
4638 @table @option
4639 @c !sort!
4640 @item -gnatv
4641 @cindex @option{-gnatv} (@command{gcc})
4642 @findex stdout
4643 @ifclear vms
4644 The v stands for verbose.
4645 @end ifclear
4646 The effect of this setting is to write long-format error
4647 messages to @file{stdout} (the standard output file.
4648 The same program compiled with the
4649 @option{-gnatv} switch would generate:
4650
4651 @smallexample
4652 @cartouche
4653 3. funcion X (Q : Integer)
4654    |
4655 >>> Incorrect spelling of keyword "function"
4656 4. return Integer;
4657                  |
4658 >>> ";" should be "is"
4659 @end cartouche
4660 @end smallexample
4661
4662 @noindent
4663 The vertical bar indicates the location of the error, and the @samp{>>>}
4664 prefix can be used to search for error messages. When this switch is
4665 used the only source lines output are those with errors.
4666
4667 @item -gnatl
4668 @cindex @option{-gnatl} (@command{gcc})
4669 @ifclear vms
4670 The @code{l} stands for list.
4671 @end ifclear
4672 This switch causes a full listing of
4673 the file to be generated. In the case where a body is
4674 compiled, the corresponding spec is also listed, along
4675 with any subunits. Typical output from compiling a package
4676 body @file{p.adb} might look like:
4677
4678 @smallexample @c ada
4679 @cartouche
4680  Compiling: p.adb
4681
4682      1. package body p is
4683      2.    procedure a;
4684      3.    procedure a is separate;
4685      4. begin
4686      5.    null
4687                |
4688         >>> missing ";"
4689
4690      6. end;
4691
4692 Compiling: p.ads
4693
4694      1. package p is
4695      2.    pragma Elaborate_Body
4696                                 |
4697         >>> missing ";"
4698
4699      3. end p;
4700
4701 Compiling: p-a.adb
4702
4703      1. separate p
4704                 |
4705         >>> missing "("
4706
4707      2. procedure a is
4708      3. begin
4709      4.    null
4710                |
4711         >>> missing ";"
4712
4713      5. end;
4714 @end cartouche
4715 @end smallexample
4716
4717 @noindent
4718 @findex stderr
4719 When you specify the @option{-gnatv} or @option{-gnatl} switches and
4720 standard output is redirected, a brief summary is written to
4721 @file{stderr} (standard error) giving the number of error messages and
4722 warning messages generated.
4723
4724 @item ^-gnatl^/OUTPUT_FILE^=file
4725 @cindex @option{^-gnatl^/OUTPUT_FILE^=fname} (@command{gcc})
4726 This has the same effect as @option{-gnatl} except that the output is
4727 written to a file instead of to standard output. If the given name
4728 @file{fname} does not start with a period, then it is the full name
4729 of the file to be written. If @file{fname} is an extension, it is
4730 appended to the name of the file being compiled. For example, if
4731 file @file{xyz.adb} is compiled with @option{^-gnatl^/OUTPUT_FILE^=.lst},
4732 then the output is written to file ^xyz.adb.lst^xyz.adb_lst^.
4733
4734 @item -gnatU
4735 @cindex @option{-gnatU} (@command{gcc})
4736 This switch forces all error messages to be preceded by the unique
4737 string ``error:''. This means that error messages take a few more
4738 characters in space, but allows easy searching for and identification
4739 of error messages.
4740
4741 @item -gnatb
4742 @cindex @option{-gnatb} (@command{gcc})
4743 @ifclear vms
4744 The @code{b} stands for brief.
4745 @end ifclear
4746 This switch causes GNAT to generate the
4747 brief format error messages to @file{stderr} (the standard error
4748 file) as well as the verbose
4749 format message or full listing (which as usual is written to
4750 @file{stdout} (the standard output file).
4751
4752 @item -gnatm=@var{n}
4753 @cindex @option{-gnatm} (@command{gcc})
4754 @ifclear vms
4755 The @code{m} stands for maximum.
4756 @end ifclear
4757 @var{n} is a decimal integer in the
4758 range of 1 to 999999 and limits the number of error or warning
4759 messages to be generated. For example, using
4760 @option{-gnatm2} might yield
4761
4762 @smallexample
4763 e.adb:3:04: Incorrect spelling of keyword "function"
4764 e.adb:5:35: missing ".."
4765 fatal error: maximum number of errors detected
4766 compilation abandoned
4767 @end smallexample
4768
4769 @noindent
4770 The default setting if
4771 no switch is given is 9999. If the number of warnings reaches this
4772 limit, then a message is output and further warnings are suppressed,
4773 but the compilation is continued. If the number of error messages
4774 reaches this limit, then a message is output and the compilation
4775 is abandoned. A value of zero means that no limit applies.
4776
4777 @noindent
4778 Note that the equal sign is optional, so the switches
4779 @option{-gnatm2} and @option{-gnatm=2} are equivalent.
4780
4781 @item -gnatf
4782 @cindex @option{-gnatf} (@command{gcc})
4783 @cindex Error messages, suppressing
4784 @ifclear vms
4785 The @code{f} stands for full.
4786 @end ifclear
4787 Normally, the compiler suppresses error messages that are likely to be
4788 redundant. This switch causes all error
4789 messages to be generated. In particular, in the case of
4790 references to undefined variables. If a given variable is referenced
4791 several times, the normal format of messages is
4792 @smallexample
4793 e.adb:7:07: "V" is undefined (more references follow)
4794 @end smallexample
4795
4796 @noindent
4797 where the parenthetical comment warns that there are additional
4798 references to the variable @code{V}. Compiling the same program with the
4799 @option{-gnatf} switch yields
4800
4801 @smallexample
4802 e.adb:7:07: "V" is undefined
4803 e.adb:8:07: "V" is undefined
4804 e.adb:8:12: "V" is undefined
4805 e.adb:8:16: "V" is undefined
4806 e.adb:9:07: "V" is undefined
4807 e.adb:9:12: "V" is undefined
4808 @end smallexample
4809
4810 @noindent
4811 The @option{-gnatf} switch also generates additional information for
4812 some error messages.  Some examples are:
4813
4814 @itemize @bullet
4815 @item
4816 Details on possibly non-portable unchecked conversion
4817 @item
4818 List possible interpretations for ambiguous calls
4819 @item
4820 Additional details on incorrect parameters
4821 @end itemize
4822
4823 @item -gnatjnn
4824 @cindex @option{-gnatjnn} (@command{gcc})
4825 In normal operation mode (or if @option{-gnatj0} is used, then error messages
4826 with continuation lines are treated as though the continuation lines were
4827 separate messages (and so a warning with two continuation lines counts as
4828 three warnings, and is listed as three separate messages).
4829
4830 If the @option{-gnatjnn} switch is used with a positive value for nn, then
4831 messages are output in a different manner. A message and all its continuation
4832 lines are treated as a unit, and count as only one warning or message in the
4833 statistics totals. Furthermore, the message is reformatted so that no line
4834 is longer than nn characters.
4835
4836 @item -gnatq
4837 @cindex @option{-gnatq} (@command{gcc})
4838 @ifclear vms
4839 The @code{q} stands for quit (really ``don't quit'').
4840 @end ifclear
4841 In normal operation mode, the compiler first parses the program and
4842 determines if there are any syntax errors. If there are, appropriate
4843 error messages are generated and compilation is immediately terminated.
4844 This switch tells
4845 GNAT to continue with semantic analysis even if syntax errors have been
4846 found. This may enable the detection of more errors in a single run. On
4847 the other hand, the semantic analyzer is more likely to encounter some
4848 internal fatal error when given a syntactically invalid tree.
4849
4850 @item -gnatQ
4851 @cindex @option{-gnatQ} (@command{gcc})
4852 In normal operation mode, the @file{ALI} file is not generated if any
4853 illegalities are detected in the program. The use of @option{-gnatQ} forces
4854 generation of the @file{ALI} file. This file is marked as being in
4855 error, so it cannot be used for binding purposes, but it does contain
4856 reasonably complete cross-reference information, and thus may be useful
4857 for use by tools (e.g., semantic browsing tools or integrated development
4858 environments) that are driven from the @file{ALI} file. This switch
4859 implies @option{-gnatq}, since the semantic phase must be run to get a
4860 meaningful ALI file.
4861
4862 In addition, if @option{-gnatt} is also specified, then the tree file is
4863 generated even if there are illegalities. It may be useful in this case
4864 to also specify @option{-gnatq} to ensure that full semantic processing
4865 occurs. The resulting tree file can be processed by ASIS, for the purpose
4866 of providing partial information about illegal units, but if the error
4867 causes the tree to be badly malformed, then ASIS may crash during the
4868 analysis.
4869
4870 When @option{-gnatQ} is used and the generated @file{ALI} file is marked as
4871 being in error, @command{gnatmake} will attempt to recompile the source when it
4872 finds such an @file{ALI} file, including with switch @option{-gnatc}.
4873
4874 Note that @option{-gnatQ} has no effect if @option{-gnats} is specified,
4875 since ALI files are never generated if @option{-gnats} is set.
4876
4877 @end table
4878
4879 @node Warning Message Control
4880 @subsection Warning Message Control
4881 @cindex Warning messages
4882 @noindent
4883 In addition to error messages, which correspond to illegalities as defined
4884 in the Ada Reference Manual, the compiler detects two kinds of warning
4885 situations.
4886
4887 First, the compiler considers some constructs suspicious and generates a
4888 warning message to alert you to a possible error. Second, if the
4889 compiler detects a situation that is sure to raise an exception at
4890 run time, it generates a warning message. The following shows an example
4891 of warning messages:
4892 @smallexample
4893 e.adb:4:24: warning: creation of object may raise Storage_Error
4894 e.adb:10:17: warning: static value out of range
4895 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
4896 @end smallexample
4897
4898 @noindent
4899 GNAT considers a large number of situations as appropriate
4900 for the generation of warning messages. As always, warnings are not
4901 definite indications of errors. For example, if you do an out-of-range
4902 assignment with the deliberate intention of raising a
4903 @code{Constraint_Error} exception, then the warning that may be
4904 issued does not indicate an error. Some of the situations for which GNAT
4905 issues warnings (at least some of the time) are given in the following
4906 list. This list is not complete, and new warnings are often added to
4907 subsequent versions of GNAT. The list is intended to give a general idea
4908 of the kinds of warnings that are generated.
4909
4910 @itemize @bullet
4911 @item
4912 Possible infinitely recursive calls
4913
4914 @item
4915 Out-of-range values being assigned
4916
4917 @item
4918 Possible order of elaboration problems
4919
4920 @item
4921 Assertions (pragma Assert) that are sure to fail
4922
4923 @item
4924 Unreachable code
4925
4926 @item
4927 Address clauses with possibly unaligned values, or where an attempt is
4928 made to overlay a smaller variable with a larger one.
4929
4930 @item
4931 Fixed-point type declarations with a null range
4932
4933 @item
4934 Direct_IO or Sequential_IO instantiated with a type that has access values
4935
4936 @item
4937 Variables that are never assigned a value
4938
4939 @item
4940 Variables that are referenced before being initialized
4941
4942 @item
4943 Task entries with no corresponding @code{accept} statement
4944
4945 @item
4946 Duplicate accepts for the same task entry in a @code{select}
4947
4948 @item
4949 Objects that take too much storage
4950
4951 @item
4952 Unchecked conversion between types of differing sizes
4953
4954 @item
4955 Missing @code{return} statement along some execution path in a function
4956
4957 @item
4958 Incorrect (unrecognized) pragmas
4959
4960 @item
4961 Incorrect external names
4962
4963 @item
4964 Allocation from empty storage pool
4965
4966 @item
4967 Potentially blocking operation in protected type
4968
4969 @item
4970 Suspicious parenthesization of expressions
4971
4972 @item
4973 Mismatching bounds in an aggregate
4974
4975 @item
4976 Attempt to return local value by reference
4977
4978 @item
4979 Premature instantiation of a generic body
4980
4981 @item
4982 Attempt to pack aliased components
4983
4984 @item
4985 Out of bounds array subscripts
4986
4987 @item
4988 Wrong length on string assignment
4989
4990 @item
4991 Violations of style rules if style checking is enabled
4992
4993 @item
4994 Unused @code{with} clauses
4995
4996 @item
4997 @code{Bit_Order} usage that does not have any effect
4998
4999 @item
5000 @code{Standard.Duration} used to resolve universal fixed expression
5001
5002 @item
5003 Dereference of possibly null value
5004
5005 @item
5006 Declaration that is likely to cause storage error
5007
5008 @item
5009 Internal GNAT unit @code{with}'ed by application unit
5010
5011 @item
5012 Values known to be out of range at compile time
5013
5014 @item
5015 Unreferenced labels and variables
5016
5017 @item
5018 Address overlays that could clobber memory
5019
5020 @item
5021 Unexpected initialization when address clause present
5022
5023 @item
5024 Bad alignment for address clause
5025
5026 @item
5027 Useless type conversions
5028
5029 @item
5030 Redundant assignment statements and other redundant constructs
5031
5032 @item
5033 Useless exception handlers
5034
5035 @item
5036 Accidental hiding of name by child unit
5037
5038 @item
5039 Access before elaboration detected at compile time
5040
5041 @item
5042 A range in a @code{for} loop that is known to be null or might be null
5043
5044 @end itemize
5045
5046 @noindent
5047 The following section lists compiler switches that are available
5048 to control the handling of warning messages. It is also possible
5049 to exercise much finer control over what warnings are issued and
5050 suppressed using the GNAT pragma Warnings, @xref{Pragma Warnings,,,
5051 gnat_rm, GNAT Reference manual}.
5052
5053 @table @option
5054 @c !sort!
5055 @item -gnatwa
5056 @emph{Activate most optional warnings.}
5057 @cindex @option{-gnatwa} (@command{gcc})
5058 This switch activates most optional warning messages.  See the remaining list
5059 in this section for details on optional warning messages that can be
5060 individually controlled.  The warnings that are not turned on by this
5061 switch are
5062 @option{-gnatwd} (implicit dereferencing),
5063 @option{-gnatwh} (hiding),
5064 @option{-gnatw.h} (holes (gaps) in record layouts)
5065 @option{-gnatwl} (elaboration warnings),
5066 @option{-gnatw.o} (warn on values set by out parameters ignored)
5067 and @option{-gnatwt} (tracking of deleted conditional code).
5068 All other optional warnings are turned on.
5069
5070 @item -gnatwA
5071 @emph{Suppress all optional errors.}
5072 @cindex @option{-gnatwA} (@command{gcc})
5073 This switch suppresses all optional warning messages, see remaining list
5074 in this section for details on optional warning messages that can be
5075 individually controlled.
5076
5077 @item -gnatw.a
5078 @emph{Activate warnings on failing assertions.}
5079 @cindex @option{-gnatw.a} (@command{gcc})
5080 @cindex Assert failures
5081 This switch activates warnings for assertions where the compiler can tell at
5082 compile time that the assertion will fail. Note that this warning is given
5083 even if assertions are disabled. The default is that such warnings are
5084 generated.
5085
5086 @item -gnatw.A
5087 @emph{Suppress warnings on failing assertions.}
5088 @cindex @option{-gnatw.A} (@command{gcc})
5089 @cindex Assert failures
5090 This switch suppresses warnings for assertions where the compiler can tell at
5091 compile time that the assertion will fail.
5092
5093 @item -gnatwb
5094 @emph{Activate warnings on bad fixed values.}
5095 @cindex @option{-gnatwb} (@command{gcc})
5096 @cindex Bad fixed values
5097 @cindex Fixed-point Small value
5098 @cindex Small value
5099 This switch activates warnings for static fixed-point expressions whose
5100 value is not an exact multiple of Small. Such values are implementation
5101 dependent, since an implementation is free to choose either of the multiples
5102 that surround the value. GNAT always chooses the closer one, but this is not
5103 required behavior, and it is better to specify a value that is an exact
5104 multiple, ensuring predictable execution. The default is that such warnings
5105 are not generated.
5106
5107 @item -gnatwB
5108 @emph{Suppress warnings on bad fixed values.}
5109 @cindex @option{-gnatwB} (@command{gcc})
5110 This switch suppresses warnings for static fixed-point expressions whose
5111 value is not an exact multiple of Small.
5112
5113 @item -gnatw.b
5114 @emph{Activate warnings on biased representation.}
5115 @cindex @option{-gnatw.b} (@command{gcc})
5116 @cindex Biased representation
5117 This switch activates warnings when a size clause, value size clause, component
5118 clause, or component size clause forces the use of biased representation for an
5119 integer type (e.g. representing a range of 10..11 in a single bit by using 0/1
5120 to represent 10/11). The default is that such warnings are generated.
5121
5122 @item -gnatw.B
5123 @emph{Suppress warnings on biased representation.}
5124 @cindex @option{-gnatwB} (@command{gcc})
5125 This switch suppresses warnings for representation clauses that force the use
5126 of biased representation.
5127
5128 @item -gnatwc
5129 @emph{Activate warnings on conditionals.}
5130 @cindex @option{-gnatwc} (@command{gcc})
5131 @cindex Conditionals, constant
5132 This switch activates warnings for conditional expressions used in
5133 tests that are known to be True or False at compile time. The default
5134 is that such warnings are not generated.
5135 Note that this warning does
5136 not get issued for the use of boolean variables or constants whose
5137 values are known at compile time, since this is a standard technique
5138 for conditional compilation in Ada, and this would generate too many
5139 false positive warnings.
5140
5141 This warning option also activates a special test for comparisons using
5142 the operators ``>='' and`` <=''.
5143 If the compiler can tell that only the equality condition is possible,
5144 then it will warn that the ``>'' or ``<'' part of the test
5145 is useless and that the operator could be replaced by ``=''.
5146 An example would be comparing a @code{Natural} variable <= 0.
5147
5148 This warning option also generates warnings if
5149 one or both tests is optimized away in a membership test for integer
5150 values if the result can be determined at compile time. Range tests on
5151 enumeration types are not included, since it is common for such tests
5152 to include an end point.
5153
5154 This warning can also be turned on using @option{-gnatwa}.
5155
5156 @item -gnatwC
5157 @emph{Suppress warnings on conditionals.}
5158 @cindex @option{-gnatwC} (@command{gcc})
5159 This switch suppresses warnings for conditional expressions used in
5160 tests that are known to be True or False at compile time.
5161
5162 @item -gnatw.c
5163 @emph{Activate warnings on missing component clauses.}
5164 @cindex @option{-gnatw.c} (@command{gcc})
5165 @cindex Component clause, missing
5166 This switch activates warnings for record components where a record
5167 representation clause is present and has component clauses for the
5168 majority, but not all, of the components. A warning is given for each
5169 component for which no component clause is present.
5170
5171 This warning can also be turned on using @option{-gnatwa}.
5172
5173 @item -gnatw.C
5174 @emph{Suppress warnings on missing component clauses.}
5175 @cindex @option{-gnatwC} (@command{gcc})
5176 This switch suppresses warnings for record components that are
5177 missing a component clause in the situation described above.
5178
5179 @item -gnatwd
5180 @emph{Activate warnings on implicit dereferencing.}
5181 @cindex @option{-gnatwd} (@command{gcc})
5182 If this switch is set, then the use of a prefix of an access type
5183 in an indexed component, slice, or selected component without an
5184 explicit @code{.all} will generate a warning. With this warning
5185 enabled, access checks occur only at points where an explicit
5186 @code{.all} appears in the source code (assuming no warnings are
5187 generated as a result of this switch). The default is that such
5188 warnings are not generated.
5189 Note that @option{-gnatwa} does not affect the setting of
5190 this warning option.
5191
5192 @item -gnatwD
5193 @emph{Suppress warnings on implicit dereferencing.}
5194 @cindex @option{-gnatwD} (@command{gcc})
5195 @cindex Implicit dereferencing
5196 @cindex Dereferencing, implicit
5197 This switch suppresses warnings for implicit dereferences in
5198 indexed components, slices, and selected components.
5199
5200 @item -gnatwe
5201 @emph{Treat warnings and style checks as errors.}
5202 @cindex @option{-gnatwe} (@command{gcc})
5203 @cindex Warnings, treat as error
5204 This switch causes warning messages and style check messages to be
5205 treated as errors.
5206 The warning string still appears, but the warning messages are counted
5207 as errors, and prevent the generation of an object file. Note that this
5208 is the only -gnatw switch that affects the handling of style check messages.
5209
5210 @item -gnatw.e
5211 @emph{Activate every optional warning}
5212 @cindex @option{-gnatw.e} (@command{gcc})
5213 @cindex Warnings, activate every optional warning
5214 This switch activates all optional warnings, including those which
5215 are not activated by @code{-gnatwa}.
5216
5217 @item -gnatwf
5218 @emph{Activate warnings on unreferenced formals.}
5219 @cindex @option{-gnatwf} (@command{gcc})
5220 @cindex Formals, unreferenced
5221 This switch causes a warning to be generated if a formal parameter
5222 is not referenced in the body of the subprogram. This warning can
5223 also be turned on using @option{-gnatwa} or @option{-gnatwu}. The
5224 default is that these warnings are not generated.
5225
5226 @item -gnatwF
5227 @emph{Suppress warnings on unreferenced formals.}
5228 @cindex @option{-gnatwF} (@command{gcc})
5229 This switch suppresses warnings for unreferenced formal
5230 parameters. Note that the
5231 combination @option{-gnatwu} followed by @option{-gnatwF} has the
5232 effect of warning on unreferenced entities other than subprogram
5233 formals.
5234
5235 @item -gnatwg
5236 @emph{Activate warnings on unrecognized pragmas.}
5237 @cindex @option{-gnatwg} (@command{gcc})
5238 @cindex Pragmas, unrecognized
5239 This switch causes a warning to be generated if an unrecognized
5240 pragma is encountered. Apart from issuing this warning, the
5241 pragma is ignored and has no effect. This warning can
5242 also be turned on using @option{-gnatwa}. The default
5243 is that such warnings are issued (satisfying the Ada Reference
5244 Manual requirement that such warnings appear).
5245
5246 @item -gnatwG
5247 @emph{Suppress warnings on unrecognized pragmas.}
5248 @cindex @option{-gnatwG} (@command{gcc})
5249 This switch suppresses warnings for unrecognized pragmas.
5250
5251 @item -gnatwh
5252 @emph{Activate warnings on hiding.}
5253 @cindex @option{-gnatwh} (@command{gcc})
5254 @cindex Hiding of Declarations
5255 This switch activates warnings on hiding declarations.
5256 A declaration is considered hiding
5257 if it is for a non-overloadable entity, and it declares an entity with the
5258 same name as some other entity that is directly or use-visible. The default
5259 is that such warnings are not generated.
5260 Note that @option{-gnatwa} does not affect the setting of this warning option.
5261
5262 @item -gnatwH
5263 @emph{Suppress warnings on hiding.}
5264 @cindex @option{-gnatwH} (@command{gcc})
5265 This switch suppresses warnings on hiding declarations.
5266
5267 @item -gnatw.h
5268 @emph{Activate warnings on holes/gaps in records.}
5269 @cindex @option{-gnatw.h} (@command{gcc})
5270 @cindex Record Representation (gaps)
5271 This switch activates warnings on component clauses in record
5272 representation clauses that leave holes (gaps) in the record layout.
5273 If this warning option is active, then record representation clauses
5274 should specify a contiguous layout, adding unused fill fields if needed.
5275 Note that @option{-gnatwa} does not affect the setting of this warning option.
5276
5277 @item -gnatw.H
5278 @emph{Suppress warnings on holes/gaps in records.}
5279 @cindex @option{-gnatw.H} (@command{gcc})
5280 This switch suppresses warnings on component clauses in record
5281 representation clauses that leave holes (haps) in the record layout.
5282
5283 @item -gnatwi
5284 @emph{Activate warnings on implementation units.}
5285 @cindex @option{-gnatwi} (@command{gcc})
5286 This switch activates warnings for a @code{with} of an internal GNAT
5287 implementation unit, defined as any unit from the @code{Ada},
5288 @code{Interfaces}, @code{GNAT},
5289 ^^@code{DEC},^ or @code{System}
5290 hierarchies that is not
5291 documented in either the Ada Reference Manual or the GNAT
5292 Programmer's Reference Manual. Such units are intended only
5293 for internal implementation purposes and should not be @code{with}'ed
5294 by user programs. The default is that such warnings are generated
5295 This warning can also be turned on using @option{-gnatwa}.
5296
5297 @item -gnatwI
5298 @emph{Disable warnings on implementation units.}
5299 @cindex @option{-gnatwI} (@command{gcc})
5300 This switch disables warnings for a @code{with} of an internal GNAT
5301 implementation unit.
5302
5303 @item -gnatw.i
5304 @emph{Activate warnings on overlapping actuals.}
5305 @cindex @option{-gnatw.i} (@command{gcc})
5306 This switch enables a warning on statically detectable overlapping actuals in
5307 a subprogram call, when one of the actuals is an in-out parameter, and the
5308 types of the actuals are not by-copy types. The warning is off by default,
5309 and is not included under -gnatwa.
5310
5311 @item -gnatw.I
5312 @emph{Disable warnings on overlapping actuals.}
5313 @cindex @option{-gnatw.I} (@command{gcc})
5314 This switch disables warnings on overlapping actuals in a call..
5315
5316 @item -gnatwj
5317 @emph{Activate warnings on obsolescent features (Annex J).}
5318 @cindex @option{-gnatwj} (@command{gcc})
5319 @cindex Features, obsolescent
5320 @cindex Obsolescent features
5321 If this warning option is activated, then warnings are generated for
5322 calls to subprograms marked with @code{pragma Obsolescent} and
5323 for use of features in Annex J of the Ada Reference Manual. In the
5324 case of Annex J, not all features are flagged. In particular use
5325 of the renamed packages (like @code{Text_IO}) and use of package
5326 @code{ASCII} are not flagged, since these are very common and
5327 would generate many annoying positive warnings. The default is that
5328 such warnings are not generated. This warning is also turned on by
5329 the use of @option{-gnatwa}.
5330
5331 In addition to the above cases, warnings are also generated for
5332 GNAT features that have been provided in past versions but which
5333 have been superseded (typically by features in the new Ada standard).
5334 For example, @code{pragma Ravenscar} will be flagged since its
5335 function is replaced by @code{pragma Profile(Ravenscar)}.
5336
5337 Note that this warning option functions differently from the
5338 restriction @code{No_Obsolescent_Features} in two respects.
5339 First, the restriction applies only to annex J features.
5340 Second, the restriction does flag uses of package @code{ASCII}.
5341
5342 @item -gnatwJ
5343 @emph{Suppress warnings on obsolescent features (Annex J).}
5344 @cindex @option{-gnatwJ} (@command{gcc})
5345 This switch disables warnings on use of obsolescent features.
5346
5347 @item -gnatwk
5348 @emph{Activate warnings on variables that could be constants.}
5349 @cindex @option{-gnatwk} (@command{gcc})
5350 This switch activates warnings for variables that are initialized but
5351 never modified, and then could be declared constants. The default is that
5352 such warnings are not given.
5353 This warning can also be turned on using @option{-gnatwa}.
5354
5355 @item -gnatwK
5356 @emph{Suppress warnings on variables that could be constants.}
5357 @cindex @option{-gnatwK} (@command{gcc})
5358 This switch disables warnings on variables that could be declared constants.
5359
5360 @item -gnatwl
5361 @emph{Activate warnings for elaboration pragmas.}
5362 @cindex @option{-gnatwl} (@command{gcc})
5363 @cindex Elaboration, warnings
5364 This switch activates warnings on missing
5365 @code{Elaborate_All} and @code{Elaborate} pragmas.
5366 See the section in this guide on elaboration checking for details on
5367 when such pragmas should be used. In dynamic elaboration mode, this switch
5368 generations warnings about the need to add elaboration pragmas. Note however,
5369 that if you blindly follow these warnings, and add @code{Elaborate_All}
5370 warnings wherever they are recommended, you basically end up with the
5371 equivalent of the static elaboration model, which may not be what you want for
5372 legacy code for which the static model does not work.
5373
5374 For the static model, the messages generated are labeled "info:" (for
5375 information messages). They are not warnings to add elaboration pragmas,
5376 merely informational messages showing what implicit elaboration pragmas
5377 have been added, for use in analyzing elaboration circularity problems.
5378
5379 Warnings are also generated if you
5380 are using the static mode of elaboration, and a @code{pragma Elaborate}
5381 is encountered. The default is that such warnings
5382 are not generated.
5383 This warning is not automatically turned on by the use of @option{-gnatwa}.
5384
5385 @item -gnatwL
5386 @emph{Suppress warnings for elaboration pragmas.}
5387 @cindex @option{-gnatwL} (@command{gcc})
5388 This switch suppresses warnings on missing Elaborate and Elaborate_All pragmas.
5389 See the section in this guide on elaboration checking for details on
5390 when such pragmas should be used.
5391
5392 @item -gnatwm
5393 @emph{Activate warnings on modified but unreferenced variables.}
5394 @cindex @option{-gnatwm} (@command{gcc})
5395 This switch activates warnings for variables that are assigned (using
5396 an initialization value or with one or more assignment statements) but
5397 whose value is never read. The warning is suppressed for volatile
5398 variables and also for variables that are renamings of other variables
5399 or for which an address clause is given.
5400 This warning can also be turned on using @option{-gnatwa}.
5401 The default is that these warnings are not given.
5402
5403 @item -gnatwM
5404 @emph{Disable warnings on modified but unreferenced variables.}
5405 @cindex @option{-gnatwM} (@command{gcc})
5406 This switch disables warnings for variables that are assigned or
5407 initialized, but never read.
5408
5409 @item -gnatw.m
5410 @emph{Activate warnings on suspicious modulus values.}
5411 @cindex @option{-gnatw.m} (@command{gcc})
5412 This switch activates warnings for modulus values that seem suspicious.
5413 The cases caught are where the size is the same as the modulus (e.g.
5414 a modulus of 7 with a size of 7 bits), and modulus values of 32 or 64
5415 with no size clause. The guess in both cases is that 2**x was intended
5416 rather than x. The default is that these warnings are given.
5417
5418 @item -gnatw.M
5419 @emph{Disable warnings on suspicious modulus values.}
5420 @cindex @option{-gnatw.M} (@command{gcc})
5421 This switch disables warnings for suspicious modulus values.
5422
5423 @item -gnatwn
5424 @emph{Set normal warnings mode.}
5425 @cindex @option{-gnatwn} (@command{gcc})
5426 This switch sets normal warning mode, in which enabled warnings are
5427 issued and treated as warnings rather than errors. This is the default
5428 mode. the switch @option{-gnatwn} can be used to cancel the effect of
5429 an explicit @option{-gnatws} or
5430 @option{-gnatwe}. It also cancels the effect of the
5431 implicit @option{-gnatwe} that is activated by the
5432 use of @option{-gnatg}.
5433
5434 @item -gnatwo
5435 @emph{Activate warnings on address clause overlays.}
5436 @cindex @option{-gnatwo} (@command{gcc})
5437 @cindex Address Clauses, warnings
5438 This switch activates warnings for possibly unintended initialization
5439 effects of defining address clauses that cause one variable to overlap
5440 another. The default is that such warnings are generated.
5441 This warning can also be turned on using @option{-gnatwa}.
5442
5443 @item -gnatwO
5444 @emph{Suppress warnings on address clause overlays.}
5445 @cindex @option{-gnatwO} (@command{gcc})
5446 This switch suppresses warnings on possibly unintended initialization
5447 effects of defining address clauses that cause one variable to overlap
5448 another.
5449
5450 @item -gnatw.o
5451 @emph{Activate warnings on modified but unreferenced out parameters.}
5452 @cindex @option{-gnatw.o} (@command{gcc})
5453 This switch activates warnings for variables that are modified by using
5454 them as actuals for a call to a procedure with an out mode formal, where
5455 the resulting assigned value is never read. It is applicable in the case
5456 where there is more than one out mode formal. If there is only one out
5457 mode formal, the warning is issued by default (controlled by -gnatwu).
5458 The warning is suppressed for volatile
5459 variables and also for variables that are renamings of other variables
5460 or for which an address clause is given.
5461 The default is that these warnings are not given. Note that this warning
5462 is not included in -gnatwa, it must be activated explicitly.
5463
5464 @item -gnatw.O
5465 @emph{Disable warnings on modified but unreferenced out parameters.}
5466 @cindex @option{-gnatw.O} (@command{gcc})
5467 This switch suppresses warnings for variables that are modified by using
5468 them as actuals for a call to a procedure with an out mode formal, where
5469 the resulting assigned value is never read.
5470
5471 @item -gnatwp
5472 @emph{Activate warnings on ineffective pragma Inlines.}
5473 @cindex @option{-gnatwp} (@command{gcc})
5474 @cindex Inlining, warnings
5475 This switch activates warnings for failure of front end inlining
5476 (activated by @option{-gnatN}) to inline a particular call. There are
5477 many reasons for not being able to inline a call, including most
5478 commonly that the call is too complex to inline. The default is
5479 that such warnings are not given.
5480 This warning can also be turned on using @option{-gnatwa}.
5481 Warnings on ineffective inlining by the gcc back-end can be activated
5482 separately, using the gcc switch -Winline.
5483
5484 @item -gnatwP
5485 @emph{Suppress warnings on ineffective pragma Inlines.}
5486 @cindex @option{-gnatwP} (@command{gcc})
5487 This switch suppresses warnings on ineffective pragma Inlines. If the
5488 inlining mechanism cannot inline a call, it will simply ignore the
5489 request silently.
5490
5491 @item -gnatw.p
5492 @emph{Activate warnings on parameter ordering.}
5493 @cindex @option{-gnatw.p} (@command{gcc})
5494 @cindex Parameter order, warnings
5495 This switch activates warnings for cases of suspicious parameter
5496 ordering when the list of arguments are all simple identifiers that
5497 match the names of the formals, but are in a different order. The
5498 warning is suppressed if any use of named parameter notation is used,
5499 so this is the appropriate way to suppress a false positive (and
5500 serves to emphasize that the "misordering" is deliberate). The
5501 default is
5502 that such warnings are not given.
5503 This warning can also be turned on using @option{-gnatwa}.
5504
5505 @item -gnatw.P
5506 @emph{Suppress warnings on parameter ordering.}
5507 @cindex @option{-gnatw.P} (@command{gcc})
5508 This switch suppresses warnings on cases of suspicious parameter
5509 ordering.
5510
5511 @item -gnatwq
5512 @emph{Activate warnings on questionable missing parentheses.}
5513 @cindex @option{-gnatwq} (@command{gcc})
5514 @cindex Parentheses, warnings
5515 This switch activates warnings for cases where parentheses are not used and
5516 the result is potential ambiguity from a readers point of view. For example
5517 (not a > b) when a and b are modular means ((not a) > b) and very likely the
5518 programmer intended (not (a > b)). Similarly (-x mod 5) means (-(x mod 5)) and
5519 quite likely ((-x) mod 5) was intended. In such situations it seems best to
5520 follow the rule of always parenthesizing to make the association clear, and
5521 this warning switch warns if such parentheses are not present. The default
5522 is that these warnings are given.
5523 This warning can also be turned on using @option{-gnatwa}.
5524
5525 @item -gnatwQ
5526 @emph{Suppress warnings on questionable missing parentheses.}
5527 @cindex @option{-gnatwQ} (@command{gcc})
5528 This switch suppresses warnings for cases where the association is not
5529 clear and the use of parentheses is preferred.
5530
5531 @item -gnatwr
5532 @emph{Activate warnings on redundant constructs.}
5533 @cindex @option{-gnatwr} (@command{gcc})
5534 This switch activates warnings for redundant constructs. The following
5535 is the current list of constructs regarded as redundant:
5536
5537 @itemize @bullet
5538 @item
5539 Assignment of an item to itself.
5540 @item
5541 Type conversion that converts an expression to its own type.
5542 @item
5543 Use of the attribute @code{Base} where @code{typ'Base} is the same
5544 as @code{typ}.
5545 @item
5546 Use of pragma @code{Pack} when all components are placed by a record
5547 representation clause.
5548 @item
5549 Exception handler containing only a reraise statement (raise with no
5550 operand) which has no effect.
5551 @item
5552 Use of the operator abs on an operand that is known at compile time
5553 to be non-negative
5554 @item
5555 Comparison of boolean expressions to an explicit True value.
5556 @end itemize
5557
5558 This warning can also be turned on using @option{-gnatwa}.
5559 The default is that warnings for redundant constructs are not given.
5560
5561 @item -gnatwR
5562 @emph{Suppress warnings on redundant constructs.}
5563 @cindex @option{-gnatwR} (@command{gcc})
5564 This switch suppresses warnings for redundant constructs.
5565
5566 @item -gnatw.r
5567 @emph{Activate warnings for object renaming function.}
5568 @cindex @option{-gnatw.r} (@command{gcc})
5569 This switch activates warnings for an object renaming that renames a
5570 function call, which is equivalent to a constant declaration (as
5571 opposed to renaming the function itself).  The default is that these
5572 warnings are given.  This warning can also be turned on using
5573 @option{-gnatwa}.
5574
5575 @item -gnatw.R
5576 @emph{Suppress warnings for object renaming function.}
5577 @cindex @option{-gnatwT} (@command{gcc})
5578 This switch suppresses warnings for object renaming function.
5579
5580 @item -gnatws
5581 @emph{Suppress all warnings.}
5582 @cindex @option{-gnatws} (@command{gcc})
5583 This switch completely suppresses the
5584 output of all warning messages from the GNAT front end.
5585 Note that it does not suppress warnings from the @command{gcc} back end.
5586 To suppress these back end warnings as well, use the switch @option{-w}
5587 in addition to @option{-gnatws}. Also this switch has no effect on the
5588 handling of style check messages.
5589
5590 @item -gnatw.s
5591 @emph{Activate warnings on overridden size clauses.}
5592 @cindex @option{-gnatw.s} (@command{gcc})
5593 @cindex Record Representation (component sizes)
5594 This switch activates warnings on component clauses in record
5595 representation clauses where the length given overrides that
5596 specified by an explicit size clause for the component type. A
5597 warning is similarly given in the array case if a specified
5598 component size overrides an explicit size clause for the array
5599 component type.
5600 Note that @option{-gnatwa} does not affect the setting of this warning option.
5601
5602 @item -gnatw.S
5603 @emph{Suppress warnings on overriddebn size clauses.}
5604 @cindex @option{-gnatw.S} (@command{gcc})
5605 This switch suppresses warnings on component clauses in record
5606 representation clauses that override size clauses, and similar
5607 warnings when an array component size overrides a size clause.
5608
5609 @item -gnatwt
5610 @emph{Activate warnings for tracking of deleted conditional code.}
5611 @cindex @option{-gnatwt} (@command{gcc})
5612 @cindex Deactivated code, warnings
5613 @cindex Deleted code, warnings
5614 This switch activates warnings for tracking of code in conditionals (IF and
5615 CASE statements) that is detected to be dead code which cannot be executed, and
5616 which is removed by the front end. This warning is off by default, and is not
5617 turned on by @option{-gnatwa}, it has to be turned on explicitly. This may be
5618 useful for detecting deactivated code in certified applications.
5619
5620 @item -gnatwT
5621 @emph{Suppress warnings for tracking of deleted conditional code.}
5622 @cindex @option{-gnatwT} (@command{gcc})
5623 This switch suppresses warnings for tracking of deleted conditional code.
5624
5625 @item -gnatwu
5626 @emph{Activate warnings on unused entities.}
5627 @cindex @option{-gnatwu} (@command{gcc})
5628 This switch activates warnings to be generated for entities that
5629 are declared but not referenced, and for units that are @code{with}'ed
5630 and not
5631 referenced. In the case of packages, a warning is also generated if
5632 no entities in the package are referenced. This means that if the package
5633 is referenced but the only references are in @code{use}
5634 clauses or @code{renames}
5635 declarations, a warning is still generated. A warning is also generated
5636 for a generic package that is @code{with}'ed but never instantiated.
5637 In the case where a package or subprogram body is compiled, and there
5638 is a @code{with} on the corresponding spec
5639 that is only referenced in the body,
5640 a warning is also generated, noting that the
5641 @code{with} can be moved to the body. The default is that
5642 such warnings are not generated.
5643 This switch also activates warnings on unreferenced formals
5644 (it includes the effect of @option{-gnatwf}).
5645 This warning can also be turned on using @option{-gnatwa}.
5646
5647 @item -gnatwU
5648 @emph{Suppress warnings on unused entities.}
5649 @cindex @option{-gnatwU} (@command{gcc})
5650 This switch suppresses warnings for unused entities and packages.
5651 It also turns off warnings on unreferenced formals (and thus includes
5652 the effect of @option{-gnatwF}).
5653
5654 @item -gnatw.u
5655 @emph{Activate warnings on unordered enumeration types.}
5656 @cindex @option{-gnatw.u} (@command{gcc})
5657 This switch causes enumeration types to be considered as conceptually
5658 unordered, unless an explicit pragma @code{Ordered} is given for the type.
5659 The effect is to generate warnings in clients that use explicit comparisons
5660 or subranges, since these constructs both treat objects of the type as
5661 ordered. (A @emph{client} is defined as a unit that is other than the unit in
5662 which the type is declared, or its body or subunits.) Please refer to
5663 the description of pragma @code{Ordered} in the
5664 @cite{@value{EDITION} Reference Manual} for further details.
5665
5666 @item -gnatw.U
5667 @emph{Deactivate warnings on unordered enumeration types.}
5668 @cindex @option{-gnatw.U} (@command{gcc})
5669 This switch causes all enumeration types to be considered as ordered, so
5670 that no warnings are given for comparisons or subranges for any type.
5671
5672 @item -gnatwv
5673 @emph{Activate warnings on unassigned variables.}
5674 @cindex @option{-gnatwv} (@command{gcc})
5675 @cindex Unassigned variable warnings
5676 This switch activates warnings for access to variables which
5677 may not be properly initialized. The default is that
5678 such warnings are generated.
5679 This warning can also be turned on using @option{-gnatwa}.
5680
5681 @item -gnatwV
5682 @emph{Suppress warnings on unassigned variables.}
5683 @cindex @option{-gnatwV} (@command{gcc})
5684 This switch suppresses warnings for access to variables which
5685 may not be properly initialized.
5686 For variables of a composite type, the warning can also be suppressed in
5687 Ada 2005 by using a default initialization with a box. For example, if
5688 Table is an array of records whose components are only partially uninitialized,
5689 then the following code:
5690
5691 @smallexample @c ada
5692    Tab : Table := (others => <>);
5693 @end smallexample
5694
5695 will suppress warnings on subsequent statements that access components
5696 of variable Tab.
5697
5698 @item -gnatww
5699 @emph{Activate warnings on wrong low bound assumption.}
5700 @cindex @option{-gnatww} (@command{gcc})
5701 @cindex String indexing warnings
5702 This switch activates warnings for indexing an unconstrained string parameter
5703 with a literal or S'Length. This is a case where the code is assuming that the
5704 low bound is one, which is in general not true (for example when a slice is
5705 passed). The default is that such warnings are generated.
5706 This warning can also be turned on using @option{-gnatwa}.
5707
5708 @item -gnatwW
5709 @emph{Suppress warnings on wrong low bound assumption.}
5710 @cindex @option{-gnatwW} (@command{gcc})
5711 This switch suppresses warnings for indexing an unconstrained string parameter
5712 with a literal or S'Length. Note that this warning can also be suppressed
5713 in a particular case by adding an
5714 assertion that the lower bound is 1,
5715 as shown in the following example.
5716
5717 @smallexample @c ada
5718    procedure K (S : String) is
5719       pragma Assert (S'First = 1);
5720       @dots{}
5721 @end smallexample
5722
5723 @item -gnatw.w
5724 @emph{Activate warnings on unnecessary Warnings Off pragmas}
5725 @cindex @option{-gnatw.w} (@command{gcc})
5726 @cindex Warnings Off control
5727 This switch activates warnings for use of @code{pragma Warnings (Off, entity}
5728 where either the pragma is entirely useless (because it suppresses no
5729 warnings), or it could be replaced by @code{pragma Unreferenced} or
5730 @code{pragma Unmodified}.The default is that these warnings are not given.
5731 Note that this warning is not included in -gnatwa, it must be
5732 activated explicitly.
5733
5734 @item -gnatw.W
5735 @emph{Suppress warnings on unnecessary Warnings Off pragmas}
5736 @cindex @option{-gnatw.W} (@command{gcc})
5737 This switch suppresses warnings for use of @code{pragma Warnings (Off, entity}.
5738
5739 @item -gnatwx
5740 @emph{Activate warnings on Export/Import pragmas.}
5741 @cindex @option{-gnatwx} (@command{gcc})
5742 @cindex Export/Import pragma warnings
5743 This switch activates warnings on Export/Import pragmas when
5744 the compiler detects a possible conflict between the Ada and
5745 foreign language calling sequences. For example, the use of
5746 default parameters in a convention C procedure is dubious
5747 because the C compiler cannot supply the proper default, so
5748 a warning is issued. The default is that such warnings are
5749 generated.
5750 This warning can also be turned on using @option{-gnatwa}.
5751
5752 @item -gnatwX
5753 @emph{Suppress warnings on Export/Import pragmas.}
5754 @cindex @option{-gnatwX} (@command{gcc})
5755 This switch suppresses warnings on Export/Import pragmas.
5756 The sense of this is that you are telling the compiler that
5757 you know what you are doing in writing the pragma, and it
5758 should not complain at you.
5759
5760 @item -gnatw.x
5761 @emph{Activate warnings for No_Exception_Propagation mode.}
5762 @cindex @option{-gnatwm} (@command{gcc})
5763 This switch activates warnings for exception usage when pragma Restrictions
5764 (No_Exception_Propagation) is in effect. Warnings are given for implicit or
5765 explicit exception raises which are not covered by a local handler, and for
5766 exception handlers which do not cover a local raise. The default is that these
5767 warnings are not given.
5768
5769 @item -gnatw.X
5770 @emph{Disable warnings for No_Exception_Propagation mode.}
5771 This switch disables warnings for exception usage when pragma Restrictions
5772 (No_Exception_Propagation) is in effect.
5773
5774 @item -gnatwy
5775 @emph{Activate warnings for Ada 2005 compatibility issues.}
5776 @cindex @option{-gnatwy} (@command{gcc})
5777 @cindex Ada 2005 compatibility issues warnings
5778 For the most part Ada 2005 is upwards compatible with Ada 95,
5779 but there are some exceptions (for example the fact that
5780 @code{interface} is now a reserved word in Ada 2005). This
5781 switch activates several warnings to help in identifying
5782 and correcting such incompatibilities. The default is that
5783 these warnings are generated. Note that at one point Ada 2005
5784 was called Ada 0Y, hence the choice of character.
5785 This warning can also be turned on using @option{-gnatwa}.
5786
5787 @item -gnatwY
5788 @emph{Disable warnings for Ada 2005 compatibility issues.}
5789 @cindex @option{-gnatwY} (@command{gcc})
5790 @cindex Ada 2005 compatibility issues warnings
5791 This switch suppresses several warnings intended to help in identifying
5792 incompatibilities between Ada 95 and Ada 2005.
5793
5794 @item -gnatwz
5795 @emph{Activate warnings on unchecked conversions.}
5796 @cindex @option{-gnatwz} (@command{gcc})
5797 @cindex Unchecked_Conversion warnings
5798 This switch activates warnings for unchecked conversions
5799 where the types are known at compile time to have different
5800 sizes. The default
5801 is that such warnings are generated. Warnings are also
5802 generated for subprogram pointers with different conventions,
5803 and, on VMS only, for data pointers with different conventions.
5804 This warning can also be turned on using @option{-gnatwa}.
5805
5806 @item -gnatwZ
5807 @emph{Suppress warnings on unchecked conversions.}
5808 @cindex @option{-gnatwZ} (@command{gcc})
5809 This switch suppresses warnings for unchecked conversions
5810 where the types are known at compile time to have different
5811 sizes or conventions.
5812
5813 @item ^-Wunused^WARNINGS=UNUSED^
5814 @cindex @option{-Wunused}
5815 The warnings controlled by the @option{-gnatw} switch are generated by
5816 the front end of the compiler. The @option{GCC} back end can provide
5817 additional warnings and they are controlled by the @option{-W} switch.
5818 For example, @option{^-Wunused^WARNINGS=UNUSED^} activates back end
5819 warnings for entities that are declared but not referenced.
5820
5821 @item ^-Wuninitialized^WARNINGS=UNINITIALIZED^
5822 @cindex @option{-Wuninitialized}
5823 Similarly, @option{^-Wuninitialized^WARNINGS=UNINITIALIZED^} activates
5824 the back end warning for uninitialized variables. This switch must be
5825 used in conjunction with an optimization level greater than zero.
5826
5827 @item ^-Wall^/ALL_BACK_END_WARNINGS^
5828 @cindex @option{-Wall}
5829 This switch enables all the above warnings from the @option{GCC} back end.
5830 The code generator detects a number of warning situations that are missed
5831 by the @option{GNAT} front end, and this switch can be used to activate them.
5832 The use of this switch also sets the default front end warning mode to
5833 @option{-gnatwa}, that is, most front end warnings activated as well.
5834
5835 @item ^-w^/NO_BACK_END_WARNINGS^
5836 @cindex @option{-w}
5837 Conversely, this switch suppresses warnings from the @option{GCC} back end.
5838 The use of this switch also sets the default front end warning mode to
5839 @option{-gnatws}, that is, front end warnings suppressed as well.
5840
5841 @end table
5842
5843 @noindent
5844 @ifclear vms
5845 A string of warning parameters can be used in the same parameter. For example:
5846
5847 @smallexample
5848 -gnatwaLe
5849 @end smallexample
5850
5851 @noindent
5852 will turn on all optional warnings except for elaboration pragma warnings,
5853 and also specify that warnings should be treated as errors.
5854 @end ifclear
5855 When no switch @option{^-gnatw^/WARNINGS^} is used, this is equivalent to:
5856
5857 @table @option
5858 @c !sort!
5859 @item -gnatwC
5860 @item -gnatwD
5861 @item -gnatwF
5862 @item -gnatwg
5863 @item -gnatwH
5864 @item -gnatwi
5865 @item -gnatwJ
5866 @item -gnatwK
5867 @item -gnatwL
5868 @item -gnatwM
5869 @item -gnatwn
5870 @item -gnatwo
5871 @item -gnatwP
5872 @item -gnatwR
5873 @item -gnatwU
5874 @item -gnatwv
5875 @item -gnatwz
5876 @item -gnatwx
5877
5878 @end table
5879
5880 @node Debugging and Assertion Control
5881 @subsection Debugging and Assertion Control
5882
5883 @table @option
5884 @item -gnata
5885 @cindex @option{-gnata} (@command{gcc})
5886 @findex Assert
5887 @findex Debug
5888 @cindex Assertions
5889
5890 @noindent
5891 The pragmas @code{Assert} and @code{Debug} normally have no effect and
5892 are ignored. This switch, where @samp{a} stands for assert, causes
5893 @code{Assert} and @code{Debug} pragmas to be activated.
5894
5895 The pragmas have the form:
5896
5897 @smallexample
5898 @cartouche
5899    @b{pragma} Assert (@var{Boolean-expression} @r{[},
5900                       @var{static-string-expression}@r{]})
5901    @b{pragma} Debug (@var{procedure call})
5902 @end cartouche
5903 @end smallexample
5904
5905 @noindent
5906 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
5907 If the result is @code{True}, the pragma has no effect (other than
5908 possible side effects from evaluating the expression). If the result is
5909 @code{False}, the exception @code{Assert_Failure} declared in the package
5910 @code{System.Assertions} is
5911 raised (passing @var{static-string-expression}, if present, as the
5912 message associated with the exception). If no string expression is
5913 given the default is a string giving the file name and line number
5914 of the pragma.
5915
5916 The @code{Debug} pragma causes @var{procedure} to be called. Note that
5917 @code{pragma Debug} may appear within a declaration sequence, allowing
5918 debugging procedures to be called between declarations.
5919
5920 @ifset vms
5921 @item /DEBUG@r{[}=debug-level@r{]}
5922 @itemx  /NODEBUG
5923 Specifies how much debugging information is to be included in
5924 the resulting object file where 'debug-level' is one of the following:
5925 @table @code
5926 @item   TRACEBACK
5927 Include both debugger symbol records and traceback
5928 the object file.
5929 This is the default setting.
5930 @item   ALL
5931 Include both debugger symbol records and traceback in
5932 object file.
5933 @item   NONE
5934 Excludes both debugger symbol records and traceback
5935 the object file. Same as /NODEBUG.
5936 @item   SYMBOLS
5937 Includes only debugger symbol records in the object
5938 file. Note that this doesn't include traceback information.
5939 @end table
5940 @end ifset
5941 @end table
5942
5943 @node Validity Checking
5944 @subsection Validity Checking
5945 @findex Validity Checking
5946
5947 @noindent
5948 The Ada Reference Manual defines the concept of invalid values (see
5949 RM 13.9.1). The primary source of invalid values is uninitialized
5950 variables. A scalar variable that is left uninitialized may contain
5951 an invalid value; the concept of invalid does not apply to access or
5952 composite types.
5953
5954 It is an error to read an invalid value, but the RM does not require
5955 run-time checks to detect such errors, except for some minimal
5956 checking to prevent erroneous execution (i.e. unpredictable
5957 behavior). This corresponds to the @option{-gnatVd} switch below,
5958 which is the default. For example, by default, if the expression of a
5959 case statement is invalid, it will raise Constraint_Error rather than
5960 causing a wild jump, and if an array index on the left-hand side of an
5961 assignment is invalid, it will raise Constraint_Error rather than
5962 overwriting an arbitrary memory location.
5963
5964 The @option{-gnatVa} may be used to enable additional validity checks,
5965 which are not required by the RM. These checks are often very
5966 expensive (which is why the RM does not require them). These checks
5967 are useful in tracking down uninitialized variables, but they are
5968 not usually recommended for production builds.
5969
5970 The other @option{-gnatV^@var{x}^^} switches below allow finer-grained
5971 control; you can enable whichever validity checks you desire. However,
5972 for most debugging purposes, @option{-gnatVa} is sufficient, and the
5973 default @option{-gnatVd} (i.e. standard Ada behavior) is usually
5974 sufficient for non-debugging use.
5975
5976 The @option{-gnatB} switch tells the compiler to assume that all
5977 values are valid (that is, within their declared subtype range)
5978 except in the context of a use of the Valid attribute. This means
5979 the compiler can generate more efficient code, since the range
5980 of values is better known at compile time. However, an uninitialized
5981 variable can cause wild jumps and memory corruption in this mode.
5982
5983 The @option{-gnatV^@var{x}^^} switch allows control over the validity
5984 checking mode as described below.
5985 @ifclear vms
5986 The @code{x} argument is a string of letters that
5987 indicate validity checks that are performed or not performed in addition
5988 to the default checks required by Ada as described above.
5989 @end ifclear
5990 @ifset vms
5991 The options allowed for this qualifier
5992 indicate validity checks that are performed or not performed in addition
5993 to the default checks required by Ada as described above.
5994 @end ifset
5995
5996 @table @option
5997 @c !sort!
5998 @item -gnatVa
5999 @emph{All validity checks.}
6000 @cindex @option{-gnatVa} (@command{gcc})
6001 All validity checks are turned on.
6002 @ifclear vms
6003 That is, @option{-gnatVa} is
6004 equivalent to @option{gnatVcdfimorst}.
6005 @end ifclear
6006
6007 @item -gnatVc
6008 @emph{Validity checks for copies.}
6009 @cindex @option{-gnatVc} (@command{gcc})
6010 The right hand side of assignments, and the initializing values of
6011 object declarations are validity checked.
6012
6013 @item -gnatVd
6014 @emph{Default (RM) validity checks.}
6015 @cindex @option{-gnatVd} (@command{gcc})
6016 Some validity checks are done by default following normal Ada semantics
6017 (RM 13.9.1 (9-11)).
6018 A check is done in case statements that the expression is within the range
6019 of the subtype. If it is not, Constraint_Error is raised.
6020 For assignments to array components, a check is done that the expression used
6021 as index is within the range. If it is not, Constraint_Error is raised.
6022 Both these validity checks may be turned off using switch @option{-gnatVD}.
6023 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
6024 switch @option{-gnatVd} will leave the checks turned on.
6025 Switch @option{-gnatVD} should be used only if you are sure that all such
6026 expressions have valid values. If you use this switch and invalid values
6027 are present, then the program is erroneous, and wild jumps or memory
6028 overwriting may occur.
6029
6030 @item -gnatVe
6031 @emph{Validity checks for elementary components.}
6032 @cindex @option{-gnatVe} (@command{gcc})
6033 In the absence of this switch, assignments to record or array components are
6034 not validity checked, even if validity checks for assignments generally
6035 (@option{-gnatVc}) are turned on. In Ada, assignment of composite values do not
6036 require valid data, but assignment of individual components does. So for
6037 example, there is a difference between copying the elements of an array with a
6038 slice assignment, compared to assigning element by element in a loop. This
6039 switch allows you to turn off validity checking for components, even when they
6040 are assigned component by component.
6041
6042 @item -gnatVf
6043 @emph{Validity checks for floating-point values.}
6044 @cindex @option{-gnatVf} (@command{gcc})
6045 In the absence of this switch, validity checking occurs only for discrete
6046 values. If @option{-gnatVf} is specified, then validity checking also applies
6047 for floating-point values, and NaNs and infinities are considered invalid,
6048 as well as out of range values for constrained types. Note that this means
6049 that standard IEEE infinity mode is not allowed. The exact contexts
6050 in which floating-point values are checked depends on the setting of other
6051 options. For example,
6052 @option{^-gnatVif^VALIDITY_CHECKING=(IN_PARAMS,FLOATS)^} or
6053 @option{^-gnatVfi^VALIDITY_CHECKING=(FLOATS,IN_PARAMS)^}
6054 (the order does not matter) specifies that floating-point parameters of mode
6055 @code{in} should be validity checked.
6056
6057 @item -gnatVi
6058 @emph{Validity checks for @code{in} mode parameters}
6059 @cindex @option{-gnatVi} (@command{gcc})
6060 Arguments for parameters of mode @code{in} are validity checked in function
6061 and procedure calls at the point of call.
6062
6063 @item -gnatVm
6064 @emph{Validity checks for @code{in out} mode parameters.}
6065 @cindex @option{-gnatVm} (@command{gcc})
6066 Arguments for parameters of mode @code{in out} are validity checked in
6067 procedure calls at the point of call. The @code{'m'} here stands for
6068 modify, since this concerns parameters that can be modified by the call.
6069 Note that there is no specific option to test @code{out} parameters,
6070 but any reference within the subprogram will be tested in the usual
6071 manner, and if an invalid value is copied back, any reference to it
6072 will be subject to validity checking.
6073
6074 @item -gnatVn
6075 @emph{No validity checks.}
6076 @cindex @option{-gnatVn} (@command{gcc})
6077 This switch turns off all validity checking, including the default checking
6078 for case statements and left hand side subscripts. Note that the use of
6079 the switch @option{-gnatp} suppresses all run-time checks, including
6080 validity checks, and thus implies @option{-gnatVn}. When this switch
6081 is used, it cancels any other @option{-gnatV} previously issued.
6082
6083 @item -gnatVo
6084 @emph{Validity checks for operator and attribute operands.}
6085 @cindex @option{-gnatVo} (@command{gcc})
6086 Arguments for predefined operators and attributes are validity checked.
6087 This includes all operators in package @code{Standard},
6088 the shift operators defined as intrinsic in package @code{Interfaces}
6089 and operands for attributes such as @code{Pos}. Checks are also made
6090 on individual component values for composite comparisons, and on the
6091 expressions in type conversions and qualified expressions. Checks are
6092 also made on explicit ranges using @samp{..} (e.g.@: slices, loops etc).
6093
6094 @item -gnatVp
6095 @emph{Validity checks for parameters.}
6096 @cindex @option{-gnatVp} (@command{gcc})
6097 This controls the treatment of parameters within a subprogram (as opposed
6098 to @option{-gnatVi} and @option{-gnatVm} which control validity testing
6099 of parameters on a call. If either of these call options is used, then
6100 normally an assumption is made within a subprogram that the input arguments
6101 have been validity checking at the point of call, and do not need checking
6102 again within a subprogram). If @option{-gnatVp} is set, then this assumption
6103 is not made, and parameters are not assumed to be valid, so their validity
6104 will be checked (or rechecked) within the subprogram.
6105
6106 @item -gnatVr
6107 @emph{Validity checks for function returns.}
6108 @cindex @option{-gnatVr} (@command{gcc})
6109 The expression in @code{return} statements in functions is validity
6110 checked.
6111
6112 @item -gnatVs
6113 @emph{Validity checks for subscripts.}
6114 @cindex @option{-gnatVs} (@command{gcc})
6115 All subscripts expressions are checked for validity, whether they appear
6116 on the right side or left side (in default mode only left side subscripts
6117 are validity checked).
6118
6119 @item -gnatVt
6120 @emph{Validity checks for tests.}
6121 @cindex @option{-gnatVt} (@command{gcc})
6122 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
6123 statements are checked, as well as guard expressions in entry calls.
6124
6125 @end table
6126
6127 @noindent
6128 The @option{-gnatV} switch may be followed by
6129 ^a string of letters^a list of options^
6130 to turn on a series of validity checking options.
6131 For example,
6132 @option{^-gnatVcr^/VALIDITY_CHECKING=(COPIES, RETURNS)^}
6133 specifies that in addition to the default validity checking, copies and
6134 function return expressions are to be validity checked.
6135 In order to make it easier
6136 to specify the desired combination of effects,
6137 @ifclear vms
6138 the upper case letters @code{CDFIMORST} may
6139 be used to turn off the corresponding lower case option.
6140 @end ifclear
6141 @ifset vms
6142 the prefix @code{NO} on an option turns off the corresponding validity
6143 checking:
6144 @itemize @bullet
6145 @item @code{NOCOPIES}
6146 @item @code{NODEFAULT}
6147 @item @code{NOFLOATS}
6148 @item @code{NOIN_PARAMS}
6149 @item @code{NOMOD_PARAMS}
6150 @item @code{NOOPERANDS}
6151 @item @code{NORETURNS}
6152 @item @code{NOSUBSCRIPTS}
6153 @item @code{NOTESTS}
6154 @end itemize
6155 @end ifset
6156 Thus
6157 @option{^-gnatVaM^/VALIDITY_CHECKING=(ALL, NOMOD_PARAMS)^}
6158 turns on all validity checking options except for
6159 checking of @code{@b{in out}} procedure arguments.
6160
6161 The specification of additional validity checking generates extra code (and
6162 in the case of @option{-gnatVa} the code expansion can be substantial).
6163 However, these additional checks can be very useful in detecting
6164 uninitialized variables, incorrect use of unchecked conversion, and other
6165 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
6166 is useful in conjunction with the extra validity checking, since this
6167 ensures that wherever possible uninitialized variables have invalid values.
6168
6169 See also the pragma @code{Validity_Checks} which allows modification of
6170 the validity checking mode at the program source level, and also allows for
6171 temporary disabling of validity checks.
6172
6173 @node Style Checking
6174 @subsection Style Checking
6175 @findex Style checking
6176
6177 @noindent
6178 The @option{-gnaty^x^(option,option,@dots{})^} switch
6179 @cindex @option{-gnaty} (@command{gcc})
6180 causes the compiler to
6181 enforce specified style rules. A limited set of style rules has been used
6182 in writing the GNAT sources themselves. This switch allows user programs
6183 to activate all or some of these checks. If the source program fails a
6184 specified style check, an appropriate message is given, preceded by
6185 the character sequence ``(style)''. This message does not prevent
6186 successful compilation (unless the @option{-gnatwe} switch is used).
6187
6188 Note that this is by no means intended to be a general facility for
6189 checking arbitrary coding standards. It is simply an embedding of the
6190 style rules we have chosen for the GNAT sources. If you are starting
6191 a project which does not have established style standards, you may
6192 find it useful to adopt the entire set of GNAT coding standards, or
6193 some subset of them. If you already have an established set of coding
6194 standards, then it may be that selected style checking options do
6195 indeed correspond to choices you have made, but for general checking
6196 of an existing set of coding rules, you should look to the gnatcheck
6197 tool, which is designed for that purpose.
6198
6199 @ifset vms
6200 @code{(option,option,@dots{})} is a sequence of keywords
6201 @end ifset
6202 @ifclear vms
6203 The string @var{x} is a sequence of letters or digits
6204 @end ifclear
6205 indicating the particular style
6206 checks to be performed. The following checks are defined:
6207
6208 @table @option
6209 @c !sort!
6210 @item 0-9
6211 @emph{Specify indentation level.}
6212 If a digit from 1-9 appears
6213 ^in the string after @option{-gnaty}^as an option for /STYLE_CHECKS^
6214 then proper indentation is checked, with the digit indicating the
6215 indentation level required. A value of zero turns off this style check.
6216 The general style of required indentation is as specified by
6217 the examples in the Ada Reference Manual. Full line comments must be
6218 aligned with the @code{--} starting on a column that is a multiple of
6219 the alignment level, or they may be aligned the same way as the following
6220 non-blank line (this is useful when full line comments appear in the middle
6221 of a statement.
6222
6223 @item ^a^ATTRIBUTE^
6224 @emph{Check attribute casing.}
6225 Attribute names, including the case of keywords such as @code{digits}
6226 used as attributes names, must be written in mixed case, that is, the
6227 initial letter and any letter following an underscore must be uppercase.
6228 All other letters must be lowercase.
6229
6230 @item ^A^ARRAY_INDEXES^
6231 @emph{Use of array index numbers in array attributes.}
6232 When using the array attributes First, Last, Range,
6233 or Length, the index number must be omitted for one-dimensional arrays
6234 and is required for multi-dimensional arrays.
6235
6236 @item ^b^BLANKS^
6237 @emph{Blanks not allowed at statement end.}
6238 Trailing blanks are not allowed at the end of statements. The purpose of this
6239 rule, together with h (no horizontal tabs), is to enforce a canonical format
6240 for the use of blanks to separate source tokens.
6241
6242 @item ^B^BOOLEAN_OPERATORS^
6243 @emph{Check Boolean operators.}
6244 The use of AND/OR operators is not permitted except in the cases of modular
6245 operands, array operands, and simple stand-alone boolean variables or
6246 boolean constants. In all other cases AND THEN/OR ELSE are required.
6247
6248 @item ^c^COMMENTS^
6249 @emph{Check comments.}
6250 Comments must meet the following set of rules:
6251
6252 @itemize @bullet
6253
6254 @item
6255 The ``@code{--}'' that starts the column must either start in column one,
6256 or else at least one blank must precede this sequence.
6257
6258 @item
6259 Comments that follow other tokens on a line must have at least one blank
6260 following the ``@code{--}'' at the start of the comment.
6261
6262 @item
6263 Full line comments must have at least two blanks following the
6264 ``@code{--}'' that starts the comment, with the following exceptions.
6265
6266 @item
6267 A line consisting only of the ``@code{--}'' characters, possibly preceded
6268 by blanks is permitted.
6269
6270 @item
6271 A comment starting with ``@code{--x}'' where @code{x} is a special character
6272 is permitted.
6273 This allows proper processing of the output generated by specialized tools
6274 including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK
6275 annotation
6276 language (where ``@code{--#}'' is used). For the purposes of this rule, a
6277 special character is defined as being in one of the ASCII ranges
6278 @code{16#21#@dots{}16#2F#} or @code{16#3A#@dots{}16#3F#}.
6279 Note that this usage is not permitted
6280 in GNAT implementation units (i.e., when @option{-gnatg} is used).
6281
6282 @item
6283 A line consisting entirely of minus signs, possibly preceded by blanks, is
6284 permitted. This allows the construction of box comments where lines of minus
6285 signs are used to form the top and bottom of the box.
6286
6287 @item
6288 A comment that starts and ends with ``@code{--}'' is permitted as long as at
6289 least one blank follows the initial ``@code{--}''. Together with the preceding
6290 rule, this allows the construction of box comments, as shown in the following
6291 example:
6292 @smallexample
6293 ---------------------------
6294 -- This is a box comment --
6295 -- with two text lines.  --
6296 ---------------------------
6297 @end smallexample
6298 @end itemize
6299
6300 @item ^d^DOS_LINE_ENDINGS^
6301 @emph{Check no DOS line terminators present.}
6302 All lines must be terminated by a single ASCII.LF
6303 character (in particular the DOS line terminator sequence CR/LF is not
6304 allowed).
6305
6306 @item ^e^END^
6307 @emph{Check end/exit labels.}
6308 Optional labels on @code{end} statements ending subprograms and on
6309 @code{exit} statements exiting named loops, are required to be present.
6310
6311 @item ^f^VTABS^
6312 @emph{No form feeds or vertical tabs.}
6313 Neither form feeds nor vertical tab characters are permitted
6314 in the source text.
6315
6316 @item ^g^GNAT^
6317 @emph{GNAT style mode}
6318 The set of style check switches is set to match that used by the GNAT sources.
6319 This may be useful when developing code that is eventually intended to be
6320 incorporated into GNAT. For further details, see GNAT sources.
6321
6322 @item ^h^HTABS^
6323 @emph{No horizontal tabs.}
6324 Horizontal tab characters are not permitted in the source text.
6325 Together with the b (no blanks at end of line) check, this
6326 enforces a canonical form for the use of blanks to separate
6327 source tokens.
6328
6329 @item ^i^IF_THEN^
6330 @emph{Check if-then layout.}
6331 The keyword @code{then} must appear either on the same
6332 line as corresponding @code{if}, or on a line on its own, lined
6333 up under the @code{if} with at least one non-blank line in between
6334 containing all or part of the condition to be tested.
6335
6336 @item ^I^IN_MODE^
6337 @emph{check mode IN keywords}
6338 Mode @code{in} (the default mode) is not
6339 allowed to be given explicitly. @code{in out} is fine,
6340 but not @code{in} on its own.
6341
6342 @item ^k^KEYWORD^
6343 @emph{Check keyword casing.}
6344 All keywords must be in lower case (with the exception of keywords
6345 such as @code{digits} used as attribute names to which this check
6346 does not apply).
6347
6348 @item ^l^LAYOUT^
6349 @emph{Check layout.}
6350 Layout of statement and declaration constructs must follow the
6351 recommendations in the Ada Reference Manual, as indicated by the
6352 form of the syntax rules. For example an @code{else} keyword must
6353 be lined up with the corresponding @code{if} keyword.
6354
6355 There are two respects in which the style rule enforced by this check
6356 option are more liberal than those in the Ada Reference Manual. First
6357 in the case of record declarations, it is permissible to put the
6358 @code{record} keyword on the same line as the @code{type} keyword, and
6359 then the @code{end} in @code{end record} must line up under @code{type}.
6360 This is also permitted when the type declaration is split on two lines.
6361 For example, any of the following three layouts is acceptable:
6362
6363 @smallexample @c ada
6364 @cartouche
6365 type q is record
6366    a : integer;
6367    b : integer;
6368 end record;
6369
6370 type q is
6371    record
6372       a : integer;
6373       b : integer;
6374    end record;
6375
6376 type q is
6377    record
6378       a : integer;
6379       b : integer;
6380 end record;
6381
6382 @end cartouche
6383 @end smallexample
6384
6385 @noindent
6386 Second, in the case of a block statement, a permitted alternative
6387 is to put the block label on the same line as the @code{declare} or
6388 @code{begin} keyword, and then line the @code{end} keyword up under
6389 the block label. For example both the following are permitted:
6390
6391 @smallexample @c ada
6392 @cartouche
6393 Block : declare
6394    A : Integer := 3;
6395 begin
6396    Proc (A, A);
6397 end Block;
6398
6399 Block :
6400    declare
6401       A : Integer := 3;
6402    begin
6403       Proc (A, A);
6404    end Block;
6405 @end cartouche
6406 @end smallexample
6407
6408 @noindent
6409 The same alternative format is allowed for loops. For example, both of
6410 the following are permitted:
6411
6412 @smallexample @c ada
6413 @cartouche
6414 Clear : while J < 10 loop
6415    A (J) := 0;
6416 end loop Clear;
6417
6418 Clear :
6419    while J < 10 loop
6420       A (J) := 0;
6421    end loop Clear;
6422 @end cartouche
6423 @end smallexample
6424
6425 @item ^Lnnn^MAX_NESTING=nnn^
6426 @emph{Set maximum nesting level}
6427 The maximum level of nesting of constructs (including subprograms, loops,
6428 blocks, packages, and conditionals) may not exceed the given value
6429 @option{nnn}. A value of zero disconnects this style check.
6430
6431 @item ^m^LINE_LENGTH^
6432 @emph{Check maximum line length.}
6433 The length of source lines must not exceed 79 characters, including
6434 any trailing blanks. The value of 79 allows convenient display on an
6435 80 character wide device or window, allowing for possible special
6436 treatment of 80 character lines. Note that this count is of
6437 characters in the source text. This means that a tab character counts
6438 as one character in this count but a wide character sequence counts as
6439 a single character (however many bytes are needed in the encoding).
6440
6441 @item ^Mnnn^MAX_LENGTH=nnn^
6442 @emph{Set maximum line length.}
6443 The length of lines must not exceed the
6444 given value @option{nnn}. The maximum value that can be specified is 32767.
6445
6446 @item ^n^STANDARD_CASING^
6447 @emph{Check casing of entities in Standard.}
6448 Any identifier from Standard must be cased
6449 to match the presentation in the Ada Reference Manual (for example,
6450 @code{Integer} and @code{ASCII.NUL}).
6451
6452 @item ^N^NONE^
6453 @emph{Turn off all style checks}
6454 All style check options are turned off.
6455
6456 @item ^o^ORDERED_SUBPROGRAMS^
6457 @emph{Check order of subprogram bodies.}
6458 All subprogram bodies in a given scope
6459 (e.g.@: a package body) must be in alphabetical order. The ordering
6460 rule uses normal Ada rules for comparing strings, ignoring casing
6461 of letters, except that if there is a trailing numeric suffix, then
6462 the value of this suffix is used in the ordering (e.g.@: Junk2 comes
6463 before Junk10).
6464
6465 @item ^O^OVERRIDING_INDICATORS^
6466 @emph{Check that overriding subprograms are explicitly marked as such.}
6467 The declaration of a primitive operation of a type extension that overrides
6468 an inherited operation must carry an overriding indicator.
6469
6470 @item ^p^PRAGMA^
6471 @emph{Check pragma casing.}
6472 Pragma names must be written in mixed case, that is, the
6473 initial letter and any letter following an underscore must be uppercase.
6474 All other letters must be lowercase.
6475
6476 @item ^r^REFERENCES^
6477 @emph{Check references.}
6478 All identifier references must be cased in the same way as the
6479 corresponding declaration. No specific casing style is imposed on
6480 identifiers. The only requirement is for consistency of references
6481 with declarations.
6482
6483 @item ^S^STATEMENTS_AFTER_THEN_ELSE^
6484 @emph{Check no statements after THEN/ELSE.}
6485 No statements are allowed
6486 on the same line as a THEN or ELSE keyword following the
6487 keyword in an IF statement. OR ELSE and AND THEN are not affected,
6488 and a special exception allows a pragma to appear after ELSE.
6489
6490 @item ^s^SPECS^
6491 @emph{Check separate specs.}
6492 Separate declarations (``specs'') are required for subprograms (a
6493 body is not allowed to serve as its own declaration). The only
6494 exception is that parameterless library level procedures are
6495 not required to have a separate declaration. This exception covers
6496 the most frequent form of main program procedures.
6497
6498 @item ^t^TOKEN^
6499 @emph{Check token spacing.}
6500 The following token spacing rules are enforced:
6501
6502 @itemize @bullet
6503
6504 @item
6505 The keywords @code{@b{abs}} and @code{@b{not}} must be followed by a space.
6506
6507 @item
6508 The token @code{=>} must be surrounded by spaces.
6509
6510 @item
6511 The token @code{<>} must be preceded by a space or a left parenthesis.
6512
6513 @item
6514 Binary operators other than @code{**} must be surrounded by spaces.
6515 There is no restriction on the layout of the @code{**} binary operator.
6516
6517 @item
6518 Colon must be surrounded by spaces.
6519
6520 @item
6521 Colon-equal (assignment, initialization) must be surrounded by spaces.
6522
6523 @item
6524 Comma must be the first non-blank character on the line, or be
6525 immediately preceded by a non-blank character, and must be followed
6526 by a space.
6527
6528 @item
6529 If the token preceding a left parenthesis ends with a letter or digit, then
6530 a space must separate the two tokens.
6531
6532 @item
6533 if the token following a right parenthesis starts with a letter or digit, then
6534 a space must separate the two tokens.
6535
6536 @item
6537 A right parenthesis must either be the first non-blank character on
6538 a line, or it must be preceded by a non-blank character.
6539
6540 @item
6541 A semicolon must not be preceded by a space, and must not be followed by
6542 a non-blank character.
6543
6544 @item
6545 A unary plus or minus may not be followed by a space.
6546
6547 @item
6548 A vertical bar must be surrounded by spaces.
6549 @end itemize
6550
6551 @item ^u^UNNECESSARY_BLANK_LINES^
6552 @emph{Check unnecessary blank lines.}
6553 Unnecessary blank lines are not allowed. A blank line is considered
6554 unnecessary if it appears at the end of the file, or if more than
6555 one blank line occurs in sequence.
6556
6557 @item ^x^XTRA_PARENS^
6558 @emph{Check extra parentheses.}
6559 Unnecessary extra level of parentheses (C-style) are not allowed
6560 around conditions in @code{if} statements, @code{while} statements and
6561 @code{exit} statements.
6562
6563 @item ^y^ALL_BUILTIN^
6564 @emph{Set all standard style check options}
6565 This is equivalent to @code{gnaty3aAbcefhiklmnprst}, that is all checking
6566 options enabled with the exception of @option{-gnatyo}, @option{-gnatyI},
6567 @option{-gnatyS}, @option{-gnatyLnnn},
6568 @option{-gnatyd}, @option{-gnatyu}, and @option{-gnatyx}.
6569
6570 @ifclear vms
6571 @item -
6572 @emph{Remove style check options}
6573 This causes any subsequent options in the string to act as canceling the
6574 corresponding style check option. To cancel maximum nesting level control,
6575 use @option{L} parameter witout any integer value after that, because any
6576 digit following @option{-} in the parameter string of the @option{-gnaty}
6577 option will be threated as canceling indentation check. The same is true
6578 for @option{M} parameter. @option{y} and @option{N} parameters are not
6579 allowed after @option{-}.
6580
6581 @item +
6582 This causes any subsequent options in the string to enable the corresponding
6583 style check option. That is, it cancels the effect of a previous ^-^REMOVE^,
6584 if any.
6585 @end ifclear
6586
6587 @ifset vms
6588 @item NOxxx
6589 @emph{Removing style check options}
6590 If the name of a style check is preceded by @option{NO} then the corresponding
6591 style check is turned off. For example @option{NOCOMMENTS} turns off style
6592 checking for comments.
6593 @end ifset
6594 @end table
6595
6596 @noindent
6597 In the above rules, appearing in column one is always permitted, that is,
6598 counts as meeting either a requirement for a required preceding space,
6599 or as meeting a requirement for no preceding space.
6600
6601 Appearing at the end of a line is also always permitted, that is, counts
6602 as meeting either a requirement for a following space, or as meeting
6603 a requirement for no following space.
6604
6605 @noindent
6606 If any of these style rules is violated, a message is generated giving
6607 details on the violation. The initial characters of such messages are
6608 always ``@code{(style)}''. Note that these messages are treated as warning
6609 messages, so they normally do not prevent the generation of an object
6610 file. The @option{-gnatwe} switch can be used to treat warning messages,
6611 including style messages, as fatal errors.
6612
6613 The switch
6614 @ifclear vms
6615 @option{-gnaty} on its own (that is not
6616 followed by any letters or digits), then the effect is equivalent
6617 to the use of @option{-gnatyy}, as described above, that is all
6618 built-in standard style check options are enabled.
6619
6620 @end ifclear
6621 @ifset vms
6622 /STYLE_CHECKS=ALL_BUILTIN enables all checking options with
6623 the exception of ORDERED_SUBPROGRAMS, UNNECESSARY_BLANK_LINES,
6624 XTRA_PARENS, and DOS_LINE_ENDINGS. In addition
6625 @end ifset
6626
6627 The switch
6628 @ifclear vms
6629 @option{-gnatyN}
6630 @end ifclear
6631 @ifset vms
6632 /STYLE_CHECKS=NONE
6633 @end ifset
6634 clears any previously set style checks.
6635
6636 @node Run-Time Checks
6637 @subsection Run-Time Checks
6638 @cindex Division by zero
6639 @cindex Access before elaboration
6640 @cindex Checks, division by zero
6641 @cindex Checks, access before elaboration
6642 @cindex Checks, stack overflow checking
6643
6644 @noindent
6645 By default, the following checks are suppressed: integer overflow
6646 checks, stack overflow checks, and checks for access before
6647 elaboration on subprogram calls. All other checks, including range
6648 checks and array bounds checks, are turned on by default. The
6649 following @command{gcc} switches refine this default behavior.
6650
6651 @table @option
6652 @c !sort!
6653 @item -gnatp
6654 @cindex @option{-gnatp} (@command{gcc})
6655 @cindex Suppressing checks
6656 @cindex Checks, suppressing
6657 @findex Suppress
6658 This switch causes the unit to be compiled
6659 as though @code{pragma Suppress (All_checks)}
6660 had been present in the source. Validity checks are also eliminated (in
6661 other words @option{-gnatp} also implies @option{-gnatVn}.
6662 Use this switch to improve the performance
6663 of the code at the expense of safety in the presence of invalid data or
6664 program bugs.
6665
6666 Note that when checks are suppressed, the compiler is allowed, but not
6667 required, to omit the checking code. If the run-time cost of the
6668 checking code is zero or near-zero, the compiler will generate it even
6669 if checks are suppressed. In particular, if the compiler can prove
6670 that a certain check will necessarily fail, it will generate code to
6671 do an unconditional ``raise'', even if checks are suppressed. The
6672 compiler warns in this case. Another case in which checks may not be
6673 eliminated is when they are embedded in certain run time routines such
6674 as math library routines.
6675
6676 Of course, run-time checks are omitted whenever the compiler can prove
6677 that they will not fail, whether or not checks are suppressed.
6678
6679 Note that if you suppress a check that would have failed, program
6680 execution is erroneous, which means the behavior is totally
6681 unpredictable. The program might crash, or print wrong answers, or
6682 do anything else. It might even do exactly what you wanted it to do
6683 (and then it might start failing mysteriously next week or next
6684 year). The compiler will generate code based on the assumption that
6685 the condition being checked is true, which can result in disaster if
6686 that assumption is wrong.
6687
6688 The @option{-gnatp} switch has no effect if a subsequent
6689 @option{-gnat-p} switch appears.
6690
6691 @item -gnat-p
6692 @cindex @option{-gnat-p} (@command{gcc})
6693 @cindex Suppressing checks
6694 @cindex Checks, suppressing
6695 @findex Suppress
6696 This switch cancels the effect of a previous @option{gnatp} switch.
6697
6698 @item -gnato
6699 @cindex @option{-gnato} (@command{gcc})
6700 @cindex Overflow checks
6701 @cindex Check, overflow
6702 Enables overflow checking for integer operations.
6703 This causes GNAT to generate slower and larger executable
6704 programs by adding code to check for overflow (resulting in raising
6705 @code{Constraint_Error} as required by standard Ada
6706 semantics). These overflow checks correspond to situations in which
6707 the true value of the result of an operation may be outside the base
6708 range of the result type. The following example shows the distinction:
6709
6710 @smallexample @c ada
6711 X1 : Integer := "Integer'Last";
6712 X2 : Integer range 1 .. 5 := "5";
6713 X3 : Integer := "Integer'Last";
6714 X4 : Integer range 1 .. 5 := "5";
6715 F  : Float := "2.0E+20";
6716 @dots{}
6717 X1 := X1 + 1;
6718 X2 := X2 + 1;
6719 X3 := Integer (F);
6720 X4 := Integer (F);
6721 @end smallexample
6722
6723 @noindent
6724 Note that if explicit values are assigned at compile time, the
6725 compiler may be able to detect overflow at compile time, in which case
6726 no actual run-time checking code is required, and Constraint_Error
6727 will be raised unconditionally, with or without
6728 @option{-gnato}. That's why the assigned values in the above fragment
6729 are in quotes, the meaning is "assign a value not known to the
6730 compiler that happens to be equal to ...". The remaining discussion
6731 assumes that the compiler cannot detect the values at compile time.
6732
6733 Here the first addition results in a value that is outside the base range
6734 of Integer, and hence requires an overflow check for detection of the
6735 constraint error. Thus the first assignment to @code{X1} raises a
6736 @code{Constraint_Error} exception only if @option{-gnato} is set.
6737
6738 The second increment operation results in a violation of the explicit
6739 range constraint; such range checks are performed by default, and are
6740 unaffected by @option{-gnato}.
6741
6742 The two conversions of @code{F} both result in values that are outside
6743 the base range of type @code{Integer} and thus will raise
6744 @code{Constraint_Error} exceptions only if @option{-gnato} is used.
6745 The fact that the result of the second conversion is assigned to
6746 variable @code{X4} with a restricted range is irrelevant, since the problem
6747 is in the conversion, not the assignment.
6748
6749 Basically the rule is that in the default mode (@option{-gnato} not
6750 used), the generated code assures that all integer variables stay
6751 within their declared ranges, or within the base range if there is
6752 no declared range. This prevents any serious problems like indexes
6753 out of range for array operations.
6754
6755 What is not checked in default mode is an overflow that results in
6756 an in-range, but incorrect value. In the above example, the assignments
6757 to @code{X1}, @code{X2}, @code{X3} all give results that are within the
6758 range of the target variable, but the result is wrong in the sense that
6759 it is too large to be represented correctly. Typically the assignment
6760 to @code{X1} will result in wrap around to the largest negative number.
6761 The conversions of @code{F} will result in some @code{Integer} value
6762 and if that integer value is out of the @code{X4} range then the
6763 subsequent assignment would generate an exception.
6764
6765 @findex Machine_Overflows
6766 Note that the @option{-gnato} switch does not affect the code generated
6767 for any floating-point operations; it applies only to integer
6768 semantics).
6769 For floating-point, GNAT has the @code{Machine_Overflows}
6770 attribute set to @code{False} and the normal mode of operation is to
6771 generate IEEE NaN and infinite values on overflow or invalid operations
6772 (such as dividing 0.0 by 0.0).
6773
6774 The reason that we distinguish overflow checking from other kinds of
6775 range constraint checking is that a failure of an overflow check, unlike
6776 for example the failure of a range check, can result in an incorrect
6777 value, but cannot cause random memory destruction (like an out of range
6778 subscript), or a wild jump (from an out of range case value). Overflow
6779 checking is also quite expensive in time and space, since in general it
6780 requires the use of double length arithmetic.
6781
6782 Note again that @option{-gnato} is off by default, so overflow checking is
6783 not performed in default mode. This means that out of the box, with the
6784 default settings, GNAT does not do all the checks expected from the
6785 language description in the Ada Reference Manual. If you want all constraint
6786 checks to be performed, as described in this Manual, then you must
6787 explicitly use the -gnato switch either on the @command{gnatmake} or
6788 @command{gcc} command.
6789
6790 @item -gnatE
6791 @cindex @option{-gnatE} (@command{gcc})
6792 @cindex Elaboration checks
6793 @cindex Check, elaboration
6794 Enables dynamic checks for access-before-elaboration
6795 on subprogram calls and generic instantiations.
6796 Note that @option{-gnatE} is not necessary for safety, because in the
6797 default mode, GNAT ensures statically that the checks would not fail.
6798 For full details of the effect and use of this switch,
6799 @xref{Compiling Using gcc}.
6800
6801 @item -fstack-check
6802 @cindex @option{-fstack-check} (@command{gcc})
6803 @cindex Stack Overflow Checking
6804 @cindex Checks, stack overflow checking
6805 Activates stack overflow checking. For full details of the effect and use of
6806 this switch see @ref{Stack Overflow Checking}.
6807 @end table
6808
6809 @findex Unsuppress
6810 @noindent
6811 The setting of these switches only controls the default setting of the
6812 checks. You may modify them using either @code{Suppress} (to remove
6813 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
6814 the program source.
6815
6816 @node Using gcc for Syntax Checking
6817 @subsection Using @command{gcc} for Syntax Checking
6818 @table @option
6819 @item -gnats
6820 @cindex @option{-gnats} (@command{gcc})
6821 @ifclear vms
6822
6823 @noindent
6824 The @code{s} stands for ``syntax''.
6825 @end ifclear
6826
6827 Run GNAT in syntax checking only mode. For
6828 example, the command
6829
6830 @smallexample
6831 $ gcc -c -gnats x.adb
6832 @end smallexample
6833
6834 @noindent
6835 compiles file @file{x.adb} in syntax-check-only mode. You can check a
6836 series of files in a single command
6837 @ifclear vms
6838 , and can use wild cards to specify such a group of files.
6839 Note that you must specify the @option{-c} (compile
6840 only) flag in addition to the @option{-gnats} flag.
6841 @end ifclear
6842 .
6843 You may use other switches in conjunction with @option{-gnats}. In
6844 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
6845 format of any generated error messages.
6846
6847 When the source file is empty or contains only empty lines and/or comments,
6848 the output is a warning:
6849
6850 @smallexample
6851 $ gcc -c -gnats -x ada toto.txt
6852 toto.txt:1:01: warning: empty file, contains no compilation units
6853 $
6854 @end smallexample
6855
6856 Otherwise, the output is simply the error messages, if any. No object file or
6857 ALI file is generated by a syntax-only compilation. Also, no units other
6858 than the one specified are accessed. For example, if a unit @code{X}
6859 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
6860 check only mode does not access the source file containing unit
6861 @code{Y}.
6862
6863 @cindex Multiple units, syntax checking
6864 Normally, GNAT allows only a single unit in a source file. However, this
6865 restriction does not apply in syntax-check-only mode, and it is possible
6866 to check a file containing multiple compilation units concatenated
6867 together. This is primarily used by the @code{gnatchop} utility
6868 (@pxref{Renaming Files Using gnatchop}).
6869 @end table
6870
6871 @node Using gcc for Semantic Checking
6872 @subsection Using @command{gcc} for Semantic Checking
6873 @table @option
6874 @item -gnatc
6875 @cindex @option{-gnatc} (@command{gcc})
6876
6877 @ifclear vms
6878 @noindent
6879 The @code{c} stands for ``check''.
6880 @end ifclear
6881 Causes the compiler to operate in semantic check mode,
6882 with full checking for all illegalities specified in the
6883 Ada Reference Manual, but without generation of any object code
6884 (no object file is generated).
6885
6886 Because dependent files must be accessed, you must follow the GNAT
6887 semantic restrictions on file structuring to operate in this mode:
6888
6889 @itemize @bullet
6890 @item
6891 The needed source files must be accessible
6892 (@pxref{Search Paths and the Run-Time Library (RTL)}).
6893
6894 @item
6895 Each file must contain only one compilation unit.
6896
6897 @item
6898 The file name and unit name must match (@pxref{File Naming Rules}).
6899 @end itemize
6900
6901 The output consists of error messages as appropriate. No object file is
6902 generated. An @file{ALI} file is generated for use in the context of
6903 cross-reference tools, but this file is marked as not being suitable
6904 for binding (since no object file is generated).
6905 The checking corresponds exactly to the notion of
6906 legality in the Ada Reference Manual.
6907
6908 Any unit can be compiled in semantics-checking-only mode, including
6909 units that would not normally be compiled (subunits,
6910 and specifications where a separate body is present).
6911 @end table
6912
6913 @node Compiling Different Versions of Ada
6914 @subsection Compiling Different Versions of Ada
6915
6916 @noindent
6917 The switches described in this section allow you to explicitly specify
6918 the version of the Ada language that your programs are written in.
6919 By default @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION},
6920 but you can also specify @value{NONDEFAULTLANGUAGEVERSION} or
6921 indicate Ada 83 compatibility mode.
6922
6923 @table @option
6924 @cindex Compatibility with Ada 83
6925
6926 @item -gnat83 (Ada 83 Compatibility Mode)
6927 @cindex @option{-gnat83} (@command{gcc})
6928 @cindex ACVC, Ada 83 tests
6929 @cindex Ada 83 mode
6930
6931 @noindent
6932 Although GNAT is primarily an Ada 95 / Ada 2005 compiler, this switch
6933 specifies that the program is to be compiled in Ada 83 mode. With
6934 @option{-gnat83}, GNAT rejects most post-Ada 83 extensions and applies Ada 83
6935 semantics where this can be done easily.
6936 It is not possible to guarantee this switch does a perfect
6937 job; some subtle tests, such as are
6938 found in earlier ACVC tests (and that have been removed from the ACATS suite
6939 for Ada 95), might not compile correctly.
6940 Nevertheless, this switch may be useful in some circumstances, for example
6941 where, due to contractual reasons, existing code needs to be maintained
6942 using only Ada 83 features.
6943
6944 With few exceptions (most notably the need to use @code{<>} on
6945 @cindex Generic formal parameters
6946 unconstrained generic formal parameters, the use of the new Ada 95 / Ada 2005
6947 reserved words, and the use of packages
6948 with optional bodies), it is not necessary to specify the
6949 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
6950 exceptions, Ada 95 and Ada 2005 are upwardly compatible with Ada 83. Thus
6951 a correct Ada 83 program is usually also a correct program
6952 in these later versions of the language standard.
6953 For further information, please refer to @ref{Compatibility and Porting Guide}.
6954
6955 @item -gnat95 (Ada 95 mode)
6956 @cindex @option{-gnat95} (@command{gcc})
6957 @cindex Ada 95 mode
6958
6959 @noindent
6960 This switch directs the compiler to implement the Ada 95 version of the
6961 language.
6962 Since Ada 95 is almost completely upwards
6963 compatible with Ada 83, Ada 83 programs may generally be compiled using
6964 this switch (see the description of the @option{-gnat83} switch for further
6965 information about Ada 83 mode).
6966 If an Ada 2005 program is compiled in Ada 95 mode,
6967 uses of the new Ada 2005 features will cause error
6968 messages or warnings.
6969
6970 This switch also can be used to cancel the effect of a previous
6971 @option{-gnat83}, @option{-gnat05/2005}, or @option{-gnat12/2012}
6972 switch earlier in the command line.
6973
6974 @item -gnat05 or -gnat2005 (Ada 2005 mode)
6975 @cindex @option{-gnat05} (@command{gcc})
6976 @cindex @option{-gnat2005} (@command{gcc})
6977 @cindex Ada 2005 mode
6978
6979 @noindent
6980 This switch directs the compiler to implement the Ada 2005 version of the
6981 language, as documented in the official Ada standards document.
6982 Since Ada 2005 is almost completely upwards
6983 compatible with Ada 95 (and thus also with Ada 83), Ada 83 and Ada 95 programs
6984 may generally be compiled using this switch (see the description of the
6985 @option{-gnat83} and @option{-gnat95} switches for further
6986 information).
6987
6988 @ifset PROEDITION
6989 Note that even though Ada 2005 is the current official version of the
6990 language, GNAT still compiles in Ada 95 mode by default, so if you are
6991 using Ada 2005 features in your program, you must use this switch (or
6992 the equivalent Ada_05 or Ada_2005 configuration pragmas).
6993 @end ifset
6994
6995 @item -gnat12 or -gnat2012 (Ada 2012 mode)
6996 @cindex @option{-gnat12} (@command{gcc})
6997 @cindex @option{-gnat2012} (@command{gcc})
6998 @cindex Ada 2012 mode
6999
7000 @noindent
7001 This switch directs the compiler to implement the Ada 2012 version of the
7002 language.
7003 Since Ada 2012 is almost completely upwards
7004 compatible with Ada 2005 (and thus also with Ada 83, and Ada 95),
7005 Ada 83 and Ada 95 programs
7006 may generally be compiled using this switch (see the description of the
7007 @option{-gnat83}, @option{-gnat95}, and @option{-gnat05/2005} switches
7008 for further information).
7009
7010 For information about the approved ``Ada Issues'' that have been incorporated
7011 into Ada 2012, see @url{http://www.ada-auth.org/cgi-bin/cvsweb.cgi/AIs}.
7012 Included with GNAT releases is a file @file{features-ada12} that describes
7013 the set of implemented Ada 2012 features.
7014
7015 @item -gnatX (Enable GNAT Extensions)
7016 @cindex @option{-gnatX} (@command{gcc})
7017 @cindex Ada language extensions
7018 @cindex GNAT extensions
7019
7020 @noindent
7021 This switch directs the compiler to implement the latest version of the
7022 language (currently Ada 2012) and also to enable certain GNAT implementation
7023 extensions that are not part of any Ada standard. For a full list of these
7024 extensions, see the GNAT reference manual.
7025
7026 @end table
7027
7028 @node Character Set Control
7029 @subsection Character Set Control
7030 @table @option
7031 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
7032 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
7033
7034 @noindent
7035 Normally GNAT recognizes the Latin-1 character set in source program
7036 identifiers, as described in the Ada Reference Manual.
7037 This switch causes
7038 GNAT to recognize alternate character sets in identifiers. @var{c} is a
7039 single character ^^or word^ indicating the character set, as follows:
7040
7041 @table @code
7042 @item 1
7043 ISO 8859-1 (Latin-1) identifiers
7044
7045 @item 2
7046 ISO 8859-2 (Latin-2) letters allowed in identifiers
7047
7048 @item 3
7049 ISO 8859-3 (Latin-3) letters allowed in identifiers
7050
7051 @item 4
7052 ISO 8859-4 (Latin-4) letters allowed in identifiers
7053
7054 @item 5
7055 ISO 8859-5 (Cyrillic) letters allowed in identifiers
7056
7057 @item 9
7058 ISO 8859-15 (Latin-9) letters allowed in identifiers
7059
7060 @item ^p^PC^
7061 IBM PC letters (code page 437) allowed in identifiers
7062
7063 @item ^8^PC850^
7064 IBM PC letters (code page 850) allowed in identifiers
7065
7066 @item ^f^FULL_UPPER^
7067 Full upper-half codes allowed in identifiers
7068
7069 @item ^n^NO_UPPER^
7070 No upper-half codes allowed in identifiers
7071
7072 @item ^w^WIDE^
7073 Wide-character codes (that is, codes greater than 255)
7074 allowed in identifiers
7075 @end table
7076
7077 @xref{Foreign Language Representation}, for full details on the
7078 implementation of these character sets.
7079
7080 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
7081 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
7082 Specify the method of encoding for wide characters.
7083 @var{e} is one of the following:
7084
7085 @table @code
7086
7087 @item ^h^HEX^
7088 Hex encoding (brackets coding also recognized)
7089
7090 @item ^u^UPPER^
7091 Upper half encoding (brackets encoding also recognized)
7092
7093 @item ^s^SHIFT_JIS^
7094 Shift/JIS encoding (brackets encoding also recognized)
7095
7096 @item ^e^EUC^
7097 EUC encoding (brackets encoding also recognized)
7098
7099 @item ^8^UTF8^
7100 UTF-8 encoding (brackets encoding also recognized)
7101
7102 @item ^b^BRACKETS^
7103 Brackets encoding only (default value)
7104 @end table
7105 For full details on these encoding
7106 methods see @ref{Wide Character Encodings}.
7107 Note that brackets coding is always accepted, even if one of the other
7108 options is specified, so for example @option{-gnatW8} specifies that both
7109 brackets and UTF-8 encodings will be recognized. The units that are
7110 with'ed directly or indirectly will be scanned using the specified
7111 representation scheme, and so if one of the non-brackets scheme is
7112 used, it must be used consistently throughout the program. However,
7113 since brackets encoding is always recognized, it may be conveniently
7114 used in standard libraries, allowing these libraries to be used with
7115 any of the available coding schemes.
7116 scheme.
7117
7118 If no @option{-gnatW?} parameter is present, then the default
7119 representation is normally Brackets encoding only. However, if the
7120 first three characters of the file are 16#EF# 16#BB# 16#BF# (the standard
7121 byte order mark or BOM for UTF-8), then these three characters are
7122 skipped and the default representation for the file is set to UTF-8.
7123
7124 Note that the wide character representation that is specified (explicitly
7125 or by default) for the main program also acts as the default encoding used
7126 for Wide_Text_IO files if not specifically overridden by a WCEM form
7127 parameter.
7128
7129 @end table
7130 @node File Naming Control
7131 @subsection File Naming Control
7132
7133 @table @option
7134 @item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n}
7135 @cindex @option{-gnatk} (@command{gcc})
7136 Activates file name ``krunching''. @var{n}, a decimal integer in the range
7137 1-999, indicates the maximum allowable length of a file name (not
7138 including the @file{.ads} or @file{.adb} extension). The default is not
7139 to enable file name krunching.
7140
7141 For the source file naming rules, @xref{File Naming Rules}.
7142 @end table
7143
7144 @node Subprogram Inlining Control
7145 @subsection Subprogram Inlining Control
7146
7147 @table @option
7148 @c !sort!
7149 @item -gnatn
7150 @cindex @option{-gnatn} (@command{gcc})
7151 @ifclear vms
7152 The @code{n} here is intended to suggest the first syllable of the
7153 word ``inline''.
7154 @end ifclear
7155 GNAT recognizes and processes @code{Inline} pragmas. However, for the
7156 inlining to actually occur, optimization must be enabled. To enable
7157 inlining of subprograms specified by pragma @code{Inline},
7158 you must also specify this switch.
7159 In the absence of this switch, GNAT does not attempt
7160 inlining and does not need to access the bodies of
7161 subprograms for which @code{pragma Inline} is specified if they are not
7162 in the current unit.
7163
7164 If you specify this switch the compiler will access these bodies,
7165 creating an extra source dependency for the resulting object file, and
7166 where possible, the call will be inlined.
7167 For further details on when inlining is possible
7168 see @ref{Inlining of Subprograms}.
7169
7170 @item -gnatN
7171 @cindex @option{-gnatN} (@command{gcc})
7172 This switch activates front-end inlining which also
7173 generates additional dependencies.
7174
7175 When using a gcc-based back end (in practice this means using any version
7176 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
7177 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
7178 Historically front end inlining was more extensive than the gcc back end
7179 inlining, but that is no longer the case.
7180 @end table
7181
7182 @node Auxiliary Output Control
7183 @subsection Auxiliary Output Control
7184
7185 @table @option
7186 @item -gnatt
7187 @cindex @option{-gnatt} (@command{gcc})
7188 @cindex Writing internal trees
7189 @cindex Internal trees, writing to file
7190 Causes GNAT to write the internal tree for a unit to a file (with the
7191 extension @file{.adt}.
7192 This not normally required, but is used by separate analysis tools.
7193 Typically
7194 these tools do the necessary compilations automatically, so you should
7195 not have to specify this switch in normal operation.
7196 Note that the combination of switches @option{-gnatct}
7197 generates a tree in the form required by ASIS applications.
7198
7199 @item -gnatu
7200 @cindex @option{-gnatu} (@command{gcc})
7201 Print a list of units required by this compilation on @file{stdout}.
7202 The listing includes all units on which the unit being compiled depends
7203 either directly or indirectly.
7204
7205 @ifclear vms
7206 @item -pass-exit-codes
7207 @cindex @option{-pass-exit-codes} (@command{gcc})
7208 If this switch is not used, the exit code returned by @command{gcc} when
7209 compiling multiple files indicates whether all source files have
7210 been successfully used to generate object files or not.
7211
7212 When @option{-pass-exit-codes} is used, @command{gcc} exits with an extended
7213 exit status and allows an integrated development environment to better
7214 react to a compilation failure. Those exit status are:
7215
7216 @table @asis
7217 @item 5
7218 There was an error in at least one source file.
7219 @item 3
7220 At least one source file did not generate an object file.
7221 @item 2
7222 The compiler died unexpectedly (internal error for example).
7223 @item 0
7224 An object file has been generated for every source file.
7225 @end table
7226 @end ifclear
7227 @end table
7228
7229 @node Debugging Control
7230 @subsection Debugging Control
7231
7232 @table @option
7233 @c !sort!
7234 @cindex Debugging options
7235 @ifclear vms
7236 @item -gnatd@var{x}
7237 @cindex @option{-gnatd} (@command{gcc})
7238 Activate internal debugging switches. @var{x} is a letter or digit, or
7239 string of letters or digits, which specifies the type of debugging
7240 outputs desired. Normally these are used only for internal development
7241 or system debugging purposes. You can find full documentation for these
7242 switches in the body of the @code{Debug} unit in the compiler source
7243 file @file{debug.adb}.
7244 @end ifclear
7245
7246 @item -gnatG[=nn]
7247 @cindex @option{-gnatG} (@command{gcc})
7248 This switch causes the compiler to generate auxiliary output containing
7249 a pseudo-source listing of the generated expanded code. Like most Ada
7250 compilers, GNAT works by first transforming the high level Ada code into
7251 lower level constructs. For example, tasking operations are transformed
7252 into calls to the tasking run-time routines. A unique capability of GNAT
7253 is to list this expanded code in a form very close to normal Ada source.
7254 This is very useful in understanding the implications of various Ada
7255 usage on the efficiency of the generated code. There are many cases in
7256 Ada (e.g.@: the use of controlled types), where simple Ada statements can
7257 generate a lot of run-time code. By using @option{-gnatG} you can identify
7258 these cases, and consider whether it may be desirable to modify the coding
7259 approach to improve efficiency.
7260
7261 The optional parameter @code{nn} if present after -gnatG specifies an
7262 alternative maximum line length that overrides the normal default of 72.
7263 This value is in the range 40-999999, values less than 40 being silently
7264 reset to 40. The equal sign is optional.
7265
7266 The format of the output is very similar to standard Ada source, and is
7267 easily understood by an Ada programmer. The following special syntactic
7268 additions correspond to low level features used in the generated code that
7269 do not have any exact analogies in pure Ada source form. The following
7270 is a partial list of these special constructions. See the spec
7271 of package @code{Sprint} in file @file{sprint.ads} for a full list.
7272
7273 If the switch @option{-gnatL} is used in conjunction with
7274 @cindex @option{-gnatL} (@command{gcc})
7275 @option{-gnatG}, then the original source lines are interspersed
7276 in the expanded source (as comment lines with the original line number).
7277
7278 @table @code
7279 @item new @var{xxx} @r{[}storage_pool = @var{yyy}@r{]}
7280 Shows the storage pool being used for an allocator.
7281
7282 @item at end @var{procedure-name};
7283 Shows the finalization (cleanup) procedure for a scope.
7284
7285 @item (if @var{expr} then @var{expr} else @var{expr})
7286 Conditional expression equivalent to the @code{x?y:z} construction in C.
7287
7288 @item @var{target}^^^(@var{source})
7289 A conversion with floating-point truncation instead of rounding.
7290
7291 @item @var{target}?(@var{source})
7292 A conversion that bypasses normal Ada semantic checking. In particular
7293 enumeration types and fixed-point types are treated simply as integers.
7294
7295 @item @var{target}?^^^(@var{source})
7296 Combines the above two cases.
7297
7298 @item @var{x} #/ @var{y}
7299 @itemx @var{x} #mod @var{y}
7300 @itemx @var{x} #* @var{y}
7301 @itemx @var{x} #rem @var{y}
7302 A division or multiplication of fixed-point values which are treated as
7303 integers without any kind of scaling.
7304
7305 @item free @var{expr} @r{[}storage_pool = @var{xxx}@r{]}
7306 Shows the storage pool associated with a @code{free} statement.
7307
7308 @item [subtype or type declaration]
7309 Used to list an equivalent declaration for an internally generated
7310 type that is referenced elsewhere in the listing.
7311
7312 @c @item freeze @var{type-name} @ovar{actions}
7313 @c Expanding @ovar macro inline (explanation in macro def comments)
7314 @item freeze @var{type-name} @r{[}@var{actions}@r{]}
7315 Shows the point at which @var{type-name} is frozen, with possible
7316 associated actions to be performed at the freeze point.
7317
7318 @item reference @var{itype}
7319 Reference (and hence definition) to internal type @var{itype}.
7320
7321 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
7322 Intrinsic function call.
7323
7324 @item @var{label-name} : label
7325 Declaration of label @var{labelname}.
7326
7327 @item #$ @var{subprogram-name}
7328 An implicit call to a run-time support routine
7329 (to meet the requirement of H.3.1(9) in a
7330 convenient manner).
7331
7332 @item @var{expr} && @var{expr} && @var{expr} @dots{} && @var{expr}
7333 A multiple concatenation (same effect as @var{expr} & @var{expr} &
7334 @var{expr}, but handled more efficiently).
7335
7336 @item [constraint_error]
7337 Raise the @code{Constraint_Error} exception.
7338
7339 @item @var{expression}'reference
7340 A pointer to the result of evaluating @var{expression}.
7341
7342 @item @var{target-type}!(@var{source-expression})
7343 An unchecked conversion of @var{source-expression} to @var{target-type}.
7344
7345 @item [@var{numerator}/@var{denominator}]
7346 Used to represent internal real literals (that) have no exact
7347 representation in base 2-16 (for example, the result of compile time
7348 evaluation of the expression 1.0/27.0).
7349 @end table
7350
7351 @item -gnatD[=nn]
7352 @cindex @option{-gnatD} (@command{gcc})
7353 When used in conjunction with @option{-gnatG}, this switch causes
7354 the expanded source, as described above for
7355 @option{-gnatG} to be written to files with names
7356 @file{^xxx.dg^XXX_DG^}, where @file{xxx} is the normal file name,
7357 instead of to the standard output file. For
7358 example, if the source file name is @file{hello.adb}, then a file
7359 @file{^hello.adb.dg^HELLO.ADB_DG^} will be written.  The debugging
7360 information generated by the @command{gcc} @option{^-g^/DEBUG^} switch
7361 will refer to the generated @file{^xxx.dg^XXX_DG^} file. This allows
7362 you to do source level debugging using the generated code which is
7363 sometimes useful for complex code, for example to find out exactly
7364 which part of a complex construction raised an exception. This switch
7365 also suppress generation of cross-reference information (see
7366 @option{-gnatx}) since otherwise the cross-reference information
7367 would refer to the @file{^.dg^.DG^} file, which would cause
7368 confusion since this is not the original source file.
7369
7370 Note that @option{-gnatD} actually implies @option{-gnatG}
7371 automatically, so it is not necessary to give both options.
7372 In other words @option{-gnatD} is equivalent to @option{-gnatDG}).
7373
7374 If the switch @option{-gnatL} is used in conjunction with
7375 @cindex @option{-gnatL} (@command{gcc})
7376 @option{-gnatDG}, then the original source lines are interspersed
7377 in the expanded source (as comment lines with the original line number).
7378
7379 The optional parameter @code{nn} if present after -gnatD specifies an
7380 alternative maximum line length that overrides the normal default of 72.
7381 This value is in the range 40-999999, values less than 40 being silently
7382 reset to 40. The equal sign is optional.
7383
7384 @item -gnatr
7385 @cindex @option{-gnatr} (@command{gcc})
7386 @cindex pragma Restrictions
7387 This switch causes pragma Restrictions to be treated as Restriction_Warnings
7388 so that violation of restrictions causes warnings rather than illegalities.
7389 This is useful during the development process when new restrictions are added
7390 or investigated. The switch also causes pragma Profile to be treated as
7391 Profile_Warnings, and pragma Restricted_Run_Time and pragma Ravenscar set
7392 restriction warnings rather than restrictions.
7393
7394 @ifclear vms
7395 @item -gnatR@r{[}0@r{|}1@r{|}2@r{|}3@r{[}s@r{]]}
7396 @cindex @option{-gnatR} (@command{gcc})
7397 This switch controls output from the compiler of a listing showing
7398 representation information for declared types and objects. For
7399 @option{-gnatR0}, no information is output (equivalent to omitting
7400 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
7401 so @option{-gnatR} with no parameter has the same effect), size and alignment
7402 information is listed for declared array and record types. For
7403 @option{-gnatR2}, size and alignment information is listed for all
7404 declared types and objects. Finally @option{-gnatR3} includes symbolic
7405 expressions for values that are computed at run time for
7406 variant records. These symbolic expressions have a mostly obvious
7407 format with #n being used to represent the value of the n'th
7408 discriminant. See source files @file{repinfo.ads/adb} in the
7409 @code{GNAT} sources for full details on the format of @option{-gnatR3}
7410 output. If the switch is followed by an s (e.g.@: @option{-gnatR2s}), then
7411 the output is to a file with the name @file{^file.rep^file_REP^} where
7412 file is the name of the corresponding source file.
7413 @end ifclear
7414 @ifset vms
7415 @item /REPRESENTATION_INFO
7416 @cindex @option{/REPRESENTATION_INFO} (@command{gcc})
7417 This qualifier controls output from the compiler of a listing showing
7418 representation information for declared types and objects. For
7419 @option{/REPRESENTATION_INFO=NONE}, no information is output
7420 (equivalent to omitting the @option{/REPRESENTATION_INFO} qualifier).
7421 @option{/REPRESENTATION_INFO} without option is equivalent to
7422 @option{/REPRESENTATION_INFO=ARRAYS}.
7423 For @option{/REPRESENTATION_INFO=ARRAYS}, size and alignment
7424 information is listed for declared array and record types. For
7425 @option{/REPRESENTATION_INFO=OBJECTS}, size and alignment information
7426 is listed for all expression information for values that are computed
7427 at run time for variant records. These symbolic expressions have a mostly
7428 obvious format with #n being used to represent the value of the n'th
7429 discriminant. See source files @file{REPINFO.ADS/ADB} in the
7430 @code{GNAT} sources for full details on the format of
7431 @option{/REPRESENTATION_INFO=SYMBOLIC} output.
7432 If _FILE is added at the end of an option
7433 (e.g.@: @option{/REPRESENTATION_INFO=ARRAYS_FILE}),
7434 then the output is to a file with the name @file{file_REP} where
7435 file is the name of the corresponding source file.
7436 @end ifset
7437 Note that it is possible for record components to have zero size. In
7438 this case, the component clause uses an obvious extension of permitted
7439 Ada syntax, for example @code{at 0 range 0 .. -1}.
7440
7441 Representation information requires that code be generated (since it is the
7442 code generator that lays out complex data structures). If an attempt is made
7443 to output representation information when no code is generated, for example
7444 when a subunit is compiled on its own, then no information can be generated
7445 and the compiler outputs a message to this effect.
7446
7447 @item -gnatS
7448 @cindex @option{-gnatS} (@command{gcc})
7449 The use of the switch @option{-gnatS} for an
7450 Ada compilation will cause the compiler to output a
7451 representation of package Standard in a form very
7452 close to standard Ada. It is not quite possible to
7453 do this entirely in standard Ada (since new
7454 numeric base types cannot be created in standard
7455 Ada), but the output is easily
7456 readable to any Ada programmer, and is useful to
7457 determine the characteristics of target dependent
7458 types in package Standard.
7459
7460 @item -gnatx
7461 @cindex @option{-gnatx} (@command{gcc})
7462 Normally the compiler generates full cross-referencing information in
7463 the @file{ALI} file. This information is used by a number of tools,
7464 including @code{gnatfind} and @code{gnatxref}. The @option{-gnatx} switch
7465 suppresses this information. This saves some space and may slightly
7466 speed up compilation, but means that these tools cannot be used.
7467 @end table
7468
7469 @node Exception Handling Control
7470 @subsection Exception Handling Control
7471
7472 @noindent
7473 GNAT uses two methods for handling exceptions at run-time. The
7474 @code{setjmp/longjmp} method saves the context when entering
7475 a frame with an exception handler. Then when an exception is
7476 raised, the context can be restored immediately, without the
7477 need for tracing stack frames. This method provides very fast
7478 exception propagation, but introduces significant overhead for
7479 the use of exception handlers, even if no exception is raised.
7480
7481 The other approach is called ``zero cost'' exception handling.
7482 With this method, the compiler builds static tables to describe
7483 the exception ranges. No dynamic code is required when entering
7484 a frame containing an exception handler. When an exception is
7485 raised, the tables are used to control a back trace of the
7486 subprogram invocation stack to locate the required exception
7487 handler. This method has considerably poorer performance for
7488 the propagation of exceptions, but there is no overhead for
7489 exception handlers if no exception is raised. Note that in this
7490 mode and in the context of mixed Ada and C/C++ programming,
7491 to propagate an exception through a C/C++ code, the C/C++ code
7492 must be compiled with the @option{-funwind-tables} GCC's
7493 option.
7494
7495 The following switches may be used to control which of the
7496 two exception handling methods is used.
7497
7498 @table @option
7499 @c !sort!
7500
7501 @item --RTS=sjlj
7502 @cindex @option{--RTS=sjlj} (@command{gnatmake})
7503 This switch causes the setjmp/longjmp run-time (when available) to be used
7504 for exception handling. If the default
7505 mechanism for the target is zero cost exceptions, then
7506 this switch can be used to modify this default, and must be
7507 used for all units in the partition.
7508 This option is rarely used. One case in which it may be
7509 advantageous is if you have an application where exception
7510 raising is common and the overall performance of the
7511 application is improved by favoring exception propagation.
7512
7513 @item --RTS=zcx
7514 @cindex @option{--RTS=zcx} (@command{gnatmake})
7515 @cindex Zero Cost Exceptions
7516 This switch causes the zero cost approach to be used
7517 for exception handling. If this is the default mechanism for the
7518 target (see below), then this switch is unneeded. If the default
7519 mechanism for the target is setjmp/longjmp exceptions, then
7520 this switch can be used to modify this default, and must be
7521 used for all units in the partition.
7522 This option can only be used if the zero cost approach
7523 is available for the target in use, otherwise it will generate an error.
7524 @end table
7525
7526 @noindent
7527 The same option @option{--RTS} must be used both for @command{gcc}
7528 and @command{gnatbind}. Passing this option to @command{gnatmake}
7529 (@pxref{Switches for gnatmake}) will ensure the required consistency
7530 through the compilation and binding steps.
7531
7532 @node Units to Sources Mapping Files
7533 @subsection Units to Sources Mapping Files
7534
7535 @table @option
7536
7537 @item -gnatem=@var{path}
7538 @cindex @option{-gnatem} (@command{gcc})
7539 A mapping file is a way to communicate to the compiler two mappings:
7540 from unit names to file names (without any directory information) and from
7541 file names to path names (with full directory information). These mappings
7542 are used by the compiler to short-circuit the path search.
7543
7544 The use of mapping files is not required for correct operation of the
7545 compiler, but mapping files can improve efficiency, particularly when
7546 sources are read over a slow network connection. In normal operation,
7547 you need not be concerned with the format or use of mapping files,
7548 and the @option{-gnatem} switch is not a switch that you would use
7549 explicitly. It is intended primarily for use by automatic tools such as
7550 @command{gnatmake} running under the project file facility. The
7551 description here of the format of mapping files is provided
7552 for completeness and for possible use by other tools.
7553
7554 A mapping file is a sequence of sets of three lines. In each set, the
7555 first line is the unit name, in lower case, with @code{%s} appended
7556 for specs and @code{%b} appended for bodies; the second line is the
7557 file name; and the third line is the path name.
7558
7559 Example:
7560 @smallexample
7561    main%b
7562    main.2.ada
7563    /gnat/project1/sources/main.2.ada
7564 @end smallexample
7565
7566 When the switch @option{-gnatem} is specified, the compiler will
7567 create in memory the two mappings from the specified file. If there is
7568 any problem (nonexistent file, truncated file or duplicate entries),
7569 no mapping will be created.
7570
7571 Several @option{-gnatem} switches may be specified; however, only the
7572 last one on the command line will be taken into account.
7573
7574 When using a project file, @command{gnatmake} creates a temporary
7575 mapping file and communicates it to the compiler using this switch.
7576
7577 @end table
7578
7579 @node Integrated Preprocessing
7580 @subsection Integrated Preprocessing
7581
7582 @noindent
7583 GNAT sources may be preprocessed immediately before compilation.
7584 In this case, the actual
7585 text of the source is not the text of the source file, but is derived from it
7586 through a process called preprocessing. Integrated preprocessing is specified
7587 through switches @option{-gnatep} and/or @option{-gnateD}. @option{-gnatep}
7588 indicates, through a text file, the preprocessing data to be used.
7589 @option{-gnateD} specifies or modifies the values of preprocessing symbol.
7590
7591 @noindent
7592 Note that when integrated preprocessing is used, the output from the
7593 preprocessor is not written to any external file. Instead it is passed
7594 internally to the compiler. If you need to preserve the result of
7595 preprocessing in a file, then you should use @command{gnatprep}
7596 to perform the desired preprocessing in stand-alone mode.
7597
7598 @noindent
7599 It is recommended that @command{gnatmake} switch ^-s^/SWITCH_CHECK^ should be
7600 used when Integrated Preprocessing is used. The reason is that preprocessing
7601 with another Preprocessing Data file without changing the sources will
7602 not trigger recompilation without this switch.
7603
7604 @noindent
7605 Note that @command{gnatmake} switch ^-m^/MINIMAL_RECOMPILATION^ will almost
7606 always trigger recompilation for sources that are preprocessed,
7607 because @command{gnatmake} cannot compute the checksum of the source after
7608 preprocessing.
7609
7610 @noindent
7611 The actual preprocessing function is described in details in section
7612 @ref{Preprocessing Using gnatprep}. This section only describes how integrated
7613 preprocessing is triggered and parameterized.
7614
7615 @table @code
7616
7617 @item -gnatep=@var{file}
7618 @cindex @option{-gnatep} (@command{gcc})
7619 This switch indicates to the compiler the file name (without directory
7620 information) of the preprocessor data file to use. The preprocessor data file
7621 should be found in the source directories.
7622
7623 @noindent
7624 A preprocessing data file is a text file with significant lines indicating
7625 how should be preprocessed either a specific source or all sources not
7626 mentioned in other lines. A significant line is a nonempty, non-comment line.
7627 Comments are similar to Ada comments.
7628
7629 @noindent
7630 Each significant line starts with either a literal string or the character '*'.
7631 A literal string is the file name (without directory information) of the source
7632 to preprocess. A character '*' indicates the preprocessing for all the sources
7633 that are not specified explicitly on other lines (order of the lines is not
7634 significant). It is an error to have two lines with the same file name or two
7635 lines starting with the character '*'.
7636
7637 @noindent
7638 After the file name or the character '*', another optional literal string
7639 indicating the file name of the definition file to be used for preprocessing
7640 (@pxref{Form of Definitions File}). The definition files are found by the
7641 compiler in one of the source directories. In some cases, when compiling
7642 a source in a directory other than the current directory, if the definition
7643 file is in the current directory, it may be necessary to add the current
7644 directory as a source directory through switch ^-I.^/SEARCH=[]^, otherwise
7645 the compiler would not find the definition file.
7646
7647 @noindent
7648 Then, optionally, ^switches^switches^ similar to those of @code{gnatprep} may
7649 be found. Those ^switches^switches^ are:
7650
7651 @table @code
7652
7653 @item -b
7654 Causes both preprocessor lines and the lines deleted by
7655 preprocessing to be replaced by blank lines, preserving the line number.
7656 This ^switch^switch^ is always implied; however, if specified after @option{-c}
7657 it cancels the effect of @option{-c}.
7658
7659 @item -c
7660 Causes both preprocessor lines and the lines deleted
7661 by preprocessing to be retained as comments marked
7662 with the special string ``@code{--! }''.
7663
7664 @item -Dsymbol=value
7665 Define or redefine a symbol, associated with value. A symbol is an Ada
7666 identifier, or an Ada reserved word, with the exception of @code{if},
7667 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7668 @code{value} is either a literal string, an Ada identifier or any Ada reserved
7669 word. A symbol declared with this ^switch^switch^ replaces a symbol with the
7670 same name defined in a definition file.
7671
7672 @item -s
7673 Causes a sorted list of symbol names and values to be
7674 listed on the standard output file.
7675
7676 @item -u
7677 Causes undefined symbols to be treated as having the value @code{FALSE}
7678 in the context
7679 of a preprocessor test. In the absence of this option, an undefined symbol in
7680 a @code{#if} or @code{#elsif} test will be treated as an error.
7681
7682 @end table
7683
7684 @noindent
7685 Examples of valid lines in a preprocessor data file:
7686
7687 @smallexample
7688   "toto.adb"  "prep.def" -u
7689   --  preprocess "toto.adb", using definition file "prep.def",
7690   --  undefined symbol are False.
7691
7692   * -c -DVERSION=V101
7693   --  preprocess all other sources without a definition file;
7694   --  suppressed lined are commented; symbol VERSION has the value V101.
7695
7696   "titi.adb" "prep2.def" -s
7697   --  preprocess "titi.adb", using definition file "prep2.def";
7698   --  list all symbols with their values.
7699 @end smallexample
7700
7701 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=value@r{]}
7702 @cindex @option{-gnateD} (@command{gcc})
7703 Define or redefine a preprocessing symbol, associated with value. If no value
7704 is given on the command line, then the value of the symbol is @code{True}.
7705 A symbol is an identifier, following normal Ada (case-insensitive)
7706 rules for its syntax, and value is any sequence (including an empty sequence)
7707 of characters from the set (letters, digits, period, underline).
7708 Ada reserved words may be used as symbols, with the exceptions of @code{if},
7709 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7710
7711 @noindent
7712 A symbol declared with this ^switch^switch^ on the command line replaces a
7713 symbol with the same name either in a definition file or specified with a
7714 ^switch^switch^ -D in the preprocessor data file.
7715
7716 @noindent
7717 This switch is similar to switch @option{^-D^/ASSOCIATE^} of @code{gnatprep}.
7718
7719 @item -gnateG
7720 When integrated preprocessing is performed and the preprocessor modifies
7721 the source text, write the result of this preprocessing into a file
7722 <source>^.prep^_prep^.
7723
7724 @end table
7725
7726 @node Code Generation Control
7727 @subsection Code Generation Control
7728
7729 @noindent
7730
7731 The GCC technology provides a wide range of target dependent
7732 @option{-m} switches for controlling
7733 details of code generation with respect to different versions of
7734 architectures. This includes variations in instruction sets (e.g.@:
7735 different members of the power pc family), and different requirements
7736 for optimal arrangement of instructions (e.g.@: different members of
7737 the x86 family). The list of available @option{-m} switches may be
7738 found in the GCC documentation.
7739
7740 Use of these @option{-m} switches may in some cases result in improved
7741 code performance.
7742
7743 The GNAT Pro technology is tested and qualified without any
7744 @option{-m} switches,
7745 so generally the most reliable approach is to avoid the use of these
7746 switches. However, we generally expect most of these switches to work
7747 successfully with GNAT Pro, and many customers have reported successful
7748 use of these options.
7749
7750 Our general advice is to avoid the use of @option{-m} switches unless
7751 special needs lead to requirements in this area. In particular,
7752 there is no point in using @option{-m} switches to improve performance
7753 unless you actually see a performance improvement.
7754
7755 @ifset vms
7756 @node Return Codes
7757 @subsection Return Codes
7758 @cindex Return Codes
7759 @cindex @option{/RETURN_CODES=VMS}
7760
7761 @noindent
7762 On VMS, GNAT compiled programs return POSIX-style codes by default,
7763 e.g.@: @option{/RETURN_CODES=POSIX}.
7764
7765 To enable VMS style return codes, use GNAT BIND and LINK with the option
7766 @option{/RETURN_CODES=VMS}. For example:
7767
7768 @smallexample
7769 GNAT BIND MYMAIN.ALI /RETURN_CODES=VMS
7770 GNAT LINK MYMAIN.ALI /RETURN_CODES=VMS
7771 @end smallexample
7772
7773 @noindent
7774 Programs built with /RETURN_CODES=VMS are suitable to be called in
7775 VMS DCL scripts. Programs compiled with the default /RETURN_CODES=POSIX
7776 are suitable for spawning with appropriate GNAT RTL routines.
7777
7778 @end ifset
7779
7780 @node Search Paths and the Run-Time Library (RTL)
7781 @section Search Paths and the Run-Time Library (RTL)
7782
7783 @noindent
7784 With the GNAT source-based library system, the compiler must be able to
7785 find source files for units that are needed by the unit being compiled.
7786 Search paths are used to guide this process.
7787
7788 The compiler compiles one source file whose name must be given
7789 explicitly on the command line. In other words, no searching is done
7790 for this file. To find all other source files that are needed (the most
7791 common being the specs of units), the compiler examines the following
7792 directories, in the following order:
7793
7794 @enumerate
7795 @item
7796 The directory containing the source file of the main unit being compiled
7797 (the file name on the command line).
7798
7799 @item
7800 Each directory named by an @option{^-I^/SOURCE_SEARCH^} switch given on the
7801 @command{gcc} command line, in the order given.
7802
7803 @item
7804 @findex ADA_PRJ_INCLUDE_FILE
7805 Each of the directories listed in the text file whose name is given
7806 by the @env{ADA_PRJ_INCLUDE_FILE} ^environment variable^logical name^.
7807
7808 @noindent
7809 @env{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
7810 driver when project files are used. It should not normally be set
7811 by other means.
7812
7813 @item
7814 @findex ADA_INCLUDE_PATH
7815 Each of the directories listed in the value of the
7816 @env{ADA_INCLUDE_PATH} ^environment variable^logical name^.
7817 @ifclear vms
7818 Construct this value
7819 exactly as the @env{PATH} environment variable: a list of directory
7820 names separated by colons (semicolons when working with the NT version).
7821 @end ifclear
7822 @ifset vms
7823 Normally, define this value as a logical name containing a comma separated
7824 list of directory names.
7825
7826 This variable can also be defined by means of an environment string
7827 (an argument to the HP C exec* set of functions).
7828
7829 Logical Name:
7830 @smallexample
7831 DEFINE ANOTHER_PATH FOO:[BAG]
7832 DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
7833 @end smallexample
7834
7835 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
7836 first, followed by the standard Ada
7837 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADAINCLUDE].
7838 If this is not redefined, the user will obtain the HP Ada 83 IO packages
7839 (Text_IO, Sequential_IO, etc)
7840 instead of the standard Ada packages. Thus, in order to get the standard Ada
7841 packages by default, ADA_INCLUDE_PATH must be redefined.
7842 @end ifset
7843
7844 @item
7845 The content of the @file{ada_source_path} file which is part of the GNAT
7846 installation tree and is used to store standard libraries such as the
7847 GNAT Run Time Library (RTL) source files.
7848 @ifclear vms
7849 @ref{Installing a library}
7850 @end ifclear
7851 @end enumerate
7852
7853 @noindent
7854 Specifying the switch @option{^-I-^/NOCURRENT_DIRECTORY^}
7855 inhibits the use of the directory
7856 containing the source file named in the command line. You can still
7857 have this directory on your search path, but in this case it must be
7858 explicitly requested with a @option{^-I^/SOURCE_SEARCH^} switch.
7859
7860 Specifying the switch @option{-nostdinc}
7861 inhibits the search of the default location for the GNAT Run Time
7862 Library (RTL) source files.
7863
7864 The compiler outputs its object files and ALI files in the current
7865 working directory.
7866 @ifclear vms
7867 Caution: The object file can be redirected with the @option{-o} switch;
7868 however, @command{gcc} and @code{gnat1} have not been coordinated on this
7869 so the @file{ALI} file will not go to the right place. Therefore, you should
7870 avoid using the @option{-o} switch.
7871 @end ifclear
7872
7873 @findex System.IO
7874 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
7875 children make up the GNAT RTL, together with the simple @code{System.IO}
7876 package used in the @code{"Hello World"} example. The sources for these units
7877 are needed by the compiler and are kept together in one directory. Not
7878 all of the bodies are needed, but all of the sources are kept together
7879 anyway. In a normal installation, you need not specify these directory
7880 names when compiling or binding. Either the environment variables or
7881 the built-in defaults cause these files to be found.
7882
7883 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
7884 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
7885 consisting of child units of @code{GNAT}. This is a collection of generally
7886 useful types, subprograms, etc. @xref{Top, GNAT Reference Manual, About
7887 This Guid, gnat_rm, GNAT Reference Manual}, for further details.
7888
7889 Besides simplifying access to the RTL, a major use of search paths is
7890 in compiling sources from multiple directories. This can make
7891 development environments much more flexible.
7892
7893 @node Order of Compilation Issues
7894 @section Order of Compilation Issues
7895
7896 @noindent
7897 If, in our earlier example, there was a spec for the @code{hello}
7898 procedure, it would be contained in the file @file{hello.ads}; yet this
7899 file would not have to be explicitly compiled. This is the result of the
7900 model we chose to implement library management. Some of the consequences
7901 of this model are as follows:
7902
7903 @itemize @bullet
7904 @item
7905 There is no point in compiling specs (except for package
7906 specs with no bodies) because these are compiled as needed by clients. If
7907 you attempt a useless compilation, you will receive an error message.
7908 It is also useless to compile subunits because they are compiled as needed
7909 by the parent.
7910
7911 @item
7912 There are no order of compilation requirements: performing a
7913 compilation never obsoletes anything. The only way you can obsolete
7914 something and require recompilations is to modify one of the
7915 source files on which it depends.
7916
7917 @item
7918 There is no library as such, apart from the ALI files
7919 (@pxref{The Ada Library Information Files}, for information on the format
7920 of these files). For now we find it convenient to create separate ALI files,
7921 but eventually the information therein may be incorporated into the object
7922 file directly.
7923
7924 @item
7925 When you compile a unit, the source files for the specs of all units
7926 that it @code{with}'s, all its subunits, and the bodies of any generics it
7927 instantiates must be available (reachable by the search-paths mechanism
7928 described above), or you will receive a fatal error message.
7929 @end itemize
7930
7931 @node Examples
7932 @section Examples
7933
7934 @noindent
7935 The following are some typical Ada compilation command line examples:
7936
7937 @table @code
7938 @item $ gcc -c xyz.adb
7939 Compile body in file @file{xyz.adb} with all default options.
7940
7941 @ifclear vms
7942 @item $ gcc -c -O2 -gnata xyz-def.adb
7943 @end ifclear
7944 @ifset vms
7945 @item $ GNAT COMPILE /OPTIMIZE=ALL -gnata xyz-def.adb
7946 @end ifset
7947
7948 Compile the child unit package in file @file{xyz-def.adb} with extensive
7949 optimizations, and pragma @code{Assert}/@code{Debug} statements
7950 enabled.
7951
7952 @item $ gcc -c -gnatc abc-def.adb
7953 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
7954 mode.
7955 @end table
7956
7957 @node Binding Using gnatbind
7958 @chapter Binding Using @code{gnatbind}
7959 @findex gnatbind
7960
7961 @menu
7962 * Running gnatbind::
7963 * Switches for gnatbind::
7964 * Command-Line Access::
7965 * Search Paths for gnatbind::
7966 * Examples of gnatbind Usage::
7967 @end menu
7968
7969 @noindent
7970 This chapter describes the GNAT binder, @code{gnatbind}, which is used
7971 to bind compiled GNAT objects.
7972
7973 Note: to invoke @code{gnatbind} with a project file, use the @code{gnat}
7974 driver (see @ref{The GNAT Driver and Project Files}).
7975
7976 The @code{gnatbind} program performs four separate functions:
7977
7978 @enumerate
7979 @item
7980 Checks that a program is consistent, in accordance with the rules in
7981 Chapter 10 of the Ada Reference Manual. In particular, error
7982 messages are generated if a program uses inconsistent versions of a
7983 given unit.
7984
7985 @item
7986 Checks that an acceptable order of elaboration exists for the program
7987 and issues an error message if it cannot find an order of elaboration
7988 that satisfies the rules in Chapter 10 of the Ada Language Manual.
7989
7990 @item
7991 Generates a main program incorporating the given elaboration order.
7992 This program is a small Ada package (body and spec) that
7993 must be subsequently compiled
7994 using the GNAT compiler. The necessary compilation step is usually
7995 performed automatically by @command{gnatlink}. The two most important
7996 functions of this program
7997 are to call the elaboration routines of units in an appropriate order
7998 and to call the main program.
7999
8000 @item
8001 Determines the set of object files required by the given main program.
8002 This information is output in the forms of comments in the generated program,
8003 to be read by the @command{gnatlink} utility used to link the Ada application.
8004 @end enumerate
8005
8006 @node Running gnatbind
8007 @section Running @code{gnatbind}
8008
8009 @noindent
8010 The form of the @code{gnatbind} command is
8011
8012 @smallexample
8013 @c $ gnatbind @ovar{switches} @var{mainprog}@r{[}.ali@r{]} @ovar{switches}
8014 @c Expanding @ovar macro inline (explanation in macro def comments)
8015 $ gnatbind @r{[}@var{switches}@r{]} @var{mainprog}@r{[}.ali@r{]} @r{[}@var{switches}@r{]}
8016 @end smallexample
8017
8018 @noindent
8019 where @file{@var{mainprog}.adb} is the Ada file containing the main program
8020 unit body. @code{gnatbind} constructs an Ada
8021 package in two files whose names are
8022 @file{b~@var{mainprog}.ads}, and @file{b~@var{mainprog}.adb}.
8023 For example, if given the
8024 parameter @file{hello.ali}, for a main program contained in file
8025 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
8026 and @file{b~hello.adb}.
8027
8028 When doing consistency checking, the binder takes into consideration
8029 any source files it can locate. For example, if the binder determines
8030 that the given main program requires the package @code{Pack}, whose
8031 @file{.ALI}
8032 file is @file{pack.ali} and whose corresponding source spec file is
8033 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
8034 (using the same search path conventions as previously described for the
8035 @command{gcc} command). If it can locate this source file, it checks that
8036 the time stamps
8037 or source checksums of the source and its references to in @file{ALI} files
8038 match. In other words, any @file{ALI} files that mentions this spec must have
8039 resulted from compiling this version of the source file (or in the case
8040 where the source checksums match, a version close enough that the
8041 difference does not matter).
8042
8043 @cindex Source files, use by binder
8044 The effect of this consistency checking, which includes source files, is
8045 that the binder ensures that the program is consistent with the latest
8046 version of the source files that can be located at bind time. Editing a
8047 source file without compiling files that depend on the source file cause
8048 error messages to be generated by the binder.
8049
8050 For example, suppose you have a main program @file{hello.adb} and a
8051 package @code{P}, from file @file{p.ads} and you perform the following
8052 steps:
8053
8054 @enumerate
8055 @item
8056 Enter @code{gcc -c hello.adb} to compile the main program.
8057
8058 @item
8059 Enter @code{gcc -c p.ads} to compile package @code{P}.
8060
8061 @item
8062 Edit file @file{p.ads}.
8063
8064 @item
8065 Enter @code{gnatbind hello}.
8066 @end enumerate
8067
8068 @noindent
8069 At this point, the file @file{p.ali} contains an out-of-date time stamp
8070 because the file @file{p.ads} has been edited. The attempt at binding
8071 fails, and the binder generates the following error messages:
8072
8073 @smallexample
8074 error: "hello.adb" must be recompiled ("p.ads" has been modified)
8075 error: "p.ads" has been modified and must be recompiled
8076 @end smallexample
8077
8078 @noindent
8079 Now both files must be recompiled as indicated, and then the bind can
8080 succeed, generating a main program. You need not normally be concerned
8081 with the contents of this file, but for reference purposes a sample
8082 binder output file is given in @ref{Example of Binder Output File}.
8083
8084 In most normal usage, the default mode of @command{gnatbind} which is to
8085 generate the main package in Ada, as described in the previous section.
8086 In particular, this means that any Ada programmer can read and understand
8087 the generated main program. It can also be debugged just like any other
8088 Ada code provided the @option{^-g^/DEBUG^} switch is used for
8089 @command{gnatbind} and @command{gnatlink}.
8090
8091 @node Switches for gnatbind
8092 @section Switches for @command{gnatbind}
8093
8094 @noindent
8095 The following switches are available with @code{gnatbind}; details will
8096 be presented in subsequent sections.
8097
8098 @menu
8099 * Consistency-Checking Modes::
8100 * Binder Error Message Control::
8101 * Elaboration Control::
8102 * Output Control::
8103 * Dynamic Allocation Control::
8104 * Binding with Non-Ada Main Programs::
8105 * Binding Programs with No Main Subprogram::
8106 @end menu
8107
8108 @table @option
8109 @c !sort!
8110
8111 @item --version
8112 @cindex @option{--version} @command{gnatbind}
8113 Display Copyright and version, then exit disregarding all other options.
8114
8115 @item --help
8116 @cindex @option{--help} @command{gnatbind}
8117 If @option{--version} was not used, display usage, then exit disregarding
8118 all other options.
8119
8120 @item -a
8121 @cindex @option{-a} @command{gnatbind}
8122 Indicates that, if supported by the platform, the adainit procedure should
8123 be treated as an initialisation routine by the linker (a constructor). This
8124 is intended to be used by the Project Manager to automatically initialize
8125 shared Stand-Alone Libraries.
8126
8127 @item ^-aO^/OBJECT_SEARCH^
8128 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatbind})
8129 Specify directory to be searched for ALI files.
8130
8131 @item ^-aI^/SOURCE_SEARCH^
8132 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
8133 Specify directory to be searched for source file.
8134
8135 @item ^-A^/ALI_LIST^@r{[=}@var{filename}@r{]}
8136 @cindex @option{^-A^/ALI_LIST^} (@command{gnatbind})
8137 Output ALI list (to standard output or to the named file).
8138
8139 @item ^-b^/REPORT_ERRORS=BRIEF^
8140 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@command{gnatbind})
8141 Generate brief messages to @file{stderr} even if verbose mode set.
8142
8143 @item ^-c^/NOOUTPUT^
8144 @cindex @option{^-c^/NOOUTPUT^} (@command{gnatbind})
8145 Check only, no generation of binder output file.
8146
8147 @item ^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
8148 @cindex @option{^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}} (@command{gnatbind})
8149 This switch can be used to change the default task stack size value
8150 to a specified size @var{nn}, which is expressed in bytes by default, or
8151 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8152 with @var{m}.
8153 In the absence of a @samp{@r{[}k@r{|}m@r{]}} suffix, this switch is equivalent,
8154 in effect, to completing all task specs with
8155 @smallexample @c ada
8156    pragma Storage_Size (nn);
8157 @end smallexample
8158 When they do not already have such a pragma.
8159
8160 @item ^-D^/DEFAULT_SECONDARY_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
8161 @cindex @option{^-D^/DEFAULT_SECONDARY_STACK_SIZE=nnnnn^} (@command{gnatbind})
8162 This switch can be used to change the default secondary stack size value
8163 to a specified size @var{nn}, which is expressed in bytes by default, or
8164 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8165 with @var{m}.
8166
8167 The secondary stack is used to deal with functions that return a variable
8168 sized result, for example a function returning an unconstrained
8169 String. There are two ways in which this secondary stack is allocated.
8170
8171 For most targets, the secondary stack is growing on demand and is allocated
8172 as a chain of blocks in the heap. The -D option is not very
8173 relevant. It only give some control over the size of the allocated
8174 blocks (whose size is the minimum of the default secondary stack size value,
8175 and the actual size needed for the current allocation request).
8176
8177 For certain targets, notably VxWorks 653,
8178 the secondary stack is allocated by carving off a fixed ratio chunk of the
8179 primary task stack. The -D option is used to define the
8180 size of the environment task's secondary stack.
8181
8182 @item ^-e^/ELABORATION_DEPENDENCIES^
8183 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@command{gnatbind})
8184 Output complete list of elaboration-order dependencies.
8185
8186 @item ^-E^/STORE_TRACEBACKS^
8187 @cindex @option{^-E^/STORE_TRACEBACKS^} (@command{gnatbind})
8188 Store tracebacks in exception occurrences when the target supports it.
8189 @ignore
8190 @c The following may get moved to an appendix
8191 This option is currently supported on the following targets:
8192 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
8193 @end ignore
8194 See also the packages @code{GNAT.Traceback} and
8195 @code{GNAT.Traceback.Symbolic} for more information.
8196 @ifclear vms
8197 Note that on x86 ports, you must not use @option{-fomit-frame-pointer}
8198 @command{gcc} option.
8199 @end ifclear
8200
8201 @item ^-F^/FORCE_ELABS_FLAGS^
8202 @cindex @option{^-F^/FORCE_ELABS_FLAGS^} (@command{gnatbind})
8203 Force the checks of elaboration flags. @command{gnatbind} does not normally
8204 generate checks of elaboration flags for the main executable, except when
8205 a Stand-Alone Library is used. However, there are cases when this cannot be
8206 detected by gnatbind. An example is importing an interface of a Stand-Alone
8207 Library through a pragma Import and only specifying through a linker switch
8208 this Stand-Alone Library. This switch is used to guarantee that elaboration
8209 flag checks are generated.
8210
8211 @item ^-h^/HELP^
8212 @cindex @option{^-h^/HELP^} (@command{gnatbind})
8213 Output usage (help) information
8214
8215 @item ^-H32^/32_MALLOC^
8216 @cindex @option{^-H32^/32_MALLOC^} (@command{gnatbind})
8217 Use 32-bit allocations for @code{__gnat_malloc} (and thus for access types).
8218 For further details see @ref{Dynamic Allocation Control}.
8219
8220 @item ^-H64^/64_MALLOC^
8221 @cindex @option{^-H32^/32_MALLOC^} (@command{gnatbind})
8222 Use 64-bit allocations for @code{__gnat_malloc} (and thus for access types).
8223 @cindex @code{__gnat_malloc}
8224 For further details see @ref{Dynamic Allocation Control}.
8225
8226 @item ^-I^/SEARCH^
8227 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8228 Specify directory to be searched for source and ALI files.
8229
8230 @item ^-I-^/NOCURRENT_DIRECTORY^
8231 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatbind})
8232 Do not look for sources in the current directory where @code{gnatbind} was
8233 invoked, and do not look for ALI files in the directory containing the
8234 ALI file named in the @code{gnatbind} command line.
8235
8236 @item ^-l^/ORDER_OF_ELABORATION^
8237 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@command{gnatbind})
8238 Output chosen elaboration order.
8239
8240 @item ^-L@var{xxx}^/BUILD_LIBRARY=@var{xxx}^
8241 @cindex @option{^-L^/BUILD_LIBRARY^} (@command{gnatbind})
8242 Bind the units for library building. In this case the adainit and
8243 adafinal procedures (@pxref{Binding with Non-Ada Main Programs})
8244 are renamed to ^@var{xxx}init^@var{XXX}INIT^ and
8245 ^@var{xxx}final^@var{XXX}FINAL^.
8246 Implies ^-n^/NOCOMPILE^.
8247 @ifclear vms
8248 (@xref{GNAT and Libraries}, for more details.)
8249 @end ifclear
8250 @ifset vms
8251 On OpenVMS, these init and final procedures are exported in uppercase
8252 letters. For example if /BUILD_LIBRARY=toto is used, the exported name of
8253 the init procedure will be "TOTOINIT" and the exported name of the final
8254 procedure will be "TOTOFINAL".
8255 @end ifset
8256
8257 @item ^-Mxyz^/RENAME_MAIN=xyz^
8258 @cindex @option{^-M^/RENAME_MAIN^} (@command{gnatbind})
8259 Rename generated main program from main to xyz. This option is
8260 supported on cross environments only.
8261
8262 @item ^-m^/ERROR_LIMIT=^@var{n}
8263 @cindex @option{^-m^/ERROR_LIMIT^} (@command{gnatbind})
8264 Limit number of detected errors or warnings to @var{n}, where @var{n} is
8265 in the range 1..999999. The default value if no switch is
8266 given is 9999. If the number of warnings reaches this limit, then a
8267 message is output and further warnings are suppressed, the bind
8268 continues in this case. If the number of errors reaches this
8269 limit, then a message is output and the bind is abandoned.
8270 A value of zero means that no limit is enforced. The equal
8271 sign is optional.
8272
8273 @ifset unw
8274 Furthermore, under Windows, the sources pointed to by the libraries path
8275 set in the registry are not searched for.
8276 @end ifset
8277
8278 @item ^-n^/NOMAIN^
8279 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8280 No main program.
8281
8282 @item -nostdinc
8283 @cindex @option{-nostdinc} (@command{gnatbind})
8284 Do not look for sources in the system default directory.
8285
8286 @item -nostdlib
8287 @cindex @option{-nostdlib} (@command{gnatbind})
8288 Do not look for library files in the system default directory.
8289
8290 @item --RTS=@var{rts-path}
8291 @cindex @option{--RTS} (@code{gnatbind})
8292 Specifies the default location of the runtime library. Same meaning as the
8293 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
8294
8295 @item ^-o ^/OUTPUT=^@var{file}
8296 @cindex @option{^-o ^/OUTPUT^} (@command{gnatbind})
8297 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
8298 Note that if this option is used, then linking must be done manually,
8299 gnatlink cannot be used.
8300
8301 @item ^-O^/OBJECT_LIST^@r{[=}@var{filename}@r{]}
8302 @cindex @option{^-O^/OBJECT_LIST^} (@command{gnatbind})
8303 Output object list (to standard output or to the named file).
8304
8305 @item ^-p^/PESSIMISTIC_ELABORATION^
8306 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@command{gnatbind})
8307 Pessimistic (worst-case) elaboration order
8308
8309 @item ^-R^-R^
8310 @cindex @option{^-R^-R^} (@command{gnatbind})
8311 Output closure source list.
8312
8313 @item ^-s^/READ_SOURCES=ALL^
8314 @cindex @option{^-s^/READ_SOURCES=ALL^} (@command{gnatbind})
8315 Require all source files to be present.
8316
8317 @item ^-S@var{xxx}^/INITIALIZE_SCALARS=@var{xxx}^
8318 @cindex @option{^-S^/INITIALIZE_SCALARS^} (@command{gnatbind})
8319 Specifies the value to be used when detecting uninitialized scalar
8320 objects with pragma Initialize_Scalars.
8321 The @var{xxx} ^string specified with the switch^option^ may be either
8322 @itemize @bullet
8323 @item ``@option{^in^INVALID^}'' requesting an invalid value where possible
8324 @item ``@option{^lo^LOW^}'' for the lowest possible value
8325 @item ``@option{^hi^HIGH^}'' for the highest possible value
8326 @item ``@option{@var{xx}}'' for a value consisting of repeated bytes with the
8327 value @code{16#@var{xx}#} (i.e., @var{xx} is a string of two hexadecimal digits).
8328 @end itemize
8329
8330 In addition, you can specify @option{-Sev} to indicate that the value is
8331 to be set at run time. In this case, the program will look for an environment
8332 @cindex GNAT_INIT_SCALARS
8333 variable of the form @env{GNAT_INIT_SCALARS=@var{xx}}, where @var{xx} is one
8334 of @option{in/lo/hi/@var{xx}} with the same meanings as above.
8335 If no environment variable is found, or if it does not have a valid value,
8336 then the default is @option{in} (invalid values).
8337
8338 @ifclear vms
8339 @item -static
8340 @cindex @option{-static} (@code{gnatbind})
8341 Link against a static GNAT run time.
8342
8343 @item -shared
8344 @cindex @option{-shared} (@code{gnatbind})
8345 Link against a shared GNAT run time when available.
8346 @end ifclear
8347
8348 @item ^-t^/NOTIME_STAMP_CHECK^
8349 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8350 Tolerate time stamp and other consistency errors
8351
8352 @item ^-T@var{n}^/TIME_SLICE=@var{n}^
8353 @cindex @option{^-T^/TIME_SLICE^} (@code{gnatbind})
8354 Set the time slice value to @var{n} milliseconds. If the system supports
8355 the specification of a specific time slice value, then the indicated value
8356 is used. If the system does not support specific time slice values, but
8357 does support some general notion of round-robin scheduling, then any
8358 nonzero value will activate round-robin scheduling.
8359
8360 A value of zero is treated specially. It turns off time
8361 slicing, and in addition, indicates to the tasking run time that the
8362 semantics should match as closely as possible the Annex D
8363 requirements of the Ada RM, and in particular sets the default
8364 scheduling policy to @code{FIFO_Within_Priorities}.
8365
8366 @item ^-u@var{n}^/DYNAMIC_STACK_USAGE=@var{n}^
8367 @cindex @option{^-u^/DYNAMIC_STACK_USAGE^} (@code{gnatbind})
8368 Enable dynamic stack usage, with @var{n} results stored and displayed
8369 at program termination. A result is generated when a task
8370 terminates. Results that can't be stored are displayed on the fly, at
8371 task termination. This option is currently not supported on Itanium
8372 platforms. (See @ref{Dynamic Stack Usage Analysis} for details.)
8373
8374 @item ^-v^/REPORT_ERRORS=VERBOSE^
8375 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8376 Verbose mode. Write error messages, header, summary output to
8377 @file{stdout}.
8378
8379 @ifclear vms
8380 @item -w@var{x}
8381 @cindex @option{-w} (@code{gnatbind})
8382 Warning mode (@var{x}=s/e for suppress/treat as error)
8383 @end ifclear
8384
8385 @ifset vms
8386 @item /WARNINGS=NORMAL
8387 @cindex @option{/WARNINGS} (@code{gnatbind})
8388 Normal warnings mode. Warnings are issued but ignored
8389
8390 @item /WARNINGS=SUPPRESS
8391 @cindex @option{/WARNINGS} (@code{gnatbind})
8392 All warning messages are suppressed
8393
8394 @item /WARNINGS=ERROR
8395 @cindex @option{/WARNINGS} (@code{gnatbind})
8396 Warning messages are treated as fatal errors
8397 @end ifset
8398
8399 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8400 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8401 Override default wide character encoding for standard Text_IO files.
8402
8403 @item ^-x^/READ_SOURCES=NONE^
8404 @cindex @option{^-x^/READ_SOURCES^} (@code{gnatbind})
8405 Exclude source files (check object consistency only).
8406
8407 @ifset vms
8408 @item /READ_SOURCES=AVAILABLE
8409 @cindex @option{/READ_SOURCES} (@code{gnatbind})
8410 Default mode, in which sources are checked for consistency only if
8411 they are available.
8412 @end ifset
8413
8414 @item ^-y^/ENABLE_LEAP_SECONDS^
8415 @cindex @option{^-y^/ENABLE_LEAP_SECONDS^} (@code{gnatbind})
8416 Enable leap seconds support in @code{Ada.Calendar} and its children.
8417
8418 @item ^-z^/ZERO_MAIN^
8419 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8420 No main subprogram.
8421 @end table
8422
8423 @ifclear vms
8424 @noindent
8425 You may obtain this listing of switches by running @code{gnatbind} with
8426 no arguments.
8427 @end ifclear
8428
8429 @node Consistency-Checking Modes
8430 @subsection Consistency-Checking Modes
8431
8432 @noindent
8433 As described earlier, by default @code{gnatbind} checks
8434 that object files are consistent with one another and are consistent
8435 with any source files it can locate. The following switches control binder
8436 access to sources.
8437
8438 @table @option
8439 @c !sort!
8440 @item ^-s^/READ_SOURCES=ALL^
8441 @cindex @option{^-s^/READ_SOURCES=ALL^} (@code{gnatbind})
8442 Require source files to be present. In this mode, the binder must be
8443 able to locate all source files that are referenced, in order to check
8444 their consistency. In normal mode, if a source file cannot be located it
8445 is simply ignored. If you specify this switch, a missing source
8446 file is an error.
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 Normally the default wide character encoding method used for standard
8452 [Wide_[Wide_]]Text_IO files is taken from the encoding specified for
8453 the main source input (see description of switch
8454 @option{^-gnatWx^/WIDE_CHARACTER_ENCODING^} for the compiler). The
8455 use of this switch for the binder (which has the same set of
8456 possible arguments) overrides this default as specified.
8457
8458 @item ^-x^/READ_SOURCES=NONE^
8459 @cindex @option{^-x^/READ_SOURCES=NONE^} (@code{gnatbind})
8460 Exclude source files. In this mode, the binder only checks that ALI
8461 files are consistent with one another. Source files are not accessed.
8462 The binder runs faster in this mode, and there is still a guarantee that
8463 the resulting program is self-consistent.
8464 If a source file has been edited since it was last compiled, and you
8465 specify this switch, the binder will not detect that the object
8466 file is out of date with respect to the source file. Note that this is the
8467 mode that is automatically used by @command{gnatmake} because in this
8468 case the checking against sources has already been performed by
8469 @command{gnatmake} in the course of compilation (i.e.@: before binding).
8470
8471 @ifset vms
8472 @item /READ_SOURCES=AVAILABLE
8473 @cindex @code{/READ_SOURCES=AVAILABLE} (@code{gnatbind})
8474 This is the default mode in which source files are checked if they are
8475 available, and ignored if they are not available.
8476 @end ifset
8477 @end table
8478
8479 @node Binder Error Message Control
8480 @subsection Binder Error Message Control
8481
8482 @noindent
8483 The following switches provide control over the generation of error
8484 messages from the binder:
8485
8486 @table @option
8487 @c !sort!
8488 @item ^-v^/REPORT_ERRORS=VERBOSE^
8489 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8490 Verbose mode. In the normal mode, brief error messages are generated to
8491 @file{stderr}. If this switch is present, a header is written
8492 to @file{stdout} and any error messages are directed to @file{stdout}.
8493 All that is written to @file{stderr} is a brief summary message.
8494
8495 @item ^-b^/REPORT_ERRORS=BRIEF^
8496 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@code{gnatbind})
8497 Generate brief error messages to @file{stderr} even if verbose mode is
8498 specified. This is relevant only when used with the
8499 @option{^-v^/REPORT_ERRORS=VERBOSE^} switch.
8500
8501 @ifclear vms
8502 @item -m@var{n}
8503 @cindex @option{-m} (@code{gnatbind})
8504 Limits the number of error messages to @var{n}, a decimal integer in the
8505 range 1-999. The binder terminates immediately if this limit is reached.
8506
8507 @item -M@var{xxx}
8508 @cindex @option{-M} (@code{gnatbind})
8509 Renames the generated main program from @code{main} to @code{xxx}.
8510 This is useful in the case of some cross-building environments, where
8511 the actual main program is separate from the one generated
8512 by @code{gnatbind}.
8513 @end ifclear
8514
8515 @item ^-ws^/WARNINGS=SUPPRESS^
8516 @cindex @option{^-ws^/WARNINGS=SUPPRESS^} (@code{gnatbind})
8517 @cindex Warnings
8518 Suppress all warning messages.
8519
8520 @item ^-we^/WARNINGS=ERROR^
8521 @cindex @option{^-we^/WARNINGS=ERROR^} (@code{gnatbind})
8522 Treat any warning messages as fatal errors.
8523
8524 @ifset vms
8525 @item /WARNINGS=NORMAL
8526 Standard mode with warnings generated, but warnings do not get treated
8527 as errors.
8528 @end ifset
8529
8530 @item ^-t^/NOTIME_STAMP_CHECK^
8531 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8532 @cindex Time stamp checks, in binder
8533 @cindex Binder consistency checks
8534 @cindex Consistency checks, in binder
8535 The binder performs a number of consistency checks including:
8536
8537 @itemize @bullet
8538 @item
8539 Check that time stamps of a given source unit are consistent
8540 @item
8541 Check that checksums of a given source unit are consistent
8542 @item
8543 Check that consistent versions of @code{GNAT} were used for compilation
8544 @item
8545 Check consistency of configuration pragmas as required
8546 @end itemize
8547
8548 @noindent
8549 Normally failure of such checks, in accordance with the consistency
8550 requirements of the Ada Reference Manual, causes error messages to be
8551 generated which abort the binder and prevent the output of a binder
8552 file and subsequent link to obtain an executable.
8553
8554 The @option{^-t^/NOTIME_STAMP_CHECK^} switch converts these error messages
8555 into warnings, so that
8556 binding and linking can continue to completion even in the presence of such
8557 errors. The result may be a failed link (due to missing symbols), or a
8558 non-functional executable which has undefined semantics.
8559 @emph{This means that
8560 @option{^-t^/NOTIME_STAMP_CHECK^} should be used only in unusual situations,
8561 with extreme care.}
8562 @end table
8563
8564 @node Elaboration Control
8565 @subsection Elaboration Control
8566
8567 @noindent
8568 The following switches provide additional control over the elaboration
8569 order. For full details see @ref{Elaboration Order Handling in GNAT}.
8570
8571 @table @option
8572 @item ^-p^/PESSIMISTIC_ELABORATION^
8573 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@code{gnatbind})
8574 Normally the binder attempts to choose an elaboration order that is
8575 likely to minimize the likelihood of an elaboration order error resulting
8576 in raising a @code{Program_Error} exception. This switch reverses the
8577 action of the binder, and requests that it deliberately choose an order
8578 that is likely to maximize the likelihood of an elaboration error.
8579 This is useful in ensuring portability and avoiding dependence on
8580 accidental fortuitous elaboration ordering.
8581
8582 Normally it only makes sense to use the @option{^-p^/PESSIMISTIC_ELABORATION^}
8583 switch if dynamic
8584 elaboration checking is used (@option{-gnatE} switch used for compilation).
8585 This is because in the default static elaboration mode, all necessary
8586 @code{Elaborate} and @code{Elaborate_All} pragmas are implicitly inserted.
8587 These implicit pragmas are still respected by the binder in
8588 @option{^-p^/PESSIMISTIC_ELABORATION^} mode, so a
8589 safe elaboration order is assured.
8590 @end table
8591
8592 @node Output Control
8593 @subsection Output Control
8594
8595 @noindent
8596 The following switches allow additional control over the output
8597 generated by the binder.
8598
8599 @table @option
8600 @c !sort!
8601
8602 @item ^-c^/NOOUTPUT^
8603 @cindex @option{^-c^/NOOUTPUT^} (@code{gnatbind})
8604 Check only. Do not generate the binder output file. In this mode the
8605 binder performs all error checks but does not generate an output file.
8606
8607 @item ^-e^/ELABORATION_DEPENDENCIES^
8608 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@code{gnatbind})
8609 Output complete list of elaboration-order dependencies, showing the
8610 reason for each dependency. This output can be rather extensive but may
8611 be useful in diagnosing problems with elaboration order. The output is
8612 written to @file{stdout}.
8613
8614 @item ^-h^/HELP^
8615 @cindex @option{^-h^/HELP^} (@code{gnatbind})
8616 Output usage information. The output is written to @file{stdout}.
8617
8618 @item ^-K^/LINKER_OPTION_LIST^
8619 @cindex @option{^-K^/LINKER_OPTION_LIST^} (@code{gnatbind})
8620 Output linker options to @file{stdout}. Includes library search paths,
8621 contents of pragmas Ident and Linker_Options, and libraries added
8622 by @code{gnatbind}.
8623
8624 @item ^-l^/ORDER_OF_ELABORATION^
8625 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@code{gnatbind})
8626 Output chosen elaboration order. The output is written to @file{stdout}.
8627
8628 @item ^-O^/OBJECT_LIST^
8629 @cindex @option{^-O^/OBJECT_LIST^} (@code{gnatbind})
8630 Output full names of all the object files that must be linked to provide
8631 the Ada component of the program. The output is written to @file{stdout}.
8632 This list includes the files explicitly supplied and referenced by the user
8633 as well as implicitly referenced run-time unit files. The latter are
8634 omitted if the corresponding units reside in shared libraries. The
8635 directory names for the run-time units depend on the system configuration.
8636
8637 @item ^-o ^/OUTPUT=^@var{file}
8638 @cindex @option{^-o^/OUTPUT^} (@code{gnatbind})
8639 Set name of output file to @var{file} instead of the normal
8640 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
8641 binder generated body filename.
8642 Note that if this option is used, then linking must be done manually.
8643 It is not possible to use gnatlink in this case, since it cannot locate
8644 the binder file.
8645
8646 @item ^-r^/RESTRICTION_LIST^
8647 @cindex @option{^-r^/RESTRICTION_LIST^} (@code{gnatbind})
8648 Generate list of @code{pragma Restrictions} that could be applied to
8649 the current unit. This is useful for code audit purposes, and also may
8650 be used to improve code generation in some cases.
8651
8652 @end table
8653
8654 @node Dynamic Allocation Control
8655 @subsection Dynamic Allocation Control
8656
8657 @noindent
8658 The heap control switches -- @option{-H32} and @option{-H64} --
8659 determine whether dynamic allocation uses 32-bit or 64-bit memory.
8660 They only affect compiler-generated allocations via @code{__gnat_malloc};
8661 explicit calls to @code{malloc} and related functions from the C
8662 run-time library are unaffected.
8663
8664 @table @option
8665 @item -H32
8666 Allocate memory on 32-bit heap
8667
8668 @item -H64
8669 Allocate memory on 64-bit heap.  This is the default
8670 unless explicitly overridden by a @code{'Size} clause on the access type.
8671 @end table
8672
8673 @ifset vms
8674 @noindent
8675 See also @ref{Access types and 32/64-bit allocation}.
8676 @end ifset
8677 @ifclear vms
8678 @noindent
8679 These switches are only effective on VMS platforms.
8680 @end ifclear
8681
8682
8683 @node Binding with Non-Ada Main Programs
8684 @subsection Binding with Non-Ada Main Programs
8685
8686 @noindent
8687 In our description so far we have assumed that the main
8688 program is in Ada, and that the task of the binder is to generate a
8689 corresponding function @code{main} that invokes this Ada main
8690 program. GNAT also supports the building of executable programs where
8691 the main program is not in Ada, but some of the called routines are
8692 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
8693 The following switch is used in this situation:
8694
8695 @table @option
8696 @item ^-n^/NOMAIN^
8697 @cindex @option{^-n^/NOMAIN^} (@code{gnatbind})
8698 No main program. The main program is not in Ada.
8699 @end table
8700
8701 @noindent
8702 In this case, most of the functions of the binder are still required,
8703 but instead of generating a main program, the binder generates a file
8704 containing the following callable routines:
8705
8706 @table @code
8707 @item adainit
8708 @findex adainit
8709 You must call this routine to initialize the Ada part of the program by
8710 calling the necessary elaboration routines. A call to @code{adainit} is
8711 required before the first call to an Ada subprogram.
8712
8713 Note that it is assumed that the basic execution environment must be setup
8714 to be appropriate for Ada execution at the point where the first Ada
8715 subprogram is called. In particular, if the Ada code will do any
8716 floating-point operations, then the FPU must be setup in an appropriate
8717 manner. For the case of the x86, for example, full precision mode is
8718 required. The procedure GNAT.Float_Control.Reset may be used to ensure
8719 that the FPU is in the right state.
8720
8721 @item adafinal
8722 @findex adafinal
8723 You must call this routine to perform any library-level finalization
8724 required by the Ada subprograms. A call to @code{adafinal} is required
8725 after the last call to an Ada subprogram, and before the program
8726 terminates.
8727 @end table
8728
8729 @noindent
8730 If the @option{^-n^/NOMAIN^} switch
8731 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8732 @cindex Binder, multiple input files
8733 is given, more than one ALI file may appear on
8734 the command line for @code{gnatbind}. The normal @dfn{closure}
8735 calculation is performed for each of the specified units. Calculating
8736 the closure means finding out the set of units involved by tracing
8737 @code{with} references. The reason it is necessary to be able to
8738 specify more than one ALI file is that a given program may invoke two or
8739 more quite separate groups of Ada units.
8740
8741 The binder takes the name of its output file from the last specified ALI
8742 file, unless overridden by the use of the @option{^-o file^/OUTPUT=file^}.
8743 @cindex @option{^-o^/OUTPUT^} (@command{gnatbind})
8744 The output is an Ada unit in source form that can be compiled with GNAT.
8745 This compilation occurs automatically as part of the @command{gnatlink}
8746 processing.
8747
8748 Currently the GNAT run time requires a FPU using 80 bits mode
8749 precision. Under targets where this is not the default it is required to
8750 call GNAT.Float_Control.Reset before using floating point numbers (this
8751 include float computation, float input and output) in the Ada code. A
8752 side effect is that this could be the wrong mode for the foreign code
8753 where floating point computation could be broken after this call.
8754
8755 @node Binding Programs with No Main Subprogram
8756 @subsection Binding Programs with No Main Subprogram
8757
8758 @noindent
8759 It is possible to have an Ada program which does not have a main
8760 subprogram. This program will call the elaboration routines of all the
8761 packages, then the finalization routines.
8762
8763 The following switch is used to bind programs organized in this manner:
8764
8765 @table @option
8766 @item ^-z^/ZERO_MAIN^
8767 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8768 Normally the binder checks that the unit name given on the command line
8769 corresponds to a suitable main subprogram. When this switch is used,
8770 a list of ALI files can be given, and the execution of the program
8771 consists of elaboration of these units in an appropriate order. Note
8772 that the default wide character encoding method for standard Text_IO
8773 files is always set to Brackets if this switch is set (you can use
8774 the binder switch
8775 @option{^-Wx^WIDE_CHARACTER_ENCODING^} to override this default).
8776 @end table
8777
8778 @node Command-Line Access
8779 @section Command-Line Access
8780
8781 @noindent
8782 The package @code{Ada.Command_Line} provides access to the command-line
8783 arguments and program name. In order for this interface to operate
8784 correctly, the two variables
8785
8786 @smallexample
8787 @group
8788 int gnat_argc;
8789 char **gnat_argv;
8790 @end group
8791 @end smallexample
8792
8793 @noindent
8794 @findex gnat_argv
8795 @findex gnat_argc
8796 are declared in one of the GNAT library routines. These variables must
8797 be set from the actual @code{argc} and @code{argv} values passed to the
8798 main program. With no @option{^n^/NOMAIN^} present, @code{gnatbind}
8799 generates the C main program to automatically set these variables.
8800 If the @option{^n^/NOMAIN^} switch is used, there is no automatic way to
8801 set these variables. If they are not set, the procedures in
8802 @code{Ada.Command_Line} will not be available, and any attempt to use
8803 them will raise @code{Constraint_Error}. If command line access is
8804 required, your main program must set @code{gnat_argc} and
8805 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
8806 it.
8807
8808 @node Search Paths for gnatbind
8809 @section Search Paths for @code{gnatbind}
8810
8811 @noindent
8812 The binder takes the name of an ALI file as its argument and needs to
8813 locate source files as well as other ALI files to verify object consistency.
8814
8815 For source files, it follows exactly the same search rules as @command{gcc}
8816 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
8817 directories searched are:
8818
8819 @enumerate
8820 @item
8821 The directory containing the ALI file named in the command line, unless
8822 the switch @option{^-I-^/NOCURRENT_DIRECTORY^} is specified.
8823
8824 @item
8825 All directories specified by @option{^-I^/SEARCH^}
8826 switches on the @code{gnatbind}
8827 command line, in the order given.
8828
8829 @item
8830 @findex ADA_PRJ_OBJECTS_FILE
8831 Each of the directories listed in the text file whose name is given
8832 by the @env{ADA_PRJ_OBJECTS_FILE} ^environment variable^logical name^.
8833
8834 @noindent
8835 @env{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
8836 driver when project files are used. It should not normally be set
8837 by other means.
8838
8839 @item
8840 @findex ADA_OBJECTS_PATH
8841 Each of the directories listed in the value of the
8842 @env{ADA_OBJECTS_PATH} ^environment variable^logical name^.
8843 @ifset unw
8844 Construct this value
8845 exactly as the @env{PATH} environment variable: a list of directory
8846 names separated by colons (semicolons when working with the NT version
8847 of GNAT).
8848 @end ifset
8849 @ifset vms
8850 Normally, define this value as a logical name containing a comma separated
8851 list of directory names.
8852
8853 This variable can also be defined by means of an environment string
8854 (an argument to the HP C exec* set of functions).
8855
8856 Logical Name:
8857 @smallexample
8858 DEFINE ANOTHER_PATH FOO:[BAG]
8859 DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
8860 @end smallexample
8861
8862 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
8863 first, followed by the standard Ada
8864 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB].
8865 If this is not redefined, the user will obtain the HP Ada 83 IO packages
8866 (Text_IO, Sequential_IO, etc)
8867 instead of the standard Ada packages. Thus, in order to get the standard Ada
8868 packages by default, ADA_OBJECTS_PATH must be redefined.
8869 @end ifset
8870
8871 @item
8872 The content of the @file{ada_object_path} file which is part of the GNAT
8873 installation tree and is used to store standard libraries such as the
8874 GNAT Run Time Library (RTL) unless the switch @option{-nostdlib} is
8875 specified.
8876 @ifclear vms
8877 @ref{Installing a library}
8878 @end ifclear
8879 @end enumerate
8880
8881 @noindent
8882 In the binder the switch @option{^-I^/SEARCH^}
8883 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8884 is used to specify both source and
8885 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
8886 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
8887 instead if you want to specify
8888 source paths only, and @option{^-aO^/LIBRARY_SEARCH^}
8889 @cindex @option{^-aO^/LIBRARY_SEARCH^} (@command{gnatbind})
8890 if you want to specify library paths
8891 only. This means that for the binder
8892 @option{^-I^/SEARCH=^}@var{dir} is equivalent to
8893 @option{^-aI^/SOURCE_SEARCH=^}@var{dir}
8894 @option{^-aO^/OBJECT_SEARCH=^}@var{dir}.
8895 The binder generates the bind file (a C language source file) in the
8896 current working directory.
8897
8898 @findex Ada
8899 @findex System
8900 @findex Interfaces
8901 @findex GNAT
8902 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
8903 children make up the GNAT Run-Time Library, together with the package
8904 GNAT and its children, which contain a set of useful additional
8905 library functions provided by GNAT. The sources for these units are
8906 needed by the compiler and are kept together in one directory. The ALI
8907 files and object files generated by compiling the RTL are needed by the
8908 binder and the linker and are kept together in one directory, typically
8909 different from the directory containing the sources. In a normal
8910 installation, you need not specify these directory names when compiling
8911 or binding. Either the environment variables or the built-in defaults
8912 cause these files to be found.
8913
8914 Besides simplifying access to the RTL, a major use of search paths is
8915 in compiling sources from multiple directories. This can make
8916 development environments much more flexible.
8917
8918 @node Examples of gnatbind Usage
8919 @section Examples of @code{gnatbind} Usage
8920
8921 @noindent
8922 This section contains a number of examples of using the GNAT binding
8923 utility @code{gnatbind}.
8924
8925 @table @code
8926 @item gnatbind hello
8927 The main program @code{Hello} (source program in @file{hello.adb}) is
8928 bound using the standard switch settings. The generated main program is
8929 @file{b~hello.adb}. This is the normal, default use of the binder.
8930
8931 @ifclear vms
8932 @item gnatbind hello -o mainprog.adb
8933 @end ifclear
8934 @ifset vms
8935 @item gnatbind HELLO.ALI /OUTPUT=Mainprog.ADB
8936 @end ifset
8937 The main program @code{Hello} (source program in @file{hello.adb}) is
8938 bound using the standard switch settings. The generated main program is
8939 @file{mainprog.adb} with the associated spec in
8940 @file{mainprog.ads}. Note that you must specify the body here not the
8941 spec. Note that if this option is used, then linking must be done manually,
8942 since gnatlink will not be able to find the generated file.
8943 @end table
8944
8945 @c ------------------------------------
8946 @node Linking Using gnatlink
8947 @chapter Linking Using @command{gnatlink}
8948 @c ------------------------------------
8949 @findex gnatlink
8950
8951 @noindent
8952 This chapter discusses @command{gnatlink}, a tool that links
8953 an Ada program and builds an executable file. This utility
8954 invokes the system linker ^(via the @command{gcc} command)^^
8955 with a correct list of object files and library references.
8956 @command{gnatlink} automatically determines the list of files and
8957 references for the Ada part of a program. It uses the binder file
8958 generated by the @command{gnatbind} to determine this list.
8959
8960 Note: to invoke @code{gnatlink} with a project file, use the @code{gnat}
8961 driver (see @ref{The GNAT Driver and Project Files}).
8962
8963 @menu
8964 * Running gnatlink::
8965 * Switches for gnatlink::
8966 @end menu
8967
8968 @node Running gnatlink
8969 @section Running @command{gnatlink}
8970
8971 @noindent
8972 The form of the @command{gnatlink} command is
8973
8974 @smallexample
8975 @c $ gnatlink @ovar{switches} @var{mainprog}@r{[}.ali@r{]}
8976 @c            @ovar{non-Ada objects} @ovar{linker options}
8977 @c Expanding @ovar macro inline (explanation in macro def comments)
8978 $ gnatlink @r{[}@var{switches}@r{]} @var{mainprog}@r{[}.ali@r{]}
8979            @r{[}@var{non-Ada objects}@r{]} @r{[}@var{linker options}@r{]}
8980
8981 @end smallexample
8982
8983 @noindent
8984 The arguments of @command{gnatlink} (switches, main @file{ALI} file,
8985 non-Ada objects
8986 or linker options) may be in any order, provided that no non-Ada object may
8987 be mistaken for a main @file{ALI} file.
8988 Any file name @file{F} without the @file{.ali}
8989 extension will be taken as the main @file{ALI} file if a file exists
8990 whose name is the concatenation of @file{F} and @file{.ali}.
8991
8992 @noindent
8993 @file{@var{mainprog}.ali} references the ALI file of the main program.
8994 The @file{.ali} extension of this file can be omitted. From this
8995 reference, @command{gnatlink} locates the corresponding binder file
8996 @file{b~@var{mainprog}.adb} and, using the information in this file along
8997 with the list of non-Ada objects and linker options, constructs a
8998 linker command file to create the executable.
8999
9000 The arguments other than the @command{gnatlink} switches and the main
9001 @file{ALI} file are passed to the linker uninterpreted.
9002 They typically include the names of
9003 object files for units written in other languages than Ada and any library
9004 references required to resolve references in any of these foreign language
9005 units, or in @code{Import} pragmas in any Ada units.
9006
9007 @var{linker options} is an optional list of linker specific
9008 switches.
9009 The default linker called by gnatlink is @command{gcc} which in
9010 turn calls the appropriate system linker.
9011
9012 One useful option for the linker is @option{-s}: it reduces the size of the
9013 executable by removing all symbol table and relocation information from the
9014 executable.
9015
9016 Standard options for the linker such as @option{-lmy_lib} or
9017 @option{-Ldir} can be added as is.
9018 For options that are not recognized by
9019 @command{gcc} as linker options, use the @command{gcc} switches
9020 @option{-Xlinker} or @option{-Wl,}.
9021
9022 Refer to the GCC documentation for
9023 details.
9024
9025 Here is an example showing how to generate a linker map:
9026
9027 @smallexample
9028 $ ^gnatlink my_prog -Wl,-Map,MAPFILE^GNAT LINK my_prog.ali /MAP^
9029 @end smallexample
9030
9031 Using @var{linker options} it is possible to set the program stack and
9032 heap size.
9033 @ifset unw
9034 See @ref{Setting Stack Size from gnatlink} and
9035 @ref{Setting Heap Size from gnatlink}.
9036 @end ifset
9037
9038 @command{gnatlink} determines the list of objects required by the Ada
9039 program and prepends them to the list of objects passed to the linker.
9040 @command{gnatlink} also gathers any arguments set by the use of
9041 @code{pragma Linker_Options} and adds them to the list of arguments
9042 presented to the linker.
9043
9044 @ifset vms
9045 @command{gnatlink} accepts the following types of extra files on the command
9046 line: objects (@file{.OBJ}), libraries (@file{.OLB}), sharable images
9047 (@file{.EXE}), and options files (@file{.OPT}). These are recognized and
9048 handled according to their extension.
9049 @end ifset
9050
9051 @node Switches for gnatlink
9052 @section Switches for @command{gnatlink}
9053
9054 @noindent
9055 The following switches are available with the @command{gnatlink} utility:
9056
9057 @table @option
9058 @c !sort!
9059
9060 @item --version
9061 @cindex @option{--version} @command{gnatlink}
9062 Display Copyright and version, then exit disregarding all other options.
9063
9064 @item --help
9065 @cindex @option{--help} @command{gnatlink}
9066 If @option{--version} was not used, display usage, then exit disregarding
9067 all other options.
9068
9069 @item ^-f^/FORCE_OBJECT_FILE_LIST^
9070 @cindex Command line length
9071 @cindex @option{^-f^/FORCE_OBJECT_FILE_LIST^} (@command{gnatlink})
9072 On some targets, the command line length is limited, and @command{gnatlink}
9073 will generate a separate file for the linker if the list of object files
9074 is too long.
9075 The @option{^-f^/FORCE_OBJECT_FILE_LIST^} switch forces this file
9076 to be generated even if
9077 the limit is not exceeded. This is useful in some cases to deal with
9078 special situations where the command line length is exceeded.
9079
9080 @item ^-g^/DEBUG^
9081 @cindex Debugging information, including
9082 @cindex @option{^-g^/DEBUG^} (@command{gnatlink})
9083 The option to include debugging information causes the Ada bind file (in
9084 other words, @file{b~@var{mainprog}.adb}) to be compiled with
9085 @option{^-g^/DEBUG^}.
9086 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
9087 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
9088 Without @option{^-g^/DEBUG^}, the binder removes these files by
9089 default. The same procedure apply if a C bind file was generated using
9090 @option{^-C^/BIND_FILE=C^} @code{gnatbind} option, in this case the filenames
9091 are @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
9092
9093 @item ^-n^/NOCOMPILE^
9094 @cindex @option{^-n^/NOCOMPILE^} (@command{gnatlink})
9095 Do not compile the file generated by the binder. This may be used when
9096 a link is rerun with different options, but there is no need to recompile
9097 the binder file.
9098
9099 @item ^-v^/VERBOSE^
9100 @cindex @option{^-v^/VERBOSE^} (@command{gnatlink})
9101 Causes additional information to be output, including a full list of the
9102 included object files. This switch option is most useful when you want
9103 to see what set of object files are being used in the link step.
9104
9105 @item ^-v -v^/VERBOSE/VERBOSE^
9106 @cindex @option{^-v -v^/VERBOSE/VERBOSE^} (@command{gnatlink})
9107 Very verbose mode. Requests that the compiler operate in verbose mode when
9108 it compiles the binder file, and that the system linker run in verbose mode.
9109
9110 @item ^-o ^/EXECUTABLE=^@var{exec-name}
9111 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatlink})
9112 @var{exec-name} specifies an alternate name for the generated
9113 executable program. If this switch is omitted, the executable has the same
9114 name as the main unit. For example, @code{gnatlink try.ali} creates
9115 an executable called @file{^try^TRY.EXE^}.
9116
9117 @ifclear vms
9118 @item -b @var{target}
9119 @cindex @option{-b} (@command{gnatlink})
9120 Compile your program to run on @var{target}, which is the name of a
9121 system configuration. You must have a GNAT cross-compiler built if
9122 @var{target} is not the same as your host system.
9123
9124 @item -B@var{dir}
9125 @cindex @option{-B} (@command{gnatlink})
9126 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
9127 from @var{dir} instead of the default location. Only use this switch
9128 when multiple versions of the GNAT compiler are available.
9129 @xref{Directory Options,,, gcc, The GNU Compiler Collection},
9130 for further details. You would normally use the @option{-b} or
9131 @option{-V} switch instead.
9132
9133 @item --GCC=@var{compiler_name}
9134 @cindex @option{--GCC=compiler_name} (@command{gnatlink})
9135 Program used for compiling the binder file. The default is
9136 @command{gcc}. You need to use quotes around @var{compiler_name} if
9137 @code{compiler_name} contains spaces or other separator characters.
9138 As an example @option{--GCC="foo -x -y"} will instruct @command{gnatlink} to
9139 use @code{foo -x -y} as your compiler. Note that switch @option{-c} is always
9140 inserted after your command name. Thus in the above example the compiler
9141 command that will be used by @command{gnatlink} will be @code{foo -c -x -y}.
9142 A limitation of this syntax is that the name and path name of the executable
9143 itself must not include any embedded spaces. If the compiler executable is
9144 different from the default one (gcc or <prefix>-gcc), then the back-end
9145 switches in the ALI file are not used to compile the binder generated source.
9146 For example, this is the case with @option{--GCC="foo -x -y"}. But the back end
9147 switches will be used for @option{--GCC="gcc -gnatv"}. If several
9148 @option{--GCC=compiler_name} are used, only the last @var{compiler_name}
9149 is taken into account. However, all the additional switches are also taken
9150 into account. Thus,
9151 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9152 @option{--GCC="bar -x -y -z -t"}.
9153
9154 @item --LINK=@var{name}
9155 @cindex @option{--LINK=} (@command{gnatlink})
9156 @var{name} is the name of the linker to be invoked. This is especially
9157 useful in mixed language programs since languages such as C++ require
9158 their own linker to be used. When this switch is omitted, the default
9159 name for the linker is @command{gcc}. When this switch is used, the
9160 specified linker is called instead of @command{gcc} with exactly the same
9161 parameters that would have been passed to @command{gcc} so if the desired
9162 linker requires different parameters it is necessary to use a wrapper
9163 script that massages the parameters before invoking the real linker. It
9164 may be useful to control the exact invocation by using the verbose
9165 switch.
9166
9167 @end ifclear
9168
9169 @ifset vms
9170 @item /DEBUG=TRACEBACK
9171 @cindex @code{/DEBUG=TRACEBACK} (@command{gnatlink})
9172 This qualifier causes sufficient information to be included in the
9173 executable file to allow a traceback, but does not include the full
9174 symbol information needed by the debugger.
9175
9176 @item /IDENTIFICATION="<string>"
9177 @code{"<string>"} specifies the string to be stored in the image file
9178 identification field in the image header.
9179 It overrides any pragma @code{Ident} specified string.
9180
9181 @item /NOINHIBIT-EXEC
9182 Generate the executable file even if there are linker warnings.
9183
9184 @item /NOSTART_FILES
9185 Don't link in the object file containing the ``main'' transfer address.
9186 Used when linking with a foreign language main program compiled with an
9187 HP compiler.
9188
9189 @item /STATIC
9190 Prefer linking with object libraries over sharable images, even without
9191 /DEBUG.
9192 @end ifset
9193
9194 @end table
9195
9196 @node The GNAT Make Program gnatmake
9197 @chapter The GNAT Make Program @command{gnatmake}
9198 @findex gnatmake
9199
9200 @menu
9201 * Running gnatmake::
9202 * Switches for gnatmake::
9203 * Mode Switches for gnatmake::
9204 * Notes on the Command Line::
9205 * How gnatmake Works::
9206 * Examples of gnatmake Usage::
9207 @end menu
9208 @noindent
9209 A typical development cycle when working on an Ada program consists of
9210 the following steps:
9211
9212 @enumerate
9213 @item
9214 Edit some sources to fix bugs.
9215
9216 @item
9217 Add enhancements.
9218
9219 @item
9220 Compile all sources affected.
9221
9222 @item
9223 Rebind and relink.
9224
9225 @item
9226 Test.
9227 @end enumerate
9228
9229 @noindent
9230 The third step can be tricky, because not only do the modified files
9231 @cindex Dependency rules
9232 have to be compiled, but any files depending on these files must also be
9233 recompiled. The dependency rules in Ada can be quite complex, especially
9234 in the presence of overloading, @code{use} clauses, generics and inlined
9235 subprograms.
9236
9237 @command{gnatmake} automatically takes care of the third and fourth steps
9238 of this process. It determines which sources need to be compiled,
9239 compiles them, and binds and links the resulting object files.
9240
9241 Unlike some other Ada make programs, the dependencies are always
9242 accurately recomputed from the new sources. The source based approach of
9243 the GNAT compilation model makes this possible. This means that if
9244 changes to the source program cause corresponding changes in
9245 dependencies, they will always be tracked exactly correctly by
9246 @command{gnatmake}.
9247
9248 @node Running gnatmake
9249 @section Running @command{gnatmake}
9250
9251 @noindent
9252 The usual form of the @command{gnatmake} command is
9253
9254 @smallexample
9255 @c $ gnatmake @ovar{switches} @var{file_name}
9256 @c       @ovar{file_names} @ovar{mode_switches}
9257 @c Expanding @ovar macro inline (explanation in macro def comments)
9258 $ gnatmake @r{[}@var{switches}@r{]} @var{file_name}
9259       @r{[}@var{file_names}@r{]} @r{[}@var{mode_switches}@r{]}
9260 @end smallexample
9261
9262 @noindent
9263 The only required argument is one @var{file_name}, which specifies
9264 a compilation unit that is a main program. Several @var{file_names} can be
9265 specified: this will result in several executables being built.
9266 If @code{switches} are present, they can be placed before the first
9267 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
9268 If @var{mode_switches} are present, they must always be placed after
9269 the last @var{file_name} and all @code{switches}.
9270
9271 If you are using standard file extensions (@file{.adb} and @file{.ads}), then the
9272 extension may be omitted from the @var{file_name} arguments. However, if
9273 you are using non-standard extensions, then it is required that the
9274 extension be given. A relative or absolute directory path can be
9275 specified in a @var{file_name}, in which case, the input source file will
9276 be searched for in the specified directory only. Otherwise, the input
9277 source file will first be searched in the directory where
9278 @command{gnatmake} was invoked and if it is not found, it will be search on
9279 the source path of the compiler as described in
9280 @ref{Search Paths and the Run-Time Library (RTL)}.
9281
9282 All @command{gnatmake} output (except when you specify
9283 @option{^-M^/DEPENDENCIES_LIST^}) is to
9284 @file{stderr}. The output produced by the
9285 @option{^-M^/DEPENDENCIES_LIST^} switch is send to
9286 @file{stdout}.
9287
9288 @node Switches for gnatmake
9289 @section Switches for @command{gnatmake}
9290
9291 @noindent
9292 You may specify any of the following switches to @command{gnatmake}:
9293
9294 @table @option
9295 @c !sort!
9296
9297 @item --version
9298 @cindex @option{--version} @command{gnatmake}
9299 Display Copyright and version, then exit disregarding all other options.
9300
9301 @item --help
9302 @cindex @option{--help} @command{gnatmake}
9303 If @option{--version} was not used, display usage, then exit disregarding
9304 all other options.
9305
9306 @ifclear vms
9307 @item --GCC=@var{compiler_name}
9308 @cindex @option{--GCC=compiler_name} (@command{gnatmake})
9309 Program used for compiling. The default is `@command{gcc}'. You need to use
9310 quotes around @var{compiler_name} if @code{compiler_name} contains
9311 spaces or other separator characters. As an example @option{--GCC="foo -x
9312 -y"} will instruct @command{gnatmake} to use @code{foo -x -y} as your
9313 compiler. A limitation of this syntax is that the name and path name of
9314 the executable itself must not include any embedded spaces. Note that
9315 switch @option{-c} is always inserted after your command name. Thus in the
9316 above example the compiler command that will be used by @command{gnatmake}
9317 will be @code{foo -c -x -y}. If several @option{--GCC=compiler_name} are
9318 used, only the last @var{compiler_name} is taken into account. However,
9319 all the additional switches are also taken into account. Thus,
9320 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9321 @option{--GCC="bar -x -y -z -t"}.
9322
9323 @item --GNATBIND=@var{binder_name}
9324 @cindex @option{--GNATBIND=binder_name} (@command{gnatmake})
9325 Program used for binding. The default is `@code{gnatbind}'. You need to
9326 use quotes around @var{binder_name} if @var{binder_name} contains spaces
9327 or other separator characters. As an example @option{--GNATBIND="bar -x
9328 -y"} will instruct @command{gnatmake} to use @code{bar -x -y} as your
9329 binder. Binder switches that are normally appended by @command{gnatmake}
9330 to `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
9331 A limitation of this syntax is that the name and path name of the executable
9332 itself must not include any embedded spaces.
9333
9334 @item --GNATLINK=@var{linker_name}
9335 @cindex @option{--GNATLINK=linker_name} (@command{gnatmake})
9336 Program used for linking. The default is `@command{gnatlink}'. You need to
9337 use quotes around @var{linker_name} if @var{linker_name} contains spaces
9338 or other separator characters. As an example @option{--GNATLINK="lan -x
9339 -y"} will instruct @command{gnatmake} to use @code{lan -x -y} as your
9340 linker. Linker switches that are normally appended by @command{gnatmake} to
9341 `@command{gnatlink}' are now appended to the end of @code{lan -x -y}.
9342 A limitation of this syntax is that the name and path name of the executable
9343 itself must not include any embedded spaces.
9344
9345 @end ifclear
9346
9347 @item ^--subdirs^/SUBDIRS^=subdir
9348 Actual object directory of each project file is the subdirectory subdir of the
9349 object directory specified or defaulted in the project file.
9350
9351 @item ^--single-compile-per-obj-dir^/SINGLE_COMPILE_PER_OBJ_DIR^
9352 Disallow simultaneous compilations in the same object directory when
9353 project files are used.
9354
9355 @item ^--unchecked-shared-lib-imports^/UNCHECKED_SHARED_LIB_IMPORTS^
9356 By default, shared library projects are not allowed to import static library
9357 projects. When this switch is used on the command line, this restriction is
9358 relaxed.
9359
9360 @item ^--source-info=<source info file>^/SRC_INFO=source-info-file^
9361 Specify a source info file. This switch is active only when project files
9362 are used. If the source info file is specified as a relative path, then it is
9363 relative to the object directory of the main project. If the source info file
9364 does not exist, then after the Project Manager has successfully parsed and
9365 processed the project files and found the sources, it creates the source info
9366 file. If the source info file already exists and can be read successfully,
9367 then the Project Manager will get all the needed information about the sources
9368 from the source info file and will not look for them. This reduces the time
9369 to process the project files, especially when looking for sources that take a
9370 long time. If the source info file exists but cannot be parsed successfully,
9371 the Project Manager will attempt to recreate it. If the Project Manager fails
9372 to create the source info file, a message is issued, but gnatmake does not
9373 fail.
9374
9375 @ifclear vms
9376 @item --create-map-file
9377 When linking an executable, create a map file. The name of the map file
9378 has the same name as the executable with extension ".map".
9379
9380 @item --create-map-file=mapfile
9381 When linking an executable, create a map file. The name of the map file is
9382 "mapfile".
9383
9384 @end ifclear
9385
9386 @item ^-a^/ALL_FILES^
9387 @cindex @option{^-a^/ALL_FILES^} (@command{gnatmake})
9388 Consider all files in the make process, even the GNAT internal system
9389 files (for example, the predefined Ada library files), as well as any
9390 locked files. Locked files are files whose ALI file is write-protected.
9391 By default,
9392 @command{gnatmake} does not check these files,
9393 because the assumption is that the GNAT internal files are properly up
9394 to date, and also that any write protected ALI files have been properly
9395 installed. Note that if there is an installation problem, such that one
9396 of these files is not up to date, it will be properly caught by the
9397 binder.
9398 You may have to specify this switch if you are working on GNAT
9399 itself. The switch @option{^-a^/ALL_FILES^} is also useful
9400 in conjunction with @option{^-f^/FORCE_COMPILE^}
9401 if you need to recompile an entire application,
9402 including run-time files, using special configuration pragmas,
9403 such as a @code{Normalize_Scalars} pragma.
9404
9405 By default
9406 @code{gnatmake ^-a^/ALL_FILES^} compiles all GNAT
9407 internal files with
9408 @ifclear vms
9409 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
9410 @end ifclear
9411 @ifset vms
9412 the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} switch.
9413 @end ifset
9414
9415 @item ^-b^/ACTIONS=BIND^
9416 @cindex @option{^-b^/ACTIONS=BIND^} (@command{gnatmake})
9417 Bind only. Can be combined with @option{^-c^/ACTIONS=COMPILE^} to do
9418 compilation and binding, but no link.
9419 Can be combined with @option{^-l^/ACTIONS=LINK^}
9420 to do binding and linking. When not combined with
9421 @option{^-c^/ACTIONS=COMPILE^}
9422 all the units in the closure of the main program must have been previously
9423 compiled and must be up to date. The root unit specified by @var{file_name}
9424 may be given without extension, with the source extension or, if no GNAT
9425 Project File is specified, with the ALI file extension.
9426
9427 @item ^-c^/ACTIONS=COMPILE^
9428 @cindex @option{^-c^/ACTIONS=COMPILE^} (@command{gnatmake})
9429 Compile only. Do not perform binding, except when @option{^-b^/ACTIONS=BIND^}
9430 is also specified. Do not perform linking, except if both
9431 @option{^-b^/ACTIONS=BIND^} and
9432 @option{^-l^/ACTIONS=LINK^} are also specified.
9433 If the root unit specified by @var{file_name} is not a main unit, this is the
9434 default. Otherwise @command{gnatmake} will attempt binding and linking
9435 unless all objects are up to date and the executable is more recent than
9436 the objects.
9437
9438 @item ^-C^/MAPPING^
9439 @cindex @option{^-C^/MAPPING^} (@command{gnatmake})
9440 Use a temporary mapping file. A mapping file is a way to communicate
9441 to the compiler two mappings: from unit names to file names (without
9442 any directory information) and from file names to path names (with
9443 full directory information). A mapping file can make the compiler's
9444 file searches faster, especially if there are many source directories,
9445 or the sources are read over a slow network connection. If
9446 @option{^-P^/PROJECT_FILE^} is used, a mapping file is always used, so
9447 @option{^-C^/MAPPING^} is unnecessary; in this case the mapping file
9448 is initially populated based on the project file. If
9449 @option{^-C^/MAPPING^} is used without
9450 @option{^-P^/PROJECT_FILE^},
9451 the mapping file is initially empty. Each invocation of the compiler
9452 will add any newly accessed sources to the mapping file.
9453
9454 @item ^-C=^/USE_MAPPING_FILE=^@var{file}
9455 @cindex @option{^-C=^/USE_MAPPING^} (@command{gnatmake})
9456 Use a specific mapping file. The file, specified as a path name (absolute or
9457 relative) by this switch, should already exist, otherwise the switch is
9458 ineffective. The specified mapping file will be communicated to the compiler.
9459 This switch is not compatible with a project file
9460 (^-P^/PROJECT_FILE=^@var{file}) or with multiple compiling processes
9461 (^-j^/PROCESSES=^nnn, when nnn is greater than 1).
9462
9463 @item ^-d^/DISPLAY_PROGRESS^
9464 @cindex @option{^-d^/DISPLAY_PROGRESS^} (@command{gnatmake})
9465 Display progress for each source, up to date or not, as a single line
9466
9467 @smallexample
9468 completed x out of y (zz%)
9469 @end smallexample
9470
9471 If the file needs to be compiled this is displayed after the invocation of
9472 the compiler. These lines are displayed even in quiet output mode.
9473
9474 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
9475 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@command{gnatmake})
9476 Put all object files and ALI file in directory @var{dir}.
9477 If the @option{^-D^/DIRECTORY_OBJECTS^} switch is not used, all object files
9478 and ALI files go in the current working directory.
9479
9480 This switch cannot be used when using a project file.
9481
9482 @ifclear vms
9483 @item -eL
9484 @cindex @option{-eL} (@command{gnatmake})
9485 @cindex symbolic links
9486 Follow all symbolic links when processing project files.
9487 This should be used if your project uses symbolic links for files or
9488 directories, but is not needed in other cases.
9489
9490 @cindex naming scheme
9491 This also assumes that no directory matches the naming scheme for files (for
9492 instance that you do not have a directory called "sources.ads" when using the
9493 default GNAT naming scheme).
9494
9495 When you do not have to use this switch (ie by default), gnatmake is able to
9496 save a lot of system calls (several per source file and object file), which
9497 can result in a significant speed up to load and manipulate a project file,
9498 especially when using source files from a remote system.
9499
9500 @end ifclear
9501
9502 @item ^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^
9503 @cindex @option{^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^} (@command{gnatmake})
9504 Output the commands for the compiler, the binder and the linker
9505 on ^standard output^SYS$OUTPUT^,
9506 instead of ^standard error^SYS$ERROR^.
9507
9508 @item ^-f^/FORCE_COMPILE^
9509 @cindex @option{^-f^/FORCE_COMPILE^} (@command{gnatmake})
9510 Force recompilations. Recompile all sources, even though some object
9511 files may be up to date, but don't recompile predefined or GNAT internal
9512 files or locked files (files with a write-protected ALI file),
9513 unless the @option{^-a^/ALL_FILES^} switch is also specified.
9514
9515 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
9516 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@command{gnatmake})
9517 When using project files, if some errors or warnings are detected during
9518 parsing and verbose mode is not in effect (no use of switch
9519 ^-v^/VERBOSE^), then error lines start with the full path name of the project
9520 file, rather than its simple file name.
9521
9522 @item ^-g^/DEBUG^
9523 @cindex @option{^-g^/DEBUG^} (@command{gnatmake})
9524 Enable debugging. This switch is simply passed to the compiler and to the
9525 linker.
9526
9527 @item ^-i^/IN_PLACE^
9528 @cindex @option{^-i^/IN_PLACE^} (@command{gnatmake})
9529 In normal mode, @command{gnatmake} compiles all object files and ALI files
9530 into the current directory. If the @option{^-i^/IN_PLACE^} switch is used,
9531 then instead object files and ALI files that already exist are overwritten
9532 in place. This means that once a large project is organized into separate
9533 directories in the desired manner, then @command{gnatmake} will automatically
9534 maintain and update this organization. If no ALI files are found on the
9535 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
9536 the new object and ALI files are created in the
9537 directory containing the source being compiled. If another organization
9538 is desired, where objects and sources are kept in different directories,
9539 a useful technique is to create dummy ALI files in the desired directories.
9540 When detecting such a dummy file, @command{gnatmake} will be forced to
9541 recompile the corresponding source file, and it will be put the resulting
9542 object and ALI files in the directory where it found the dummy file.
9543
9544 @item ^-j^/PROCESSES=^@var{n}
9545 @cindex @option{^-j^/PROCESSES^} (@command{gnatmake})
9546 @cindex Parallel make
9547 Use @var{n} processes to carry out the (re)compilations. On a
9548 multiprocessor machine compilations will occur in parallel. In the
9549 event of compilation errors, messages from various compilations might
9550 get interspersed (but @command{gnatmake} will give you the full ordered
9551 list of failing compiles at the end). If this is problematic, rerun
9552 the make process with n set to 1 to get a clean list of messages.
9553
9554 @item ^-k^/CONTINUE_ON_ERROR^
9555 @cindex @option{^-k^/CONTINUE_ON_ERROR^} (@command{gnatmake})
9556 Keep going. Continue as much as possible after a compilation error. To
9557 ease the programmer's task in case of compilation errors, the list of
9558 sources for which the compile fails is given when @command{gnatmake}
9559 terminates.
9560
9561 If @command{gnatmake} is invoked with several @file{file_names} and with this
9562 switch, if there are compilation errors when building an executable,
9563 @command{gnatmake} will not attempt to build the following executables.
9564
9565 @item ^-l^/ACTIONS=LINK^
9566 @cindex @option{^-l^/ACTIONS=LINK^} (@command{gnatmake})
9567 Link only. Can be combined with @option{^-b^/ACTIONS=BIND^} to binding
9568 and linking. Linking will not be performed if combined with
9569 @option{^-c^/ACTIONS=COMPILE^}
9570 but not with @option{^-b^/ACTIONS=BIND^}.
9571 When not combined with @option{^-b^/ACTIONS=BIND^}
9572 all the units in the closure of the main program must have been previously
9573 compiled and must be up to date, and the main program needs to have been bound.
9574 The root unit specified by @var{file_name}
9575 may be given without extension, with the source extension or, if no GNAT
9576 Project File is specified, with the ALI file extension.
9577
9578 @item ^-m^/MINIMAL_RECOMPILATION^
9579 @cindex @option{^-m^/MINIMAL_RECOMPILATION^} (@command{gnatmake})
9580 Specify that the minimum necessary amount of recompilations
9581 be performed. In this mode @command{gnatmake} ignores time
9582 stamp differences when the only
9583 modifications to a source file consist in adding/removing comments,
9584 empty lines, spaces or tabs. This means that if you have changed the
9585 comments in a source file or have simply reformatted it, using this
9586 switch will tell @command{gnatmake} not to recompile files that depend on it
9587 (provided other sources on which these files depend have undergone no
9588 semantic modifications). Note that the debugging information may be
9589 out of date with respect to the sources if the @option{-m} switch causes
9590 a compilation to be switched, so the use of this switch represents a
9591 trade-off between compilation time and accurate debugging information.
9592
9593 @item ^-M^/DEPENDENCIES_LIST^
9594 @cindex Dependencies, producing list
9595 @cindex @option{^-M^/DEPENDENCIES_LIST^} (@command{gnatmake})
9596 Check if all objects are up to date. If they are, output the object
9597 dependences to @file{stdout} in a form that can be directly exploited in
9598 a @file{Makefile}. By default, each source file is prefixed with its
9599 (relative or absolute) directory name. This name is whatever you
9600 specified in the various @option{^-aI^/SOURCE_SEARCH^}
9601 and @option{^-I^/SEARCH^} switches. If you use
9602 @code{gnatmake ^-M^/DEPENDENCIES_LIST^}
9603 @option{^-q^/QUIET^}
9604 (see below), only the source file names,
9605 without relative paths, are output. If you just specify the
9606 @option{^-M^/DEPENDENCIES_LIST^}
9607 switch, dependencies of the GNAT internal system files are omitted. This
9608 is typically what you want. If you also specify
9609 the @option{^-a^/ALL_FILES^} switch,
9610 dependencies of the GNAT internal files are also listed. Note that
9611 dependencies of the objects in external Ada libraries (see switch
9612 @option{^-aL^/SKIP_MISSING=^}@var{dir} in the following list)
9613 are never reported.
9614
9615 @item ^-n^/DO_OBJECT_CHECK^
9616 @cindex @option{^-n^/DO_OBJECT_CHECK^} (@command{gnatmake})
9617 Don't compile, bind, or link. Checks if all objects are up to date.
9618 If they are not, the full name of the first file that needs to be
9619 recompiled is printed.
9620 Repeated use of this option, followed by compiling the indicated source
9621 file, will eventually result in recompiling all required units.
9622
9623 @item ^-o ^/EXECUTABLE=^@var{exec_name}
9624 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatmake})
9625 Output executable name. The name of the final executable program will be
9626 @var{exec_name}. If the @option{^-o^/EXECUTABLE^} switch is omitted the default
9627 name for the executable will be the name of the input file in appropriate form
9628 for an executable file on the host system.
9629
9630 This switch cannot be used when invoking @command{gnatmake} with several
9631 @file{file_names}.
9632
9633 @item ^-p or --create-missing-dirs^/CREATE_MISSING_DIRS^
9634 @cindex @option{^-p^/CREATE_MISSING_DIRS^} (@command{gnatmake})
9635 When using project files (^-P^/PROJECT_FILE=^@var{project}), create
9636 automatically missing object directories, library directories and exec
9637 directories.
9638
9639 @item ^-P^/PROJECT_FILE=^@var{project}
9640 @cindex @option{^-P^/PROJECT_FILE^} (@command{gnatmake})
9641 Use project file @var{project}. Only one such switch can be used.
9642 @xref{gnatmake and Project Files}.
9643
9644 @item ^-q^/QUIET^
9645 @cindex @option{^-q^/QUIET^} (@command{gnatmake})
9646 Quiet. When this flag is not set, the commands carried out by
9647 @command{gnatmake} are displayed.
9648
9649 @item ^-s^/SWITCH_CHECK/^
9650 @cindex @option{^-s^/SWITCH_CHECK^} (@command{gnatmake})
9651 Recompile if compiler switches have changed since last compilation.
9652 All compiler switches but -I and -o are taken into account in the
9653 following way:
9654 orders between different ``first letter'' switches are ignored, but
9655 orders between same switches are taken into account. For example,
9656 @option{-O -O2} is different than @option{-O2 -O}, but @option{-g -O}
9657 is equivalent to @option{-O -g}.
9658
9659 This switch is recommended when Integrated Preprocessing is used.
9660
9661 @item ^-u^/UNIQUE^
9662 @cindex @option{^-u^/UNIQUE^} (@command{gnatmake})
9663 Unique. Recompile at most the main files. It implies -c. Combined with
9664 -f, it is equivalent to calling the compiler directly. Note that using
9665 ^-u^/UNIQUE^ with a project file and no main has a special meaning
9666 (@pxref{Project Files and Main Subprograms}).
9667
9668 @item ^-U^/ALL_PROJECTS^
9669 @cindex @option{^-U^/ALL_PROJECTS^} (@command{gnatmake})
9670 When used without a project file or with one or several mains on the command
9671 line, is equivalent to ^-u^/UNIQUE^. When used with a project file and no main
9672 on the command line, all sources of all project files are checked and compiled
9673 if not up to date, and libraries are rebuilt, if necessary.
9674
9675 @item ^-v^/REASONS^
9676 @cindex @option{^-v^/REASONS^} (@command{gnatmake})
9677 Verbose. Display the reason for all recompilations @command{gnatmake}
9678 decides are necessary, with the highest verbosity level.
9679
9680 @item ^-vl^/LOW_VERBOSITY^
9681 @cindex @option{^-vl^/LOW_VERBOSITY^} (@command{gnatmake})
9682 Verbosity level Low. Display fewer lines than in verbosity Medium.
9683
9684 @item ^-vm^/MEDIUM_VERBOSITY^
9685 @cindex @option{^-vm^/MEDIUM_VERBOSITY^} (@command{gnatmake})
9686 Verbosity level Medium. Potentially display fewer lines than in verbosity High.
9687
9688 @item ^-vh^/HIGH_VERBOSITY^
9689 @cindex @option{^-vm^/HIGH_VERBOSITY^} (@command{gnatmake})
9690 Verbosity level High. Equivalent to ^-v^/REASONS^.
9691
9692 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
9693 Indicate the verbosity of the parsing of GNAT project files.
9694 @xref{Switches Related to Project Files}.
9695
9696 @item ^-x^/NON_PROJECT_UNIT_COMPILATION^
9697 @cindex @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} (@command{gnatmake})
9698 Indicate that sources that are not part of any Project File may be compiled.
9699 Normally, when using Project Files, only sources that are part of a Project
9700 File may be compile. When this switch is used, a source outside of all Project
9701 Files may be compiled. The ALI file and the object file will be put in the
9702 object directory of the main Project. The compilation switches used will only
9703 be those specified on the command line. Even when
9704 @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} is used, mains specified on the
9705 command line need to be sources of a project file.
9706
9707 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
9708 Indicate that external variable @var{name} has the value @var{value}.
9709 The Project Manager will use this value for occurrences of
9710 @code{external(name)} when parsing the project file.
9711 @xref{Switches Related to Project Files}.
9712
9713 @item ^-z^/NOMAIN^
9714 @cindex @option{^-z^/NOMAIN^} (@command{gnatmake})
9715 No main subprogram. Bind and link the program even if the unit name
9716 given on the command line is a package name. The resulting executable
9717 will execute the elaboration routines of the package and its closure,
9718 then the finalization routines.
9719
9720 @end table
9721
9722 @table @asis
9723 @item @command{gcc} @asis{switches}
9724 @ifclear vms
9725 Any uppercase or multi-character switch that is not a @command{gnatmake} switch
9726 is passed to @command{gcc} (e.g.@: @option{-O}, @option{-gnato,} etc.)
9727 @end ifclear
9728 @ifset vms
9729 Any qualifier that cannot be recognized as a qualifier for @code{GNAT MAKE}
9730 but is recognizable as a valid qualifier for @code{GNAT COMPILE} is
9731 automatically treated as a compiler switch, and passed on to all
9732 compilations that are carried out.
9733 @end ifset
9734 @end table
9735
9736 @noindent
9737 Source and library search path switches:
9738
9739 @table @option
9740 @c !sort!
9741 @item ^-aI^/SOURCE_SEARCH=^@var{dir}
9742 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatmake})
9743 When looking for source files also look in directory @var{dir}.
9744 The order in which source files search is undertaken is
9745 described in @ref{Search Paths and the Run-Time Library (RTL)}.
9746
9747 @item ^-aL^/SKIP_MISSING=^@var{dir}
9748 @cindex @option{^-aL^/SKIP_MISSING^} (@command{gnatmake})
9749 Consider @var{dir} as being an externally provided Ada library.
9750 Instructs @command{gnatmake} to skip compilation units whose @file{.ALI}
9751 files have been located in directory @var{dir}. This allows you to have
9752 missing bodies for the units in @var{dir} and to ignore out of date bodies
9753 for the same units. You still need to specify
9754 the location of the specs for these units by using the switches
9755 @option{^-aI^/SOURCE_SEARCH=^@var{dir}}
9756 or @option{^-I^/SEARCH=^@var{dir}}.
9757 Note: this switch is provided for compatibility with previous versions
9758 of @command{gnatmake}. The easier method of causing standard libraries
9759 to be excluded from consideration is to write-protect the corresponding
9760 ALI files.
9761
9762 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
9763 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatmake})
9764 When searching for library and object files, look in directory
9765 @var{dir}. The order in which library files are searched is described in
9766 @ref{Search Paths for gnatbind}.
9767
9768 @item ^-A^/CONDITIONAL_SOURCE_SEARCH=^@var{dir}
9769 @cindex Search paths, for @command{gnatmake}
9770 @cindex @option{^-A^/CONDITIONAL_SOURCE_SEARCH^} (@command{gnatmake})
9771 Equivalent to @option{^-aL^/SKIP_MISSING=^@var{dir}
9772 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9773
9774 @item ^-I^/SEARCH=^@var{dir}
9775 @cindex @option{^-I^/SEARCH^} (@command{gnatmake})
9776 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}
9777 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9778
9779 @item ^-I-^/NOCURRENT_DIRECTORY^
9780 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatmake})
9781 @cindex Source files, suppressing search
9782 Do not look for source files in the directory containing the source
9783 file named in the command line.
9784 Do not look for ALI or object files in the directory
9785 where @command{gnatmake} was invoked.
9786
9787 @item ^-L^/LIBRARY_SEARCH=^@var{dir}
9788 @cindex @option{^-L^/LIBRARY_SEARCH^} (@command{gnatmake})
9789 @cindex Linker libraries
9790 Add directory @var{dir} to the list of directories in which the linker
9791 will search for libraries. This is equivalent to
9792 @option{-largs ^-L^/LIBRARY_SEARCH=^}@var{dir}.
9793 @ifclear vms
9794 Furthermore, under Windows, the sources pointed to by the libraries path
9795 set in the registry are not searched for.
9796 @end ifclear
9797
9798 @item -nostdinc
9799 @cindex @option{-nostdinc} (@command{gnatmake})
9800 Do not look for source files in the system default directory.
9801
9802 @item -nostdlib
9803 @cindex @option{-nostdlib} (@command{gnatmake})
9804 Do not look for library files in the system default directory.
9805
9806 @item --RTS=@var{rts-path}
9807 @cindex @option{--RTS} (@command{gnatmake})
9808 Specifies the default location of the runtime library. GNAT looks for the
9809 runtime
9810 in the following directories, and stops as soon as a valid runtime is found
9811 (@file{adainclude} or @file{ada_source_path}, and @file{adalib} or
9812 @file{ada_object_path} present):
9813
9814 @itemize @bullet
9815 @item <current directory>/$rts_path
9816
9817 @item <default-search-dir>/$rts_path
9818
9819 @item <default-search-dir>/rts-$rts_path
9820 @end itemize
9821
9822 @noindent
9823 The selected path is handled like a normal RTS path.
9824
9825 @end table
9826
9827 @node Mode Switches for gnatmake
9828 @section Mode Switches for @command{gnatmake}
9829
9830 @noindent
9831 The mode switches (referred to as @code{mode_switches}) allow the
9832 inclusion of switches that are to be passed to the compiler itself, the
9833 binder or the linker. The effect of a mode switch is to cause all
9834 subsequent switches up to the end of the switch list, or up to the next
9835 mode switch, to be interpreted as switches to be passed on to the
9836 designated component of GNAT.
9837
9838 @table @option
9839 @c !sort!
9840 @item -cargs @var{switches}
9841 @cindex @option{-cargs} (@command{gnatmake})
9842 Compiler switches. Here @var{switches} is a list of switches
9843 that are valid switches for @command{gcc}. They will be passed on to
9844 all compile steps performed by @command{gnatmake}.
9845
9846 @item -bargs @var{switches}
9847 @cindex @option{-bargs} (@command{gnatmake})
9848 Binder switches. Here @var{switches} is a list of switches
9849 that are valid switches for @code{gnatbind}. They will be passed on to
9850 all bind steps performed by @command{gnatmake}.
9851
9852 @item -largs @var{switches}
9853 @cindex @option{-largs} (@command{gnatmake})
9854 Linker switches. Here @var{switches} is a list of switches
9855 that are valid switches for @command{gnatlink}. They will be passed on to
9856 all link steps performed by @command{gnatmake}.
9857
9858 @item -margs @var{switches}
9859 @cindex @option{-margs} (@command{gnatmake})
9860 Make switches. The switches are directly interpreted by @command{gnatmake},
9861 regardless of any previous occurrence of @option{-cargs}, @option{-bargs}
9862 or @option{-largs}.
9863 @end table
9864
9865 @node Notes on the Command Line
9866 @section Notes on the Command Line
9867
9868 @noindent
9869 This section contains some additional useful notes on the operation
9870 of the @command{gnatmake} command.
9871
9872 @itemize @bullet
9873 @item
9874 @cindex Recompilation, by @command{gnatmake}
9875 If @command{gnatmake} finds no ALI files, it recompiles the main program
9876 and all other units required by the main program.
9877 This means that @command{gnatmake}
9878 can be used for the initial compile, as well as during subsequent steps of
9879 the development cycle.
9880
9881 @item
9882 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
9883 is a subunit or body of a generic unit, @command{gnatmake} recompiles
9884 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
9885 warning.
9886
9887 @item
9888 In @command{gnatmake} the switch @option{^-I^/SEARCH^}
9889 is used to specify both source and
9890 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
9891 instead if you just want to specify
9892 source paths only and @option{^-aO^/OBJECT_SEARCH^}
9893 if you want to specify library paths
9894 only.
9895
9896 @item
9897 @command{gnatmake} will ignore any files whose ALI file is write-protected.
9898 This may conveniently be used to exclude standard libraries from
9899 consideration and in particular it means that the use of the
9900 @option{^-f^/FORCE_COMPILE^} switch will not recompile these files
9901 unless @option{^-a^/ALL_FILES^} is also specified.
9902
9903 @item
9904 @command{gnatmake} has been designed to make the use of Ada libraries
9905 particularly convenient. Assume you have an Ada library organized
9906 as follows: @i{^obj-dir^[OBJ_DIR]^} contains the objects and ALI files for
9907 of your Ada compilation units,
9908 whereas @i{^include-dir^[INCLUDE_DIR]^} contains the
9909 specs of these units, but no bodies. Then to compile a unit
9910 stored in @code{main.adb}, which uses this Ada library you would just type
9911
9912 @smallexample
9913 @ifclear vms
9914 $ gnatmake -aI@var{include-dir}  -aL@var{obj-dir}  main
9915 @end ifclear
9916 @ifset vms
9917 $ gnatmake /SOURCE_SEARCH=@i{[INCLUDE_DIR]}
9918            /SKIP_MISSING=@i{[OBJ_DIR]} main
9919 @end ifset
9920 @end smallexample
9921
9922 @item
9923 Using @command{gnatmake} along with the
9924 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}
9925 switch provides a mechanism for avoiding unnecessary recompilations. Using
9926 this switch,
9927 you can update the comments/format of your
9928 source files without having to recompile everything. Note, however, that
9929 adding or deleting lines in a source files may render its debugging
9930 info obsolete. If the file in question is a spec, the impact is rather
9931 limited, as that debugging info will only be useful during the
9932 elaboration phase of your program. For bodies the impact can be more
9933 significant. In all events, your debugger will warn you if a source file
9934 is more recent than the corresponding object, and alert you to the fact
9935 that the debugging information may be out of date.
9936 @end itemize
9937
9938 @node How gnatmake Works
9939 @section How @command{gnatmake} Works
9940
9941 @noindent
9942 Generally @command{gnatmake} automatically performs all necessary
9943 recompilations and you don't need to worry about how it works. However,
9944 it may be useful to have some basic understanding of the @command{gnatmake}
9945 approach and in particular to understand how it uses the results of
9946 previous compilations without incorrectly depending on them.
9947
9948 First a definition: an object file is considered @dfn{up to date} if the
9949 corresponding ALI file exists and if all the source files listed in the
9950 dependency section of this ALI file have time stamps matching those in
9951 the ALI file. This means that neither the source file itself nor any
9952 files that it depends on have been modified, and hence there is no need
9953 to recompile this file.
9954
9955 @command{gnatmake} works by first checking if the specified main unit is up
9956 to date. If so, no compilations are required for the main unit. If not,
9957 @command{gnatmake} compiles the main program to build a new ALI file that
9958 reflects the latest sources. Then the ALI file of the main unit is
9959 examined to find all the source files on which the main program depends,
9960 and @command{gnatmake} recursively applies the above procedure on all these
9961 files.
9962
9963 This process ensures that @command{gnatmake} only trusts the dependencies
9964 in an existing ALI file if they are known to be correct. Otherwise it
9965 always recompiles to determine a new, guaranteed accurate set of
9966 dependencies. As a result the program is compiled ``upside down'' from what may
9967 be more familiar as the required order of compilation in some other Ada
9968 systems. In particular, clients are compiled before the units on which
9969 they depend. The ability of GNAT to compile in any order is critical in
9970 allowing an order of compilation to be chosen that guarantees that
9971 @command{gnatmake} will recompute a correct set of new dependencies if
9972 necessary.
9973
9974 When invoking @command{gnatmake} with several @var{file_names}, if a unit is
9975 imported by several of the executables, it will be recompiled at most once.
9976
9977 Note: when using non-standard naming conventions
9978 (@pxref{Using Other File Names}), changing through a configuration pragmas
9979 file the version of a source and invoking @command{gnatmake} to recompile may
9980 have no effect, if the previous version of the source is still accessible
9981 by @command{gnatmake}. It may be necessary to use the switch
9982 ^-f^/FORCE_COMPILE^.
9983
9984 @node Examples of gnatmake Usage
9985 @section Examples of @command{gnatmake} Usage
9986
9987 @table @code
9988 @item gnatmake hello.adb
9989 Compile all files necessary to bind and link the main program
9990 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
9991 resulting object files to generate an executable file @file{^hello^HELLO.EXE^}.
9992
9993 @item gnatmake main1 main2 main3
9994 Compile all files necessary to bind and link the main programs
9995 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
9996 (containing unit @code{Main2}) and @file{main3.adb}
9997 (containing unit @code{Main3}) and bind and link the resulting object files
9998 to generate three executable files @file{^main1^MAIN1.EXE^},
9999 @file{^main2^MAIN2.EXE^}
10000 and @file{^main3^MAIN3.EXE^}.
10001
10002 @ifclear vms
10003 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
10004 @end ifclear
10005
10006 @ifset vms
10007 @item gnatmake Main_Unit /QUIET
10008 /COMPILER_QUALIFIERS /OPTIMIZE=ALL
10009 /BINDER_QUALIFIERS /ORDER_OF_ELABORATION
10010 @end ifset
10011 Compile all files necessary to bind and link the main program unit
10012 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
10013 be done with optimization level 2 and the order of elaboration will be
10014 listed by the binder. @command{gnatmake} will operate in quiet mode, not
10015 displaying commands it is executing.
10016 @end table
10017
10018 @c *************************
10019 @node Improving Performance
10020 @chapter Improving Performance
10021 @cindex Improving performance
10022
10023 @noindent
10024 This chapter presents several topics related to program performance.
10025 It first describes some of the tradeoffs that need to be considered
10026 and some of the techniques for making your program run faster.
10027 It then documents the @command{gnatelim} tool and unused subprogram/data
10028 elimination feature, which can reduce the size of program executables.
10029
10030 Note: to invoke @command{gnatelim} with a project file, use the @code{gnat}
10031 driver (see @ref{The GNAT Driver and Project Files}).
10032
10033 @ifnottex
10034 @menu
10035 * Performance Considerations::
10036 * Text_IO Suggestions::
10037 * Reducing Size of Ada Executables with gnatelim::
10038 * Reducing Size of Executables with unused subprogram/data elimination::
10039 @end menu
10040 @end ifnottex
10041
10042 @c *****************************
10043 @node Performance Considerations
10044 @section Performance Considerations
10045
10046 @noindent
10047 The GNAT system provides a number of options that allow a trade-off
10048 between
10049
10050 @itemize @bullet
10051 @item
10052 performance of the generated code
10053
10054 @item
10055 speed of compilation
10056
10057 @item
10058 minimization of dependences and recompilation
10059
10060 @item
10061 the degree of run-time checking.
10062 @end itemize
10063
10064 @noindent
10065 The defaults (if no options are selected) aim at improving the speed
10066 of compilation and minimizing dependences, at the expense of performance
10067 of the generated code:
10068
10069 @itemize @bullet
10070 @item
10071 no optimization
10072
10073 @item
10074 no inlining of subprogram calls
10075
10076 @item
10077 all run-time checks enabled except overflow and elaboration checks
10078 @end itemize
10079
10080 @noindent
10081 These options are suitable for most program development purposes. This
10082 chapter describes how you can modify these choices, and also provides
10083 some guidelines on debugging optimized code.
10084
10085 @menu
10086 * Controlling Run-Time Checks::
10087 * Use of Restrictions::
10088 * Optimization Levels::
10089 * Debugging Optimized Code::
10090 * Inlining of Subprograms::
10091 * Other Optimization Switches::
10092 * Optimization and Strict Aliasing::
10093
10094 @ifset vms
10095 * Coverage Analysis::
10096 @end ifset
10097 @end menu
10098
10099 @node Controlling Run-Time Checks
10100 @subsection Controlling Run-Time Checks
10101
10102 @noindent
10103 By default, GNAT generates all run-time checks, except integer overflow
10104 checks, stack overflow checks, and checks for access before elaboration on
10105 subprogram calls. The latter are not required in default mode, because all
10106 necessary checking is done at compile time.
10107 @cindex @option{-gnatp} (@command{gcc})
10108 @cindex @option{-gnato} (@command{gcc})
10109 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
10110 be modified. @xref{Run-Time Checks}.
10111
10112 Our experience is that the default is suitable for most development
10113 purposes.
10114
10115 We treat integer overflow specially because these
10116 are quite expensive and in our experience are not as important as other
10117 run-time checks in the development process. Note that division by zero
10118 is not considered an overflow check, and divide by zero checks are
10119 generated where required by default.
10120
10121 Elaboration checks are off by default, and also not needed by default, since
10122 GNAT uses a static elaboration analysis approach that avoids the need for
10123 run-time checking. This manual contains a full chapter discussing the issue
10124 of elaboration checks, and if the default is not satisfactory for your use,
10125 you should read this chapter.
10126
10127 For validity checks, the minimal checks required by the Ada Reference
10128 Manual (for case statements and assignments to array elements) are on
10129 by default. These can be suppressed by use of the @option{-gnatVn} switch.
10130 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
10131 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
10132 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
10133 are also suppressed entirely if @option{-gnatp} is used.
10134
10135 @cindex Overflow checks
10136 @cindex Checks, overflow
10137 @findex Suppress
10138 @findex Unsuppress
10139 @cindex pragma Suppress
10140 @cindex pragma Unsuppress
10141 Note that the setting of the switches controls the default setting of
10142 the checks. They may be modified using either @code{pragma Suppress} (to
10143 remove checks) or @code{pragma Unsuppress} (to add back suppressed
10144 checks) in the program source.
10145
10146 @node Use of Restrictions
10147 @subsection Use of Restrictions
10148
10149 @noindent
10150 The use of pragma Restrictions allows you to control which features are
10151 permitted in your program. Apart from the obvious point that if you avoid
10152 relatively expensive features like finalization (enforceable by the use
10153 of pragma Restrictions (No_Finalization), the use of this pragma does not
10154 affect the generated code in most cases.
10155
10156 One notable exception to this rule is that the possibility of task abort
10157 results in some distributed overhead, particularly if finalization or
10158 exception handlers are used. The reason is that certain sections of code
10159 have to be marked as non-abortable.
10160
10161 If you use neither the @code{abort} statement, nor asynchronous transfer
10162 of control (@code{select @dots{} then abort}), then this distributed overhead
10163 is removed, which may have a general positive effect in improving
10164 overall performance.  Especially code involving frequent use of tasking
10165 constructs and controlled types will show much improved performance.
10166 The relevant restrictions pragmas are
10167
10168 @smallexample @c ada
10169    pragma Restrictions (No_Abort_Statements);
10170    pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
10171 @end smallexample
10172
10173 @noindent
10174 It is recommended that these restriction pragmas be used if possible. Note
10175 that this also means that you can write code without worrying about the
10176 possibility of an immediate abort at any point.
10177
10178 @node Optimization Levels
10179 @subsection Optimization Levels
10180 @cindex @option{^-O^/OPTIMIZE^} (@command{gcc})
10181
10182 @noindent
10183 Without any optimization ^option,^qualifier,^
10184 the compiler's goal is to reduce the cost of
10185 compilation and to make debugging produce the expected results.
10186 Statements are independent: if you stop the program with a breakpoint between
10187 statements, you can then assign a new value to any variable or change
10188 the program counter to any other statement in the subprogram and get exactly
10189 the results you would expect from the source code.
10190
10191 Turning on optimization makes the compiler attempt to improve the
10192 performance and/or code size at the expense of compilation time and
10193 possibly the ability to debug the program.
10194
10195 If you use multiple
10196 ^-O options, with or without level numbers,^/OPTIMIZE qualifiers,^
10197 the last such option is the one that is effective.
10198
10199 @noindent
10200 The default is optimization off. This results in the fastest compile
10201 times, but GNAT makes absolutely no attempt to optimize, and the
10202 generated programs are considerably larger and slower than when
10203 optimization is enabled. You can use the
10204 @ifclear vms
10205 @option{-O} switch (the permitted forms are @option{-O0}, @option{-O1}
10206 @option{-O2}, @option{-O3}, and @option{-Os})
10207 @end ifclear
10208 @ifset vms
10209 @code{OPTIMIZE} qualifier
10210 @end ifset
10211 to @command{gcc} to control the optimization level:
10212
10213 @table @option
10214 @item ^-O0^/OPTIMIZE=NONE^
10215 No optimization (the default);
10216 generates unoptimized code but has
10217 the fastest compilation time.
10218
10219 Note that many other compilers do fairly extensive optimization
10220 even if ``no optimization'' is specified. With gcc, it is
10221 very unusual to use ^-O0^/OPTIMIZE=NONE^ for production if
10222 execution time is of any concern, since ^-O0^/OPTIMIZE=NONE^
10223 really does mean no optimization at all. This difference between
10224 gcc and other compilers should be kept in mind when doing
10225 performance comparisons.
10226
10227 @item ^-O1^/OPTIMIZE=SOME^
10228 Moderate optimization;
10229 optimizes reasonably well but does not
10230 degrade compilation time significantly.
10231
10232 @item ^-O2^/OPTIMIZE=ALL^
10233 @ifset vms
10234 @itemx /OPTIMIZE=DEVELOPMENT
10235 @end ifset
10236 Full optimization;
10237 generates highly optimized code and has
10238 the slowest compilation time.
10239
10240 @item ^-O3^/OPTIMIZE=INLINING^
10241 Full optimization as in @option{-O2};
10242 also uses more aggressive automatic inlining of subprograms within a unit
10243 (@pxref{Inlining of Subprograms}) and attemps to vectorize loops.
10244
10245 @item ^-Os^/OPTIMIZE=SPACE^
10246 Optimize space usage (code and data) of resulting program.
10247 @end table
10248
10249 @noindent
10250 Higher optimization levels perform more global transformations on the
10251 program and apply more expensive analysis algorithms in order to generate
10252 faster and more compact code. The price in compilation time, and the
10253 resulting improvement in execution time,
10254 both depend on the particular application and the hardware environment.
10255 You should experiment to find the best level for your application.
10256
10257 Since the precise set of optimizations done at each level will vary from
10258 release to release (and sometime from target to target), it is best to think
10259 of the optimization settings in general terms.
10260 @xref{Optimize Options,, Options That Control Optimization, gcc, Using
10261 the GNU Compiler Collection (GCC)}, for details about
10262 ^the @option{-O} settings and a number of @option{-f} options that^how to^
10263 individually enable or disable specific optimizations.
10264
10265 Unlike some other compilation systems, ^@command{gcc}^GNAT^ has
10266 been tested extensively at all optimization levels. There are some bugs
10267 which appear only with optimization turned on, but there have also been
10268 bugs which show up only in @emph{unoptimized} code. Selecting a lower
10269 level of optimization does not improve the reliability of the code
10270 generator, which in practice is highly reliable at all optimization
10271 levels.
10272
10273 Note regarding the use of @option{-O3}: The use of this optimization level
10274 is generally discouraged with GNAT, since it often results in larger
10275 executables which may run more slowly. See further discussion of this point
10276 in @ref{Inlining of Subprograms}.
10277
10278 @node Debugging Optimized Code
10279 @subsection Debugging Optimized Code
10280 @cindex Debugging optimized code
10281 @cindex Optimization and debugging
10282
10283 @noindent
10284 Although it is possible to do a reasonable amount of debugging at
10285 @ifclear vms
10286 nonzero optimization levels,
10287 the higher the level the more likely that
10288 @end ifclear
10289 @ifset vms
10290 @option{/OPTIMIZE} settings other than @code{NONE},
10291 such settings will make it more likely that
10292 @end ifset
10293 source-level constructs will have been eliminated by optimization.
10294 For example, if a loop is strength-reduced, the loop
10295 control variable may be completely eliminated and thus cannot be
10296 displayed in the debugger.
10297 This can only happen at @option{-O2} or @option{-O3}.
10298 Explicit temporary variables that you code might be eliminated at
10299 ^level^setting^ @option{-O1} or higher.
10300
10301 The use of the @option{^-g^/DEBUG^} switch,
10302 @cindex @option{^-g^/DEBUG^} (@command{gcc})
10303 which is needed for source-level debugging,
10304 affects the size of the program executable on disk,
10305 and indeed the debugging information can be quite large.
10306 However, it has no effect on the generated code (and thus does not
10307 degrade performance)
10308
10309 Since the compiler generates debugging tables for a compilation unit before
10310 it performs optimizations, the optimizing transformations may invalidate some
10311 of the debugging data.  You therefore need to anticipate certain
10312 anomalous situations that may arise while debugging optimized code.
10313 These are the most common cases:
10314
10315 @enumerate
10316 @item
10317 @i{The ``hopping Program Counter'':}  Repeated @code{step} or @code{next}
10318 commands show
10319 the PC bouncing back and forth in the code.  This may result from any of
10320 the following optimizations:
10321
10322 @itemize @bullet
10323 @item
10324 @i{Common subexpression elimination:} using a single instance of code for a
10325 quantity that the source computes several times.  As a result you
10326 may not be able to stop on what looks like a statement.
10327
10328 @item
10329 @i{Invariant code motion:} moving an expression that does not change within a
10330 loop, to the beginning of the loop.
10331
10332 @item
10333 @i{Instruction scheduling:} moving instructions so as to
10334 overlap loads and stores (typically) with other code, or in
10335 general to move computations of values closer to their uses. Often
10336 this causes you to pass an assignment statement without the assignment
10337 happening and then later bounce back to the statement when the
10338 value is actually needed.  Placing a breakpoint on a line of code
10339 and then stepping over it may, therefore, not always cause all the
10340 expected side-effects.
10341 @end itemize
10342
10343 @item
10344 @i{The ``big leap'':} More commonly known as @emph{cross-jumping}, in which
10345 two identical pieces of code are merged and the program counter suddenly
10346 jumps to a statement that is not supposed to be executed, simply because
10347 it (and the code following) translates to the same thing as the code
10348 that @emph{was} supposed to be executed.  This effect is typically seen in
10349 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
10350 a @code{break} in a C @code{^switch^switch^} statement.
10351
10352 @item
10353 @i{The ``roving variable'':} The symptom is an unexpected value in a variable.
10354 There are various reasons for this effect:
10355
10356 @itemize @bullet
10357 @item
10358 In a subprogram prologue, a parameter may not yet have been moved to its
10359 ``home''.
10360
10361 @item
10362 A variable may be dead, and its register re-used.  This is
10363 probably the most common cause.
10364
10365 @item
10366 As mentioned above, the assignment of a value to a variable may
10367 have been moved.
10368
10369 @item
10370 A variable may be eliminated entirely by value propagation or
10371 other means.  In this case, GCC may incorrectly generate debugging
10372 information for the variable
10373 @end itemize
10374
10375 @noindent
10376 In general, when an unexpected value appears for a local variable or parameter
10377 you should first ascertain if that value was actually computed by
10378 your program, as opposed to being incorrectly reported by the debugger.
10379 Record fields or
10380 array elements in an object designated by an access value
10381 are generally less of a problem, once you have ascertained that the access
10382 value is sensible.
10383 Typically, this means checking variables in the preceding code and in the
10384 calling subprogram to verify that the value observed is explainable from other
10385 values (one must apply the procedure recursively to those
10386 other values); or re-running the code and stopping a little earlier
10387 (perhaps before the call) and stepping to better see how the variable obtained
10388 the value in question; or continuing to step @emph{from} the point of the
10389 strange value to see if code motion had simply moved the variable's
10390 assignments later.
10391 @end enumerate
10392
10393 @noindent
10394 In light of such anomalies, a recommended technique is to use @option{-O0}
10395 early in the software development cycle, when extensive debugging capabilities
10396 are most needed, and then move to @option{-O1} and later @option{-O2} as
10397 the debugger becomes less critical.
10398 Whether to use the @option{^-g^/DEBUG^} switch in the release version is
10399 a release management issue.
10400 @ifclear vms
10401 Note that if you use @option{-g} you can then use the @command{strip} program
10402 on the resulting executable,
10403 which removes both debugging information and global symbols.
10404 @end ifclear
10405
10406 @node Inlining of Subprograms
10407 @subsection Inlining of Subprograms
10408
10409 @noindent
10410 A call to a subprogram in the current unit is inlined if all the
10411 following conditions are met:
10412
10413 @itemize @bullet
10414 @item
10415 The optimization level is at least @option{-O1}.
10416
10417 @item
10418 The called subprogram is suitable for inlining: It must be small enough
10419 and not contain something that @command{gcc} cannot support in inlined
10420 subprograms.
10421
10422 @item
10423 @cindex pragma Inline
10424 @findex Inline
10425 Any one of the following applies: @code{pragma Inline} is applied to the
10426 subprogram and the @option{^-gnatn^/INLINE^} switch is specified; the
10427 subprogram is local to the unit and called once from within it; the
10428 subprogram is small and optimization level @option{-O2} is specified;
10429 optimization level @option{-O3}) is specified.
10430 @end itemize
10431
10432 @noindent
10433 Calls to subprograms in @code{with}'ed units are normally not inlined.
10434 To achieve actual inlining (that is, replacement of the call by the code
10435 in the body of the subprogram), the following conditions must all be true.
10436
10437 @itemize @bullet
10438 @item
10439 The optimization level is at least @option{-O1}.
10440
10441 @item
10442 The called subprogram is suitable for inlining: It must be small enough
10443 and not contain something that @command{gcc} cannot support in inlined
10444 subprograms.
10445
10446 @item
10447 The call appears in a body (not in a package spec).
10448
10449 @item
10450 There is a @code{pragma Inline} for the subprogram.
10451
10452 @item
10453 The @option{^-gnatn^/INLINE^} switch is used on the command line.
10454 @end itemize
10455
10456 Even if all these conditions are met, it may not be possible for
10457 the compiler to inline the call, due to the length of the body,
10458 or features in the body that make it impossible for the compiler
10459 to do the inlining.
10460
10461 Note that specifying the @option{-gnatn} switch causes additional
10462 compilation dependencies. Consider the following:
10463
10464 @smallexample @c ada
10465 @cartouche
10466 package R is
10467    procedure Q;
10468    pragma Inline (Q);
10469 end R;
10470 package body R is
10471    @dots{}
10472 end R;
10473
10474 with R;
10475 procedure Main is
10476 begin
10477    @dots{}
10478    R.Q;
10479 end Main;
10480 @end cartouche
10481 @end smallexample
10482
10483 @noindent
10484 With the default behavior (no @option{-gnatn} switch specified), the
10485 compilation of the @code{Main} procedure depends only on its own source,
10486 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
10487 means that editing the body of @code{R} does not require recompiling
10488 @code{Main}.
10489
10490 On the other hand, the call @code{R.Q} is not inlined under these
10491 circumstances. If the @option{-gnatn} switch is present when @code{Main}
10492 is compiled, the call will be inlined if the body of @code{Q} is small
10493 enough, but now @code{Main} depends on the body of @code{R} in
10494 @file{r.adb} as well as on the spec. This means that if this body is edited,
10495 the main program must be recompiled. Note that this extra dependency
10496 occurs whether or not the call is in fact inlined by @command{gcc}.
10497
10498 The use of front end inlining with @option{-gnatN} generates similar
10499 additional dependencies.
10500
10501 @cindex @option{^-fno-inline^/INLINE=SUPPRESS^} (@command{gcc})
10502 Note: The @option{^-fno-inline^/INLINE=SUPPRESS^} switch
10503 can be used to prevent
10504 all inlining. This switch overrides all other conditions and ensures
10505 that no inlining occurs. The extra dependences resulting from
10506 @option{-gnatn} will still be active, even if
10507 this switch is used to suppress the resulting inlining actions.
10508
10509 @cindex @option{-fno-inline-functions} (@command{gcc})
10510 Note: The @option{-fno-inline-functions} switch can be used to prevent
10511 automatic inlining of subprograms if @option{-O3} is used.
10512
10513 @cindex @option{-fno-inline-small-functions} (@command{gcc})
10514 Note: The @option{-fno-inline-small-functions} switch can be used to prevent
10515 automatic inlining of small subprograms if @option{-O2} is used.
10516
10517 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
10518 Note: The @option{-fno-inline-functions-called-once} switch
10519 can be used to prevent inlining of subprograms local to the unit
10520 and called once from within it if @option{-O1} is used.
10521
10522 Note regarding the use of @option{-O3}: There is no difference in inlining
10523 behavior between @option{-O2} and @option{-O3} for subprograms with an explicit
10524 pragma @code{Inline} assuming the use of @option{-gnatn}
10525 or @option{-gnatN} (the switches that activate inlining). If you have used
10526 pragma @code{Inline} in appropriate cases, then it is usually much better
10527 to use @option{-O2} and @option{-gnatn} and avoid the use of @option{-O3} which
10528 in this case only has the effect of inlining subprograms you did not
10529 think should be inlined. We often find that the use of @option{-O3} slows
10530 down code by performing excessive inlining, leading to increased instruction
10531 cache pressure from the increased code size. So the bottom line here is
10532 that you should not automatically assume that @option{-O3} is better than
10533 @option{-O2}, and indeed you should use @option{-O3} only if tests show that
10534 it actually improves performance.
10535
10536 @node Other Optimization Switches
10537 @subsection Other Optimization Switches
10538 @cindex Optimization Switches
10539
10540 Since @code{GNAT} uses the @command{gcc} back end, all the specialized
10541 @command{gcc} optimization switches are potentially usable. These switches
10542 have not been extensively tested with GNAT but can generally be expected
10543 to work. Examples of switches in this category are
10544 @option{-funroll-loops} and
10545 the various target-specific @option{-m} options (in particular, it has been
10546 observed that @option{-march=pentium4} can significantly improve performance
10547 on appropriate machines). For full details of these switches, see
10548 @ref{Submodel Options,, Hardware Models and Configurations, gcc, Using
10549 the GNU Compiler Collection (GCC)}.
10550
10551 @node Optimization and Strict Aliasing
10552 @subsection Optimization and Strict Aliasing
10553 @cindex Aliasing
10554 @cindex Strict Aliasing
10555 @cindex No_Strict_Aliasing
10556
10557 @noindent
10558 The strong typing capabilities of Ada allow an optimizer to generate
10559 efficient code in situations where other languages would be forced to
10560 make worst case assumptions preventing such optimizations. Consider
10561 the following example:
10562
10563 @smallexample @c ada
10564 @cartouche
10565 procedure R is
10566    type Int1 is new Integer;
10567    type Int2 is new Integer;
10568    type Int1A is access Int1;
10569    type Int2A is access Int2;
10570    Int1V : Int1A;
10571    Int2V : Int2A;
10572    @dots{}
10573
10574 begin
10575    @dots{}
10576    for J in Data'Range loop
10577       if Data (J) = Int1V.all then
10578          Int2V.all := Int2V.all + 1;
10579       end if;
10580    end loop;
10581    @dots{}
10582 end R;
10583 @end cartouche
10584 @end smallexample
10585
10586 @noindent
10587 In this example, since the variable @code{Int1V} can only access objects
10588 of type @code{Int1}, and @code{Int2V} can only access objects of type
10589 @code{Int2}, there is no possibility that the assignment to
10590 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
10591 the compiler optimizer can "know" that the value @code{Int1V.all} is constant
10592 for all iterations of the loop and avoid the extra memory reference
10593 required to dereference it each time through the loop.
10594
10595 This kind of optimization, called strict aliasing analysis, is
10596 triggered by specifying an optimization level of @option{-O2} or
10597 higher or @option{-Os} and allows @code{GNAT} to generate more efficient code
10598 when access values are involved.
10599
10600 However, although this optimization is always correct in terms of
10601 the formal semantics of the Ada Reference Manual, difficulties can
10602 arise if features like @code{Unchecked_Conversion} are used to break
10603 the typing system. Consider the following complete program example:
10604
10605 @smallexample @c ada
10606 @cartouche
10607 package p1 is
10608    type int1 is new integer;
10609    type int2 is new integer;
10610    type a1 is access int1;
10611    type a2 is access int2;
10612 end p1;
10613
10614 with p1; use p1;
10615 package p2 is
10616    function to_a2 (Input : a1) return a2;
10617 end p2;
10618
10619 with Unchecked_Conversion;
10620 package body p2 is
10621    function to_a2 (Input : a1) return a2 is
10622       function to_a2u is
10623         new Unchecked_Conversion (a1, a2);
10624    begin
10625       return to_a2u (Input);
10626    end to_a2;
10627 end p2;
10628
10629 with p2; use p2;
10630 with p1; use p1;
10631 with Text_IO; use Text_IO;
10632 procedure m is
10633    v1 : a1 := new int1;
10634    v2 : a2 := to_a2 (v1);
10635 begin
10636    v1.all := 1;
10637    v2.all := 0;
10638    put_line (int1'image (v1.all));
10639 end;
10640 @end cartouche
10641 @end smallexample
10642
10643 @noindent
10644 This program prints out 0 in @option{-O0} or @option{-O1}
10645 mode, but it prints out 1 in @option{-O2} mode. That's
10646 because in strict aliasing mode, the compiler can and
10647 does assume that the assignment to @code{v2.all} could not
10648 affect the value of @code{v1.all}, since different types
10649 are involved.
10650
10651 This behavior is not a case of non-conformance with the standard, since
10652 the Ada RM specifies that an unchecked conversion where the resulting
10653 bit pattern is not a correct value of the target type can result in an
10654 abnormal value and attempting to reference an abnormal value makes the
10655 execution of a program erroneous.  That's the case here since the result
10656 does not point to an object of type @code{int2}.  This means that the
10657 effect is entirely unpredictable.
10658
10659 However, although that explanation may satisfy a language
10660 lawyer, in practice an applications programmer expects an
10661 unchecked conversion involving pointers to create true
10662 aliases and the behavior of printing 1 seems plain wrong.
10663 In this case, the strict aliasing optimization is unwelcome.
10664
10665 Indeed the compiler recognizes this possibility, and the
10666 unchecked conversion generates a warning:
10667
10668 @smallexample
10669 p2.adb:5:07: warning: possible aliasing problem with type "a2"
10670 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
10671 p2.adb:5:07: warning:  or use "pragma No_Strict_Aliasing (a2);"
10672 @end smallexample
10673
10674 @noindent
10675 Unfortunately the problem is recognized when compiling the body of
10676 package @code{p2}, but the actual "bad" code is generated while
10677 compiling the body of @code{m} and this latter compilation does not see
10678 the suspicious @code{Unchecked_Conversion}.
10679
10680 As implied by the warning message, there are approaches you can use to
10681 avoid the unwanted strict aliasing optimization in a case like this.
10682
10683 One possibility is to simply avoid the use of @option{-O2}, but
10684 that is a bit drastic, since it throws away a number of useful
10685 optimizations that do not involve strict aliasing assumptions.
10686
10687 A less drastic approach is to compile the program using the
10688 option @option{-fno-strict-aliasing}. Actually it is only the
10689 unit containing the dereferencing of the suspicious pointer
10690 that needs to be compiled. So in this case, if we compile
10691 unit @code{m} with this switch, then we get the expected
10692 value of zero printed. Analyzing which units might need
10693 the switch can be painful, so a more reasonable approach
10694 is to compile the entire program with options @option{-O2}
10695 and @option{-fno-strict-aliasing}. If the performance is
10696 satisfactory with this combination of options, then the
10697 advantage is that the entire issue of possible "wrong"
10698 optimization due to strict aliasing is avoided.
10699
10700 To avoid the use of compiler switches, the configuration
10701 pragma @code{No_Strict_Aliasing} with no parameters may be
10702 used to specify that for all access types, the strict
10703 aliasing optimization should be suppressed.
10704
10705 However, these approaches are still overkill, in that they causes
10706 all manipulations of all access values to be deoptimized. A more
10707 refined approach is to concentrate attention on the specific
10708 access type identified as problematic.
10709
10710 First, if a careful analysis of uses of the pointer shows
10711 that there are no possible problematic references, then
10712 the warning can be suppressed by bracketing the
10713 instantiation of @code{Unchecked_Conversion} to turn
10714 the warning off:
10715
10716 @smallexample @c ada
10717    pragma Warnings (Off);
10718    function to_a2u is
10719      new Unchecked_Conversion (a1, a2);
10720    pragma Warnings (On);
10721 @end smallexample
10722
10723 @noindent
10724 Of course that approach is not appropriate for this particular
10725 example, since indeed there is a problematic reference. In this
10726 case we can take one of two other approaches.
10727
10728 The first possibility is to move the instantiation of unchecked
10729 conversion to the unit in which the type is declared. In
10730 this example, we would move the instantiation of
10731 @code{Unchecked_Conversion} from the body of package
10732 @code{p2} to the spec of package @code{p1}. Now the
10733 warning disappears. That's because any use of the
10734 access type knows there is a suspicious unchecked
10735 conversion, and the strict aliasing optimization
10736 is automatically suppressed for the type.
10737
10738 If it is not practical to move the unchecked conversion to the same unit
10739 in which the destination access type is declared (perhaps because the
10740 source type is not visible in that unit), you may use pragma
10741 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
10742 same declarative sequence as the declaration of the access type:
10743
10744 @smallexample @c ada
10745    type a2 is access int2;
10746    pragma No_Strict_Aliasing (a2);
10747 @end smallexample
10748
10749 @noindent
10750 Here again, the compiler now knows that the strict aliasing optimization
10751 should be suppressed for any reference to type @code{a2} and the
10752 expected behavior is obtained.
10753
10754 Finally, note that although the compiler can generate warnings for
10755 simple cases of unchecked conversions, there are tricker and more
10756 indirect ways of creating type incorrect aliases which the compiler
10757 cannot detect. Examples are the use of address overlays and unchecked
10758 conversions involving composite types containing access types as
10759 components. In such cases, no warnings are generated, but there can
10760 still be aliasing problems. One safe coding practice is to forbid the
10761 use of address clauses for type overlaying, and to allow unchecked
10762 conversion only for primitive types. This is not really a significant
10763 restriction since any possible desired effect can be achieved by
10764 unchecked conversion of access values.
10765
10766 The aliasing analysis done in strict aliasing mode can certainly
10767 have significant benefits. We have seen cases of large scale
10768 application code where the time is increased by up to 5% by turning
10769 this optimization off. If you have code that includes significant
10770 usage of unchecked conversion, you might want to just stick with
10771 @option{-O1} and avoid the entire issue. If you get adequate
10772 performance at this level of optimization level, that's probably
10773 the safest approach. If tests show that you really need higher
10774 levels of optimization, then you can experiment with @option{-O2}
10775 and @option{-O2 -fno-strict-aliasing} to see how much effect this
10776 has on size and speed of the code. If you really need to use
10777 @option{-O2} with strict aliasing in effect, then you should
10778 review any uses of unchecked conversion of access types,
10779 particularly if you are getting the warnings described above.
10780
10781 @ifset vms
10782 @node Coverage Analysis
10783 @subsection Coverage Analysis
10784
10785 @noindent
10786 GNAT supports the HP Performance Coverage Analyzer (PCA), which allows
10787 the user to determine the distribution of execution time across a program,
10788 @pxref{Profiling} for details of usage.
10789 @end ifset
10790
10791
10792 @node Text_IO Suggestions
10793 @section @code{Text_IO} Suggestions
10794 @cindex @code{Text_IO} and performance
10795
10796 @noindent
10797 The @code{Ada.Text_IO} package has fairly high overheads due in part to
10798 the requirement of maintaining page and line counts. If performance
10799 is critical, a recommendation is to use @code{Stream_IO} instead of
10800 @code{Text_IO} for volume output, since this package has less overhead.
10801
10802 If @code{Text_IO} must be used, note that by default output to the standard
10803 output and standard error files is unbuffered (this provides better
10804 behavior when output statements are used for debugging, or if the
10805 progress of a program is observed by tracking the output, e.g. by
10806 using the Unix @command{tail -f} command to watch redirected output.
10807
10808 If you are generating large volumes of output with @code{Text_IO} and
10809 performance is an important factor, use a designated file instead
10810 of the standard output file, or change the standard output file to
10811 be buffered using @code{Interfaces.C_Streams.setvbuf}.
10812
10813
10814
10815 @node Reducing Size of Ada Executables with gnatelim
10816 @section Reducing Size of Ada Executables with @code{gnatelim}
10817 @findex gnatelim
10818
10819 @noindent
10820 This section describes @command{gnatelim}, a tool which detects unused
10821 subprograms and helps the compiler to create a smaller executable for your
10822 program.
10823
10824 @menu
10825 * About gnatelim::
10826 * Running gnatelim::
10827 * Processing Precompiled Libraries::
10828 * Correcting the List of Eliminate Pragmas::
10829 * Making Your Executables Smaller::
10830 * Summary of the gnatelim Usage Cycle::
10831 @end menu
10832
10833 @node About gnatelim
10834 @subsection About @code{gnatelim}
10835
10836 @noindent
10837 When a program shares a set of Ada
10838 packages with other programs, it may happen that this program uses
10839 only a fraction of the subprograms defined in these packages. The code
10840 created for these unused subprograms increases the size of the executable.
10841
10842 @code{gnatelim} tracks unused subprograms in an Ada program and
10843 outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the
10844 subprograms that are declared but never called. By placing the list of
10845 @code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and
10846 recompiling your program, you may decrease the size of its executable,
10847 because the compiler will not generate the code for 'eliminated' subprograms.
10848 @xref{Pragma Eliminate,,, gnat_rm, GNAT Reference Manual}, for more
10849 information about this pragma.
10850
10851 @code{gnatelim} needs as its input data the name of the main subprogram.
10852
10853 If a set of source files is specified as @code{gnatelim} arguments, it
10854 treats these files as a complete set of sources making up a program to
10855 analyse, and analyses only these sources.
10856
10857 After a full successful build of the main subprogram @code{gnatelim} can be
10858 called without  specifying sources to analyse, in this case it computes
10859 the source closure of the main unit from the @file{ALI} files.
10860
10861 The following command will create the set of @file{ALI} files needed for
10862 @code{gnatelim}:
10863
10864 @smallexample
10865 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
10866 @end smallexample
10867
10868 Note that @code{gnatelim} does not need object files.
10869
10870 @node Running gnatelim
10871 @subsection Running @code{gnatelim}
10872
10873 @noindent
10874 @code{gnatelim} has the following command-line interface:
10875
10876 @smallexample
10877 $ gnatelim [@var{switches}] ^-main^?MAIN^=@var{main_unit_name} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
10878 @end smallexample
10879
10880 @noindent
10881 @var{main_unit_name} should be a name of a source file that contains the main
10882 subprogram of a program (partition).
10883
10884 Each @var{filename} is the name (including the extension) of a source
10885 file to process. ``Wildcards'' are allowed, and
10886 the file name may contain path information.
10887
10888 @samp{@var{gcc_switches}} is a list of switches for
10889 @command{gcc}. They will be passed on to all compiler invocations made by
10890 @command{gnatelim} to generate the ASIS trees. Here you can provide
10891 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
10892 use the @option{-gnatec} switch to set the configuration file,
10893 use the @option{-gnat05} switch if sources should be compiled in
10894 Ada 2005 mode etc.
10895
10896 @code{gnatelim} has the following switches:
10897
10898 @table @option
10899 @c !sort!
10900 @item ^-files^/FILES^=@var{filename}
10901 @cindex @option{^-files^/FILES^} (@code{gnatelim})
10902 Take the argument source files from the specified file. This file should be an
10903 ordinary text file containing file names separated by spaces or
10904 line breaks. You can use this switch more than once in the same call to
10905 @command{gnatelim}. You also can combine this switch with
10906 an explicit list of files.
10907
10908 @item ^-log^/LOG^
10909 @cindex @option{^-log^/LOG^} (@command{gnatelim})
10910 Duplicate all the output sent to @file{stderr} into a log file. The log file
10911 is named @file{gnatelim.log} and is located in the current directory.
10912
10913 @item ^-log^/LOGFILE^=@var{filename}
10914 @cindex @option{^-log^/LOGFILE^} (@command{gnatelim})
10915 Duplicate all the output sent to @file{stderr} into a specified log file.
10916
10917 @cindex @option{^--no-elim-dispatch^/NO_DISPATCH^} (@command{gnatelim})
10918 @item ^--no-elim-dispatch^/NO_DISPATCH^
10919 Do not generate pragmas for dispatching operations.
10920
10921 @item ^--ignore^/IGNORE^=@var{filename}
10922 @cindex @option{^--ignore^/IGNORE^} (@command{gnatelim})
10923 Do not generate pragmas for subprograms declared in the sources
10924 listed in a specified file
10925
10926 @cindex @option{^-o^/OUTPUT^} (@command{gnatelim})
10927 @item ^-o^/OUTPUT^=@var{report_file}
10928 Put @command{gnatelim} output into a specified file. If this file already exists,
10929 it is overridden. If this switch is not used, @command{gnatelim} outputs its results
10930 into @file{stderr}
10931
10932 @item ^-q^/QUIET^
10933 @cindex @option{^-q^/QUIET^} (@command{gnatelim})
10934 Quiet mode: by default @code{gnatelim} outputs to the standard error
10935 stream the number of program units left to be processed. This option turns
10936 this trace off.
10937
10938 @cindex @option{^-t^/TIME^} (@command{gnatelim})
10939 @item ^-t^/TIME^
10940 Print out execution time.
10941
10942 @item ^-v^/VERBOSE^
10943 @cindex @option{^-v^/VERBOSE^} (@command{gnatelim})
10944 Verbose mode: @code{gnatelim} version information is printed as Ada
10945 comments to the standard output stream. Also, in addition to the number of
10946 program units left @code{gnatelim} will output the name of the current unit
10947 being processed.
10948
10949 @item ^-wq^/WARNINGS=QUIET^
10950 @cindex @option{^-wq^/WARNINGS=QUIET^} (@command{gnatelim})
10951 Quet warning mode - some warnings are suppressed. In particular warnings that
10952 indicate that the analysed set of sources is incomplete to make up a
10953 partition and that some subprogram bodies are missing are not generated.
10954 @end table
10955
10956 @node Processing Precompiled Libraries
10957 @subsection Processing Precompiled Libraries
10958
10959 @noindent
10960 If some program uses a precompiled Ada library, it can be processed by
10961 @code{gnatelim} in a usual way. @code{gnatelim} will newer generate an
10962 Eliminate pragma for a subprogram if the body of this subprogram has not
10963 been analysed, this is a typical case for subprograms from precompiled
10964 libraries. Switch @option{^-wq^/WARNINGS=QUIET^} may be used to suppress
10965 warnings about missing source files and non-analyzed subprogram bodies
10966 that can be generated when processing precompiled Ada libraries.
10967
10968 @node Correcting the List of Eliminate Pragmas
10969 @subsection Correcting the List of Eliminate Pragmas
10970
10971 @noindent
10972 In some rare cases @code{gnatelim} may try to eliminate
10973 subprograms that are actually called in the program. In this case, the
10974 compiler will generate an error message of the form:
10975
10976 @smallexample
10977 main.adb:4:08: cannot reference subprogram "P" eliminated at elim.out:5
10978 @end smallexample
10979
10980 @noindent
10981 You will need to manually remove the wrong @code{Eliminate} pragmas from
10982 the configuration file indicated in the error message. You should recompile
10983 your program from scratch after that, because you need a consistent
10984 configuration file(s) during the entire compilation.
10985
10986 @node Making Your Executables Smaller
10987 @subsection Making Your Executables Smaller
10988
10989 @noindent
10990 In order to get a smaller executable for your program you now have to
10991 recompile the program completely with the configuration file containing
10992 pragmas Eliminate generated by gnatelim. If these pragmas are placed in
10993 @file{gnat.adc} file located in your current directory, just do:
10994
10995 @smallexample
10996 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
10997 @end smallexample
10998
10999 @noindent
11000 (Use the @option{^-f^/FORCE_COMPILE^} option for @command{gnatmake} to
11001 recompile everything
11002 with the set of pragmas @code{Eliminate} that you have obtained with
11003 @command{gnatelim}).
11004
11005 Be aware that the set of @code{Eliminate} pragmas is specific to each
11006 program. It is not recommended to merge sets of @code{Eliminate}
11007 pragmas created for different programs in one configuration file.
11008
11009 @node Summary of the gnatelim Usage Cycle
11010 @subsection Summary of the @code{gnatelim} Usage Cycle
11011
11012 @noindent
11013 Here is a quick summary of the steps to be taken in order to reduce
11014 the size of your executables with @code{gnatelim}. You may use
11015 other GNAT options to control the optimization level,
11016 to produce the debugging information, to set search path, etc.
11017
11018 @enumerate
11019 @item
11020 Create a complete set of @file{ALI} files (if the program has not been
11021 built already)
11022
11023 @smallexample
11024 $ gnatmake ^-c main_prog^/ACTIONS=COMPILE MAIN_PROG^
11025 @end smallexample
11026
11027 @item
11028 Generate a list of @code{Eliminate} pragmas in default configuration file
11029 @file{gnat.adc} in the current directory
11030 @smallexample
11031 @ifset vms
11032 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
11033 @end ifset
11034 @ifclear vms
11035 $ gnatelim main_prog >@r{[}>@r{]} gnat.adc
11036 @end ifclear
11037 @end smallexample
11038
11039 @item
11040 Recompile the application
11041
11042 @smallexample
11043 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
11044 @end smallexample
11045
11046 @end enumerate
11047
11048 @node Reducing Size of Executables with unused subprogram/data elimination
11049 @section Reducing Size of Executables with Unused Subprogram/Data Elimination
11050 @findex unused subprogram/data elimination
11051
11052 @noindent
11053 This section describes how you can eliminate unused subprograms and data from
11054 your executable just by setting options at compilation time.
11055
11056 @menu
11057 * About unused subprogram/data elimination::
11058 * Compilation options::
11059 * Example of unused subprogram/data elimination::
11060 @end menu
11061
11062 @node About unused subprogram/data elimination
11063 @subsection About unused subprogram/data elimination
11064
11065 @noindent
11066 By default, an executable contains all code and data of its composing objects
11067 (directly linked or coming from statically linked libraries), even data or code
11068 never used by this executable.
11069
11070 This feature will allow you to eliminate such unused code from your
11071 executable, making it smaller (in disk and in memory).
11072
11073 This functionality is available on all Linux platforms except for the IA-64
11074 architecture and on all cross platforms using the ELF binary file format.
11075 In both cases GNU binutils version 2.16 or later are required to enable it.
11076
11077 @node Compilation options
11078 @subsection Compilation options
11079
11080 @noindent
11081 The operation of eliminating the unused code and data from the final executable
11082 is directly performed by the linker.
11083
11084 In order to do this, it has to work with objects compiled with the
11085 following options:
11086 @option{-ffunction-sections} @option{-fdata-sections}.
11087 @cindex @option{-ffunction-sections} (@command{gcc})
11088 @cindex @option{-fdata-sections} (@command{gcc})
11089 These options are usable with C and Ada files.
11090 They will place respectively each
11091 function or data in a separate section in the resulting object file.
11092
11093 Once the objects and static libraries are created with these options, the
11094 linker can perform the dead code elimination. You can do this by setting
11095 the @option{-Wl,--gc-sections} option to gcc command or in the
11096 @option{-largs} section of @command{gnatmake}. This will perform a
11097 garbage collection of code and data never referenced.
11098
11099 If the linker performs a partial link (@option{-r} ld linker option), then you
11100 will need to provide one or several entry point using the
11101 @option{-e} / @option{--entry} ld option.
11102
11103 Note that objects compiled without the @option{-ffunction-sections} and
11104 @option{-fdata-sections} options can still be linked with the executable.
11105 However, no dead code elimination will be performed on those objects (they will
11106 be linked as is).
11107
11108 The GNAT static library is now compiled with -ffunction-sections and
11109 -fdata-sections on some platforms. This allows you to eliminate the unused code
11110 and data of the GNAT library from your executable.
11111
11112 @node Example of unused subprogram/data elimination
11113 @subsection Example of unused subprogram/data elimination
11114
11115 @noindent
11116 Here is a simple example:
11117
11118 @smallexample @c ada
11119 with Aux;
11120
11121 procedure Test is
11122 begin
11123    Aux.Used (10);
11124 end Test;
11125
11126 package Aux is
11127    Used_Data   : Integer;
11128    Unused_Data : Integer;
11129
11130    procedure Used   (Data : Integer);
11131    procedure Unused (Data : Integer);
11132 end Aux;
11133
11134 package body Aux is
11135    procedure Used (Data : Integer) is
11136    begin
11137       Used_Data := Data;
11138    end Used;
11139
11140    procedure Unused (Data : Integer) is
11141    begin
11142       Unused_Data := Data;
11143    end Unused;
11144 end Aux;
11145 @end smallexample
11146
11147 @noindent
11148 @code{Unused} and @code{Unused_Data} are never referenced in this code
11149 excerpt, and hence they may be safely removed from the final executable.
11150
11151 @smallexample
11152 $ gnatmake test
11153
11154 $ nm test | grep used
11155 020015f0 T aux__unused
11156 02005d88 B aux__unused_data
11157 020015cc T aux__used
11158 02005d84 B aux__used_data
11159
11160 $ gnatmake test -cargs -fdata-sections -ffunction-sections \
11161      -largs -Wl,--gc-sections
11162
11163 $ nm test | grep used
11164 02005350 T aux__used
11165 0201ffe0 B aux__used_data
11166 @end smallexample
11167
11168 @noindent
11169 It can be observed that the procedure @code{Unused} and the object
11170 @code{Unused_Data} are removed by the linker when using the
11171 appropriate options.
11172
11173 @c ********************************
11174 @node Renaming Files Using gnatchop
11175 @chapter Renaming Files Using @code{gnatchop}
11176 @findex gnatchop
11177
11178 @noindent
11179 This chapter discusses how to handle files with multiple units by using
11180 the @code{gnatchop} utility. This utility is also useful in renaming
11181 files to meet the standard GNAT default file naming conventions.
11182
11183 @menu
11184 * Handling Files with Multiple Units::
11185 * Operating gnatchop in Compilation Mode::
11186 * Command Line for gnatchop::
11187 * Switches for gnatchop::
11188 * Examples of gnatchop Usage::
11189 @end menu
11190
11191 @node Handling Files with Multiple Units
11192 @section Handling Files with Multiple Units
11193
11194 @noindent
11195 The basic compilation model of GNAT requires that a file submitted to the
11196 compiler have only one unit and there be a strict correspondence
11197 between the file name and the unit name.
11198
11199 The @code{gnatchop} utility allows both of these rules to be relaxed,
11200 allowing GNAT to process files which contain multiple compilation units
11201 and files with arbitrary file names. @code{gnatchop}
11202 reads the specified file and generates one or more output files,
11203 containing one unit per file. The unit and the file name correspond,
11204 as required by GNAT.
11205
11206 If you want to permanently restructure a set of ``foreign'' files so that
11207 they match the GNAT rules, and do the remaining development using the
11208 GNAT structure, you can simply use @command{gnatchop} once, generate the
11209 new set of files and work with them from that point on.
11210
11211 Alternatively, if you want to keep your files in the ``foreign'' format,
11212 perhaps to maintain compatibility with some other Ada compilation
11213 system, you can set up a procedure where you use @command{gnatchop} each
11214 time you compile, regarding the source files that it writes as temporary
11215 files that you throw away.
11216
11217 Note that if your file containing multiple units starts with a byte order
11218 mark (BOM) specifying UTF-8 encoding, then the files generated by gnatchop
11219 will each start with a copy of this BOM, meaning that they can be compiled
11220 automatically in UTF-8 mode without needing to specify an explicit encoding.
11221
11222 @node Operating gnatchop in Compilation Mode
11223 @section Operating gnatchop in Compilation Mode
11224
11225 @noindent
11226 The basic function of @code{gnatchop} is to take a file with multiple units
11227 and split it into separate files. The boundary between files is reasonably
11228 clear, except for the issue of comments and pragmas. In default mode, the
11229 rule is that any pragmas between units belong to the previous unit, except
11230 that configuration pragmas always belong to the following unit. Any comments
11231 belong to the following unit. These rules
11232 almost always result in the right choice of
11233 the split point without needing to mark it explicitly and most users will
11234 find this default to be what they want. In this default mode it is incorrect to
11235 submit a file containing only configuration pragmas, or one that ends in
11236 configuration pragmas, to @code{gnatchop}.
11237
11238 However, using a special option to activate ``compilation mode'',
11239 @code{gnatchop}
11240 can perform another function, which is to provide exactly the semantics
11241 required by the RM for handling of configuration pragmas in a compilation.
11242 In the absence of configuration pragmas (at the main file level), this
11243 option has no effect, but it causes such configuration pragmas to be handled
11244 in a quite different manner.
11245
11246 First, in compilation mode, if @code{gnatchop} is given a file that consists of
11247 only configuration pragmas, then this file is appended to the
11248 @file{gnat.adc} file in the current directory. This behavior provides
11249 the required behavior described in the RM for the actions to be taken
11250 on submitting such a file to the compiler, namely that these pragmas
11251 should apply to all subsequent compilations in the same compilation
11252 environment. Using GNAT, the current directory, possibly containing a
11253 @file{gnat.adc} file is the representation
11254 of a compilation environment. For more information on the
11255 @file{gnat.adc} file, see @ref{Handling of Configuration Pragmas}.
11256
11257 Second, in compilation mode, if @code{gnatchop}
11258 is given a file that starts with
11259 configuration pragmas, and contains one or more units, then these
11260 configuration pragmas are prepended to each of the chopped files. This
11261 behavior provides the required behavior described in the RM for the
11262 actions to be taken on compiling such a file, namely that the pragmas
11263 apply to all units in the compilation, but not to subsequently compiled
11264 units.
11265
11266 Finally, if configuration pragmas appear between units, they are appended
11267 to the previous unit. This results in the previous unit being illegal,
11268 since the compiler does not accept configuration pragmas that follow
11269 a unit. This provides the required RM behavior that forbids configuration
11270 pragmas other than those preceding the first compilation unit of a
11271 compilation.
11272
11273 For most purposes, @code{gnatchop} will be used in default mode. The
11274 compilation mode described above is used only if you need exactly
11275 accurate behavior with respect to compilations, and you have files
11276 that contain multiple units and configuration pragmas. In this
11277 circumstance the use of @code{gnatchop} with the compilation mode
11278 switch provides the required behavior, and is for example the mode
11279 in which GNAT processes the ACVC tests.
11280
11281 @node Command Line for gnatchop
11282 @section Command Line for @code{gnatchop}
11283
11284 @noindent
11285 The @code{gnatchop} command has the form:
11286
11287 @smallexample
11288 @c $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11289 @c      @ovar{directory}
11290 @c Expanding @ovar macro inline (explanation in macro def comments)
11291 $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11292       @r{[}@var{directory}@r{]}
11293 @end smallexample
11294
11295 @noindent
11296 The only required argument is the file name of the file to be chopped.
11297 There are no restrictions on the form of this file name. The file itself
11298 contains one or more Ada units, in normal GNAT format, concatenated
11299 together. As shown, more than one file may be presented to be chopped.
11300
11301 When run in default mode, @code{gnatchop} generates one output file in
11302 the current directory for each unit in each of the files.
11303
11304 @var{directory}, if specified, gives the name of the directory to which
11305 the output files will be written. If it is not specified, all files are
11306 written to the current directory.
11307
11308 For example, given a
11309 file called @file{hellofiles} containing
11310
11311 @smallexample @c ada
11312 @group
11313 @cartouche
11314 procedure hello;
11315
11316 with Text_IO; use Text_IO;
11317 procedure hello is
11318 begin
11319    Put_Line ("Hello");
11320 end hello;
11321 @end cartouche
11322 @end group
11323 @end smallexample
11324
11325 @noindent
11326 the command
11327
11328 @smallexample
11329 $ gnatchop ^hellofiles^HELLOFILES.^
11330 @end smallexample
11331
11332 @noindent
11333 generates two files in the current directory, one called
11334 @file{hello.ads} containing the single line that is the procedure spec,
11335 and the other called @file{hello.adb} containing the remaining text. The
11336 original file is not affected. The generated files can be compiled in
11337 the normal manner.
11338
11339 @noindent
11340 When gnatchop is invoked on a file that is empty or that contains only empty
11341 lines and/or comments, gnatchop will not fail, but will not produce any
11342 new sources.
11343
11344 For example, given a
11345 file called @file{toto.txt} containing
11346
11347 @smallexample @c ada
11348 @group
11349 @cartouche
11350 --  Just a comment
11351 @end cartouche
11352 @end group
11353 @end smallexample
11354
11355 @noindent
11356 the command
11357
11358 @smallexample
11359 $ gnatchop ^toto.txt^TOT.TXT^
11360 @end smallexample
11361
11362 @noindent
11363 will not produce any new file and will result in the following warnings:
11364
11365 @smallexample
11366 toto.txt:1:01: warning: empty file, contains no compilation units
11367 no compilation units found
11368 no source files written
11369 @end smallexample
11370
11371 @node Switches for gnatchop
11372 @section Switches for @code{gnatchop}
11373
11374 @noindent
11375 @command{gnatchop} recognizes the following switches:
11376
11377 @table @option
11378 @c !sort!
11379
11380 @item --version
11381 @cindex @option{--version} @command{gnatchop}
11382 Display Copyright and version, then exit disregarding all other options.
11383
11384 @item --help
11385 @cindex @option{--help} @command{gnatchop}
11386 If @option{--version} was not used, display usage, then exit disregarding
11387 all other options.
11388
11389 @item ^-c^/COMPILATION^
11390 @cindex @option{^-c^/COMPILATION^} (@code{gnatchop})
11391 Causes @code{gnatchop} to operate in compilation mode, in which
11392 configuration pragmas are handled according to strict RM rules. See
11393 previous section for a full description of this mode.
11394
11395 @ifclear vms
11396 @item -gnat@var{xxx}
11397 This passes the given @option{-gnat@var{xxx}} switch to @code{gnat} which is
11398 used to parse the given file. Not all @var{xxx} options make sense,
11399 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
11400 process a source file that uses Latin-2 coding for identifiers.
11401 @end ifclear
11402
11403 @item ^-h^/HELP^
11404 Causes @code{gnatchop} to generate a brief help summary to the standard
11405 output file showing usage information.
11406
11407 @item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^
11408 @cindex @option{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop})
11409 Limit generated file names to the specified number @code{mm}
11410 of characters.
11411 This is useful if the
11412 resulting set of files is required to be interoperable with systems
11413 which limit the length of file names.
11414 @ifset vms
11415 If no value is given, or
11416 if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given,
11417 a default of 39, suitable for OpenVMS Alpha
11418 Systems, is assumed
11419 @end ifset
11420 @ifclear vms
11421 No space is allowed between the @option{-k} and the numeric value. The numeric
11422 value may be omitted in which case a default of @option{-k8},
11423 suitable for use
11424 with DOS-like file systems, is used. If no @option{-k} switch
11425 is present then
11426 there is no limit on the length of file names.
11427 @end ifclear
11428
11429 @item ^-p^/PRESERVE^
11430 @cindex @option{^-p^/PRESERVE^} (@code{gnatchop})
11431 Causes the file ^modification^creation^ time stamp of the input file to be
11432 preserved and used for the time stamp of the output file(s). This may be
11433 useful for preserving coherency of time stamps in an environment where
11434 @code{gnatchop} is used as part of a standard build process.
11435
11436 @item ^-q^/QUIET^
11437 @cindex @option{^-q^/QUIET^} (@code{gnatchop})
11438 Causes output of informational messages indicating the set of generated
11439 files to be suppressed. Warnings and error messages are unaffected.
11440
11441 @item ^-r^/REFERENCE^
11442 @cindex @option{^-r^/REFERENCE^} (@code{gnatchop})
11443 @findex Source_Reference
11444 Generate @code{Source_Reference} pragmas. Use this switch if the output
11445 files are regarded as temporary and development is to be done in terms
11446 of the original unchopped file. This switch causes
11447 @code{Source_Reference} pragmas to be inserted into each of the
11448 generated files to refers back to the original file name and line number.
11449 The result is that all error messages refer back to the original
11450 unchopped file.
11451 In addition, the debugging information placed into the object file (when
11452 the @option{^-g^/DEBUG^} switch of @command{gcc} or @command{gnatmake} is
11453 specified)
11454 also refers back to this original file so that tools like profilers and
11455 debuggers will give information in terms of the original unchopped file.
11456
11457 If the original file to be chopped itself contains
11458 a @code{Source_Reference}
11459 pragma referencing a third file, then gnatchop respects
11460 this pragma, and the generated @code{Source_Reference} pragmas
11461 in the chopped file refer to the original file, with appropriate
11462 line numbers. This is particularly useful when @code{gnatchop}
11463 is used in conjunction with @code{gnatprep} to compile files that
11464 contain preprocessing statements and multiple units.
11465
11466 @item ^-v^/VERBOSE^
11467 @cindex @option{^-v^/VERBOSE^} (@code{gnatchop})
11468 Causes @code{gnatchop} to operate in verbose mode. The version
11469 number and copyright notice are output, as well as exact copies of
11470 the gnat1 commands spawned to obtain the chop control information.
11471
11472 @item ^-w^/OVERWRITE^
11473 @cindex @option{^-w^/OVERWRITE^} (@code{gnatchop})
11474 Overwrite existing file names. Normally @code{gnatchop} regards it as a
11475 fatal error if there is already a file with the same name as a
11476 file it would otherwise output, in other words if the files to be
11477 chopped contain duplicated units. This switch bypasses this
11478 check, and causes all but the last instance of such duplicated
11479 units to be skipped.
11480
11481 @ifclear vms
11482 @item --GCC=@var{xxxx}
11483 @cindex @option{--GCC=} (@code{gnatchop})
11484 Specify the path of the GNAT parser to be used. When this switch is used,
11485 no attempt is made to add the prefix to the GNAT parser executable.
11486 @end ifclear
11487 @end table
11488
11489 @node Examples of gnatchop Usage
11490 @section Examples of @code{gnatchop} Usage
11491
11492 @table @code
11493 @ifset vms
11494 @item gnatchop /OVERWRITE HELLO_S.ADA [PRERELEASE.FILES]
11495 @end ifset
11496 @ifclear vms
11497 @item gnatchop -w hello_s.ada prerelease/files
11498 @end ifclear
11499
11500 Chops the source file @file{hello_s.ada}. The output files will be
11501 placed in the directory @file{^prerelease/files^[PRERELEASE.FILES]^},
11502 overwriting any
11503 files with matching names in that directory (no files in the current
11504 directory are modified).
11505
11506 @item gnatchop ^archive^ARCHIVE.^
11507 Chops the source file @file{^archive^ARCHIVE.^}
11508 into the current directory. One
11509 useful application of @code{gnatchop} is in sending sets of sources
11510 around, for example in email messages. The required sources are simply
11511 concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^
11512 command), and then
11513 @command{gnatchop} is used at the other end to reconstitute the original
11514 file names.
11515
11516 @item gnatchop file1 file2 file3 direc
11517 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
11518 the resulting files in the directory @file{direc}. Note that if any units
11519 occur more than once anywhere within this set of files, an error message
11520 is generated, and no files are written. To override this check, use the
11521 @option{^-w^/OVERWRITE^} switch,
11522 in which case the last occurrence in the last file will
11523 be the one that is output, and earlier duplicate occurrences for a given
11524 unit will be skipped.
11525 @end table
11526
11527 @node Configuration Pragmas
11528 @chapter Configuration Pragmas
11529 @cindex Configuration pragmas
11530 @cindex Pragmas, configuration
11531
11532 @noindent
11533 Configuration pragmas include those pragmas described as
11534 such in the Ada Reference Manual, as well as
11535 implementation-dependent pragmas that are configuration pragmas.
11536 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
11537 for details on these additional GNAT-specific configuration pragmas.
11538 Most notably, the pragma @code{Source_File_Name}, which allows
11539 specifying non-default names for source files, is a configuration
11540 pragma. The following is a complete list of configuration pragmas
11541 recognized by GNAT:
11542
11543 @smallexample
11544    Ada_83
11545    Ada_95
11546    Ada_05
11547    Ada_2005
11548    Ada_12
11549    Ada_2012
11550    Assertion_Policy
11551    Assume_No_Invalid_Values
11552    C_Pass_By_Copy
11553    Check_Name
11554    Check_Policy
11555    Compile_Time_Error
11556    Compile_Time_Warning
11557    Compiler_Unit
11558    Component_Alignment
11559    Convention_Identifier
11560    Debug_Policy
11561    Detect_Blocking
11562    Default_Storage_Pool
11563    Discard_Names
11564    Elaboration_Checks
11565    Eliminate
11566    Extend_System
11567    Extensions_Allowed
11568    External_Name_Casing
11569    Fast_Math
11570    Favor_Top_Level
11571    Float_Representation
11572    Implicit_Packing
11573    Initialize_Scalars
11574    Interrupt_State
11575    License
11576    Locking_Policy
11577    Long_Float
11578    No_Run_Time
11579    No_Strict_Aliasing
11580    Normalize_Scalars
11581    Optimize_Alignment
11582    Persistent_BSS
11583    Polling
11584    Priority_Specific_Dispatching
11585    Profile
11586    Profile_Warnings
11587    Propagate_Exceptions
11588    Queuing_Policy
11589    Ravenscar
11590    Restricted_Run_Time
11591    Restrictions
11592    Restrictions_Warnings
11593    Reviewable
11594    Short_Circuit_And_Or
11595    Source_File_Name
11596    Source_File_Name_Project
11597    Style_Checks
11598    Suppress
11599    Suppress_Exception_Locations
11600    Task_Dispatching_Policy
11601    Universal_Data
11602    Unsuppress
11603    Use_VADS_Size
11604    Validity_Checks
11605    Warnings
11606    Wide_Character_Encoding
11607
11608 @end smallexample
11609
11610 @menu
11611 * Handling of Configuration Pragmas::
11612 * The Configuration Pragmas Files::
11613 @end menu
11614
11615 @node Handling of Configuration Pragmas
11616 @section Handling of Configuration Pragmas
11617
11618 Configuration pragmas may either appear at the start of a compilation
11619 unit, in which case they apply only to that unit, or they may apply to
11620 all compilations performed in a given compilation environment.
11621
11622 GNAT also provides the @code{gnatchop} utility to provide an automatic
11623 way to handle configuration pragmas following the semantics for
11624 compilations (that is, files with multiple units), described in the RM.
11625 See @ref{Operating gnatchop in Compilation Mode} for details.
11626 However, for most purposes, it will be more convenient to edit the
11627 @file{gnat.adc} file that contains configuration pragmas directly,
11628 as described in the following section.
11629
11630 @node The Configuration Pragmas Files
11631 @section The Configuration Pragmas Files
11632 @cindex @file{gnat.adc}
11633
11634 @noindent
11635 In GNAT a compilation environment is defined by the current
11636 directory at the time that a compile command is given. This current
11637 directory is searched for a file whose name is @file{gnat.adc}. If
11638 this file is present, it is expected to contain one or more
11639 configuration pragmas that will be applied to the current compilation.
11640 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
11641 considered.
11642
11643 Configuration pragmas may be entered into the @file{gnat.adc} file
11644 either by running @code{gnatchop} on a source file that consists only of
11645 configuration pragmas, or more conveniently  by
11646 direct editing of the @file{gnat.adc} file, which is a standard format
11647 source file.
11648
11649 In addition to @file{gnat.adc}, additional files containing configuration
11650 pragmas may be applied to the current compilation using the switch
11651 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
11652 contains only configuration pragmas. These configuration pragmas are
11653 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
11654 is present and switch @option{-gnatA} is not used).
11655
11656 It is allowed to specify several switches @option{-gnatec}, all of which
11657 will be taken into account.
11658
11659 If you are using project file, a separate mechanism is provided using
11660 project attributes, see @ref{Specifying Configuration Pragmas} for more
11661 details.
11662
11663 @ifset vms
11664 Of special interest to GNAT OpenVMS Alpha is the following
11665 configuration pragma:
11666
11667 @smallexample @c ada
11668 @cartouche
11669 pragma Extend_System (Aux_DEC);
11670 @end cartouche
11671 @end smallexample
11672
11673 @noindent
11674 In the presence of this pragma, GNAT adds to the definition of the
11675 predefined package SYSTEM all the additional types and subprograms that are
11676 defined in HP Ada. See @ref{Compatibility with HP Ada} for details.
11677 @end ifset
11678
11679 @node Handling Arbitrary File Naming Conventions Using gnatname
11680 @chapter Handling Arbitrary File Naming Conventions Using @code{gnatname}
11681 @cindex Arbitrary File Naming Conventions
11682
11683 @menu
11684 * Arbitrary File Naming Conventions::
11685 * Running gnatname::
11686 * Switches for gnatname::
11687 * Examples of gnatname Usage::
11688 @end menu
11689
11690 @node Arbitrary File Naming Conventions
11691 @section Arbitrary File Naming Conventions
11692
11693 @noindent
11694 The GNAT compiler must be able to know the source file name of a compilation
11695 unit.  When using the standard GNAT default file naming conventions
11696 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
11697 does not need additional information.
11698
11699 @noindent
11700 When the source file names do not follow the standard GNAT default file naming
11701 conventions, the GNAT compiler must be given additional information through
11702 a configuration pragmas file (@pxref{Configuration Pragmas})
11703 or a project file.
11704 When the non-standard file naming conventions are well-defined,
11705 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
11706 (@pxref{Alternative File Naming Schemes}) may be sufficient. However,
11707 if the file naming conventions are irregular or arbitrary, a number
11708 of pragma @code{Source_File_Name} for individual compilation units
11709 must be defined.
11710 To help maintain the correspondence between compilation unit names and
11711 source file names within the compiler,
11712 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
11713 set of files.
11714
11715 @node Running gnatname
11716 @section Running @code{gnatname}
11717
11718 @noindent
11719 The usual form of the @code{gnatname} command is
11720
11721 @smallexample
11722 @c $ gnatname @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}
11723 @c       @r{[}--and @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}@r{]}
11724 @c Expanding @ovar macro inline (explanation in macro def comments)
11725 $ gnatname @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}
11726       @r{[}--and @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}@r{]}
11727 @end smallexample
11728
11729 @noindent
11730 All of the arguments are optional. If invoked without any argument,
11731 @code{gnatname} will display its usage.
11732
11733 @noindent
11734 When used with at least one naming pattern, @code{gnatname} will attempt to
11735 find all the compilation units in files that follow at least one of the
11736 naming patterns. To find these compilation units,
11737 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
11738 regular files.
11739
11740 @noindent
11741 One or several Naming Patterns may be given as arguments to @code{gnatname}.
11742 Each Naming Pattern is enclosed between double quotes (or single
11743 quotes on Windows).
11744 A Naming Pattern is a regular expression similar to the wildcard patterns
11745 used in file names by the Unix shells or the DOS prompt.
11746
11747 @noindent
11748 @code{gnatname} may be called with several sections of directories/patterns.
11749 Sections are separated by switch @code{--and}. In each section, there must be
11750 at least one pattern. If no directory is specified in a section, the current
11751 directory (or the project directory is @code{-P} is used) is implied.
11752 The options other that the directory switches and the patterns apply globally
11753 even if they are in different sections.
11754
11755 @noindent
11756 Examples of Naming Patterns are
11757
11758 @smallexample
11759    "*.[12].ada"
11760    "*.ad[sb]*"
11761    "body_*"    "spec_*"
11762 @end smallexample
11763
11764 @noindent
11765 For a more complete description of the syntax of Naming Patterns,
11766 see the second kind of regular expressions described in @file{g-regexp.ads}
11767 (the ``Glob'' regular expressions).
11768
11769 @noindent
11770 When invoked with no switch @code{-P}, @code{gnatname} will create a
11771 configuration pragmas file @file{gnat.adc} in the current working directory,
11772 with pragmas @code{Source_File_Name} for each file that contains a valid Ada
11773 unit.
11774
11775 @node Switches for gnatname
11776 @section Switches for @code{gnatname}
11777
11778 @noindent
11779 Switches for @code{gnatname} must precede any specified Naming Pattern.
11780
11781 @noindent
11782 You may specify any of the following switches to @code{gnatname}:
11783
11784 @table @option
11785 @c !sort!
11786
11787 @item --version
11788 @cindex @option{--version} @command{gnatname}
11789 Display Copyright and version, then exit disregarding all other options.
11790
11791 @item --help
11792 @cindex @option{--help} @command{gnatname}
11793 If @option{--version} was not used, display usage, then exit disregarding
11794 all other options.
11795
11796 @item --and
11797 Start another section of directories/patterns.
11798
11799 @item ^-c^/CONFIG_FILE=^@file{file}
11800 @cindex @option{^-c^/CONFIG_FILE^} (@code{gnatname})
11801 Create a configuration pragmas file @file{file} (instead of the default
11802 @file{gnat.adc}).
11803 @ifclear vms
11804 There may be zero, one or more space between @option{-c} and
11805 @file{file}.
11806 @end ifclear
11807 @file{file} may include directory information. @file{file} must be
11808 writable. There may be only one switch @option{^-c^/CONFIG_FILE^}.
11809 When a switch @option{^-c^/CONFIG_FILE^} is
11810 specified, no switch @option{^-P^/PROJECT_FILE^} may be specified (see below).
11811
11812 @item ^-d^/SOURCE_DIRS=^@file{dir}
11813 @cindex @option{^-d^/SOURCE_DIRS^} (@code{gnatname})
11814 Look for source files in directory @file{dir}. There may be zero, one or more
11815 spaces between @option{^-d^/SOURCE_DIRS=^} and @file{dir}.
11816 When a switch @option{^-d^/SOURCE_DIRS^}
11817 is specified, the current working directory will not be searched for source
11818 files, unless it is explicitly specified with a @option{^-d^/SOURCE_DIRS^}
11819 or @option{^-D^/DIR_FILES^} switch.
11820 Several switches @option{^-d^/SOURCE_DIRS^} may be specified.
11821 If @file{dir} is a relative path, it is relative to the directory of
11822 the configuration pragmas file specified with switch
11823 @option{^-c^/CONFIG_FILE^},
11824 or to the directory of the project file specified with switch
11825 @option{^-P^/PROJECT_FILE^} or,
11826 if neither switch @option{^-c^/CONFIG_FILE^}
11827 nor switch @option{^-P^/PROJECT_FILE^} are specified, it is relative to the
11828 current working directory. The directory
11829 specified with switch @option{^-d^/SOURCE_DIRS^} must exist and be readable.
11830
11831 @item ^-D^/DIRS_FILE=^@file{file}
11832 @cindex @option{^-D^/DIRS_FILE^} (@code{gnatname})
11833 Look for source files in all directories listed in text file @file{file}.
11834 There may be zero, one or more spaces between @option{^-D^/DIRS_FILE=^}
11835 and @file{file}.
11836 @file{file} must be an existing, readable text file.
11837 Each nonempty line in @file{file} must be a directory.
11838 Specifying switch @option{^-D^/DIRS_FILE^} is equivalent to specifying as many
11839 switches @option{^-d^/SOURCE_DIRS^} as there are nonempty lines in
11840 @file{file}.
11841
11842 @item ^-f^/FOREIGN_PATTERN=^@file{pattern}
11843 @cindex @option{^-f^/FOREIGN_PATTERN^} (@code{gnatname})
11844 Foreign patterns. Using this switch, it is possible to add sources of languages
11845 other than Ada to the list of sources of a project file.
11846 It is only useful if a ^-P^/PROJECT_FILE^ switch is used.
11847 For example,
11848 @smallexample
11849 gnatname ^-Pprj -f"*.c"^/PROJECT_FILE=PRJ /FOREIGN_PATTERN=*.C^ "*.ada"
11850 @end smallexample
11851 @noindent
11852 will look for Ada units in all files with the @file{.ada} extension,
11853 and will add to the list of file for project @file{prj.gpr} the C files
11854 with extension @file{.^c^C^}.
11855
11856 @item ^-h^/HELP^
11857 @cindex @option{^-h^/HELP^} (@code{gnatname})
11858 Output usage (help) information. The output is written to @file{stdout}.
11859
11860 @item ^-P^/PROJECT_FILE=^@file{proj}
11861 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatname})
11862 Create or update project file @file{proj}. There may be zero, one or more space
11863 between @option{-P} and @file{proj}. @file{proj} may include directory
11864 information. @file{proj} must be writable.
11865 There may be only one switch @option{^-P^/PROJECT_FILE^}.
11866 When a switch @option{^-P^/PROJECT_FILE^} is specified,
11867 no switch @option{^-c^/CONFIG_FILE^} may be specified.
11868
11869 @item ^-v^/VERBOSE^
11870 @cindex @option{^-v^/VERBOSE^} (@code{gnatname})
11871 Verbose mode. Output detailed explanation of behavior to @file{stdout}.
11872 This includes name of the file written, the name of the directories to search
11873 and, for each file in those directories whose name matches at least one of
11874 the Naming Patterns, an indication of whether the file contains a unit,
11875 and if so the name of the unit.
11876
11877 @item ^-v -v^/VERBOSE /VERBOSE^
11878 @cindex @option{^-v -v^/VERBOSE /VERBOSE^} (@code{gnatname})
11879 Very Verbose mode. In addition to the output produced in verbose mode,
11880 for each file in the searched directories whose name matches none of
11881 the Naming Patterns, an indication is given that there is no match.
11882
11883 @item ^-x^/EXCLUDED_PATTERN=^@file{pattern}
11884 @cindex @option{^-x^/EXCLUDED_PATTERN^} (@code{gnatname})
11885 Excluded patterns. Using this switch, it is possible to exclude some files
11886 that would match the name patterns. For example,
11887 @smallexample
11888 gnatname ^-x "*_nt.ada"^/EXCLUDED_PATTERN=*_nt.ada^ "*.ada"
11889 @end smallexample
11890 @noindent
11891 will look for Ada units in all files with the @file{.ada} extension,
11892 except those whose names end with @file{_nt.ada}.
11893
11894 @end table
11895
11896 @node Examples of gnatname Usage
11897 @section Examples of @code{gnatname} Usage
11898
11899 @ifset vms
11900 @smallexample
11901 $ gnatname /CONFIG_FILE=[HOME.ME]NAMES.ADC /SOURCE_DIRS=SOURCES "[a-z]*.ada*"
11902 @end smallexample
11903 @end ifset
11904
11905 @ifclear vms
11906 @smallexample
11907 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
11908 @end smallexample
11909 @end ifclear
11910
11911 @noindent
11912 In this example, the directory @file{^/home/me^[HOME.ME]^} must already exist
11913 and be writable. In addition, the directory
11914 @file{^/home/me/sources^[HOME.ME.SOURCES]^} (specified by
11915 @option{^-d sources^/SOURCE_DIRS=SOURCES^}) must exist and be readable.
11916
11917 @ifclear vms
11918 Note the optional spaces after @option{-c} and @option{-d}.
11919 @end ifclear
11920
11921 @smallexample
11922 @ifclear vms
11923 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
11924   -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
11925 @end ifclear
11926 @ifset vms
11927 $ gnatname  /PROJECT_FILE=[HOME.ME]PROJ
11928   /EXCLUDED_PATTERN=*_nt_body.ada
11929   /SOURCE_DIRS=(SOURCES,[SOURCES.PLUS])
11930   /DIRS_FILE=COMMON_DIRS.TXT "body_*" "spec_*"
11931 @end ifset
11932 @end smallexample
11933
11934 Note that several switches @option{^-d^/SOURCE_DIRS^} may be used,
11935 even in conjunction with one or several switches
11936 @option{^-D^/DIRS_FILE^}. Several Naming Patterns and one excluded pattern
11937 are used in this example.
11938
11939 @c *****************************************
11940 @c * G N A T  P r o j e c t  M a n a g e r *
11941 @c *****************************************
11942
11943 @c ------ macros for projects.texi
11944 @c These macros are needed when building the gprbuild documentation, but
11945 @c should have no effect in the gnat user's guide
11946
11947 @macro CODESAMPLE{TXT}
11948 @smallexample
11949 @group
11950 \TXT\
11951 @end group
11952 @end smallexample
11953 @end macro
11954
11955 @macro PROJECTFILE{TXT}
11956 @CODESAMPLE{\TXT\}
11957 @end macro
11958
11959 @c simulates a newline when in a @CODESAMPLE
11960 @macro NL{}
11961 @end macro
11962
11963 @macro TIP{TXT}
11964 @quotation
11965 @noindent
11966 \TXT\
11967 @end quotation
11968 @end macro
11969
11970 @macro TIPHTML{TXT}
11971 \TXT\
11972 @end macro
11973
11974 @macro IMPORTANT{TXT}
11975 @quotation
11976 @noindent
11977 \TXT\
11978 @end quotation
11979
11980 @end macro
11981
11982 @macro NOTE{TXT}
11983 @quotation
11984 @noindent
11985 \TXT\
11986 @end quotation
11987 @end macro
11988
11989 @include projects.texi
11990
11991 @c *****************************************
11992 @c * Cross-referencing tools
11993 @c *****************************************
11994
11995 @node The Cross-Referencing Tools gnatxref and gnatfind
11996 @chapter  The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
11997 @findex gnatxref
11998 @findex gnatfind
11999
12000 @noindent
12001 The compiler generates cross-referencing information (unless
12002 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
12003 This information indicates where in the source each entity is declared and
12004 referenced. Note that entities in package Standard are not included, but
12005 entities in all other predefined units are included in the output.
12006
12007 Before using any of these two tools, you need to compile successfully your
12008 application, so that GNAT gets a chance to generate the cross-referencing
12009 information.
12010
12011 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
12012 information to provide the user with the capability to easily locate the
12013 declaration and references to an entity. These tools are quite similar,
12014 the difference being that @code{gnatfind} is intended for locating
12015 definitions and/or references to a specified entity or entities, whereas
12016 @code{gnatxref} is oriented to generating a full report of all
12017 cross-references.
12018
12019 To use these tools, you must not compile your application using the
12020 @option{-gnatx} switch on the @command{gnatmake} command line
12021 (@pxref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
12022 information will not be generated.
12023
12024 Note: to invoke @code{gnatxref} or @code{gnatfind} with a project file,
12025 use the @code{gnat} driver (see @ref{The GNAT Driver and Project Files}).
12026
12027 @menu
12028 * Switches for gnatxref::
12029 * Switches for gnatfind::
12030 * Project Files for gnatxref and gnatfind::
12031 * Regular Expressions in gnatfind and gnatxref::
12032 * Examples of gnatxref Usage::
12033 * Examples of gnatfind Usage::
12034 @end menu
12035
12036 @node Switches for gnatxref
12037 @section @code{gnatxref} Switches
12038
12039 @noindent
12040 The command invocation for @code{gnatxref} is:
12041 @smallexample
12042 @c $ gnatxref @ovar{switches} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
12043 @c Expanding @ovar macro inline (explanation in macro def comments)
12044 $ gnatxref @r{[}@var{switches}@r{]} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
12045 @end smallexample
12046
12047 @noindent
12048 where
12049
12050 @table @var
12051 @item sourcefile1
12052 @itemx sourcefile2
12053 identifies the source files for which a report is to be generated. The
12054 ``with''ed units will be processed too. You must provide at least one file.
12055
12056 These file names are considered to be regular expressions, so for instance
12057 specifying @file{source*.adb} is the same as giving every file in the current
12058 directory whose name starts with @file{source} and whose extension is
12059 @file{adb}.
12060
12061 You shouldn't specify any directory name, just base names. @command{gnatxref}
12062 and @command{gnatfind} will be able to locate these files by themselves using
12063 the source path. If you specify directories, no result is produced.
12064
12065 @end table
12066
12067 @noindent
12068 The switches can be:
12069 @table @option
12070 @c !sort!
12071 @item --version
12072 @cindex @option{--version} @command{gnatxref}
12073 Display Copyright and version, then exit disregarding all other options.
12074
12075 @item --help
12076 @cindex @option{--help} @command{gnatxref}
12077 If @option{--version} was not used, display usage, then exit disregarding
12078 all other options.
12079
12080 @item ^-a^/ALL_FILES^
12081 @cindex @option{^-a^/ALL_FILES^} (@command{gnatxref})
12082 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
12083 the read-only files found in the library search path. Otherwise, these files
12084 will be ignored. This option can be used to protect Gnat sources or your own
12085 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
12086 much faster, and their output much smaller. Read-only here refers to access
12087 or permissions status in the file system for the current user.
12088
12089 @item -aIDIR
12090 @cindex @option{-aIDIR} (@command{gnatxref})
12091 When looking for source files also look in directory DIR. The order in which
12092 source file search is undertaken is the same as for @command{gnatmake}.
12093
12094 @item -aODIR
12095 @cindex @option{-aODIR} (@command{gnatxref})
12096 When searching for library and object files, look in directory
12097 DIR. The order in which library files are searched is the same as for
12098 @command{gnatmake}.
12099
12100 @item -nostdinc
12101 @cindex @option{-nostdinc} (@command{gnatxref})
12102 Do not look for sources in the system default directory.
12103
12104 @item -nostdlib
12105 @cindex @option{-nostdlib} (@command{gnatxref})
12106 Do not look for library files in the system default directory.
12107
12108 @item --ext=@var{extension}
12109 @cindex @option{--ext} (@command{gnatxref})
12110 Specify an alternate ali file extension. The default is @code{ali} and other
12111 extensions (e.g. @code{sli} for SPARK library files) may be specified via this
12112 switch. Note that if this switch overrides the default, which means that only
12113 the new extension will be considered.
12114
12115 @item --RTS=@var{rts-path}
12116 @cindex @option{--RTS} (@command{gnatxref})
12117 Specifies the default location of the runtime library. Same meaning as the
12118 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
12119
12120 @item ^-d^/DERIVED_TYPES^
12121 @cindex @option{^-d^/DERIVED_TYPES^} (@command{gnatxref})
12122 If this switch is set @code{gnatxref} will output the parent type
12123 reference for each matching derived types.
12124
12125 @item ^-f^/FULL_PATHNAME^
12126 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatxref})
12127 If this switch is set, the output file names will be preceded by their
12128 directory (if the file was found in the search path). If this switch is
12129 not set, the directory will not be printed.
12130
12131 @item ^-g^/IGNORE_LOCALS^
12132 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatxref})
12133 If this switch is set, information is output only for library-level
12134 entities, ignoring local entities. The use of this switch may accelerate
12135 @code{gnatfind} and @code{gnatxref}.
12136
12137 @item -IDIR
12138 @cindex @option{-IDIR} (@command{gnatxref})
12139 Equivalent to @samp{-aODIR -aIDIR}.
12140
12141 @item -pFILE
12142 @cindex @option{-pFILE} (@command{gnatxref})
12143 Specify a project file to use @xref{GNAT Project Manager}.
12144 If you need to use the @file{.gpr}
12145 project files, you should use gnatxref through the GNAT driver
12146 (@command{gnat xref -Pproject}).
12147
12148 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
12149 project file in the current directory.
12150
12151 If a project file is either specified or found by the tools, then the content
12152 of the source directory and object directory lines are added as if they
12153 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^}
12154 and @samp{^-aO^OBJECT_SEARCH^}.
12155 @item ^-u^/UNUSED^
12156 Output only unused symbols. This may be really useful if you give your
12157 main compilation unit on the command line, as @code{gnatxref} will then
12158 display every unused entity and 'with'ed package.
12159
12160 @ifclear vms
12161 @item -v
12162 Instead of producing the default output, @code{gnatxref} will generate a
12163 @file{tags} file that can be used by vi. For examples how to use this
12164 feature, see @ref{Examples of gnatxref Usage}. The tags file is output
12165 to the standard output, thus you will have to redirect it to a file.
12166 @end ifclear
12167
12168 @end table
12169
12170 @noindent
12171 All these switches may be in any order on the command line, and may even
12172 appear after the file names. They need not be separated by spaces, thus
12173 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
12174 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
12175
12176 @node Switches for gnatfind
12177 @section @code{gnatfind} Switches
12178
12179 @noindent
12180 The command line for @code{gnatfind} is:
12181
12182 @smallexample
12183 @c $ gnatfind @ovar{switches} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
12184 @c       @r{[}@var{file1} @var{file2} @dots{}]
12185 @c Expanding @ovar macro inline (explanation in macro def comments)
12186 $ gnatfind @r{[}@var{switches}@r{]} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
12187       @r{[}@var{file1} @var{file2} @dots{}@r{]}
12188 @end smallexample
12189
12190 @noindent
12191 where
12192
12193 @table @var
12194 @item pattern
12195 An entity will be output only if it matches the regular expression found
12196 in @var{pattern}, see @ref{Regular Expressions in gnatfind and gnatxref}.
12197
12198 Omitting the pattern is equivalent to specifying @samp{*}, which
12199 will match any entity. Note that if you do not provide a pattern, you
12200 have to provide both a sourcefile and a line.
12201
12202 Entity names are given in Latin-1, with uppercase/lowercase equivalence
12203 for matching purposes. At the current time there is no support for
12204 8-bit codes other than Latin-1, or for wide characters in identifiers.
12205
12206 @item sourcefile
12207 @code{gnatfind} will look for references, bodies or declarations
12208 of symbols referenced in @file{@var{sourcefile}}, at line @var{line}
12209 and column @var{column}. See @ref{Examples of gnatfind Usage}
12210 for syntax examples.
12211
12212 @item line
12213 is a decimal integer identifying the line number containing
12214 the reference to the entity (or entities) to be located.
12215
12216 @item column
12217 is a decimal integer identifying the exact location on the
12218 line of the first character of the identifier for the
12219 entity reference. Columns are numbered from 1.
12220
12221 @item file1 file2 @dots{}
12222 The search will be restricted to these source files. If none are given, then
12223 the search will be done for every library file in the search path.
12224 These file must appear only after the pattern or sourcefile.
12225
12226 These file names are considered to be regular expressions, so for instance
12227 specifying @file{source*.adb} is the same as giving every file in the current
12228 directory whose name starts with @file{source} and whose extension is
12229 @file{adb}.
12230
12231 The location of the spec of the entity will always be displayed, even if it
12232 isn't in one of @file{@var{file1}}, @file{@var{file2}},@enddots{}  The
12233 occurrences of the entity in the separate units of the ones given on the
12234 command line will also be displayed.
12235
12236 Note that if you specify at least one file in this part, @code{gnatfind} may
12237 sometimes not be able to find the body of the subprograms.
12238
12239 @end table
12240
12241 @noindent
12242 At least one of 'sourcefile' or 'pattern' has to be present on
12243 the command line.
12244
12245 The following switches are available:
12246 @table @option
12247 @c !sort!
12248
12249 @cindex @option{--version} @command{gnatfind}
12250 Display Copyright and version, then exit disregarding all other options.
12251
12252 @item --help
12253 @cindex @option{--help} @command{gnatfind}
12254 If @option{--version} was not used, display usage, then exit disregarding
12255 all other options.
12256
12257 @item ^-a^/ALL_FILES^
12258 @cindex @option{^-a^/ALL_FILES^} (@command{gnatfind})
12259 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
12260 the read-only files found in the library search path. Otherwise, these files
12261 will be ignored. This option can be used to protect Gnat sources or your own
12262 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
12263 much faster, and their output much smaller. Read-only here refers to access
12264 or permission status in the file system for the current user.
12265
12266 @item -aIDIR
12267 @cindex @option{-aIDIR} (@command{gnatfind})
12268 When looking for source files also look in directory DIR. The order in which
12269 source file search is undertaken is the same as for @command{gnatmake}.
12270
12271 @item -aODIR
12272 @cindex @option{-aODIR} (@command{gnatfind})
12273 When searching for library and object files, look in directory
12274 DIR. The order in which library files are searched is the same as for
12275 @command{gnatmake}.
12276
12277 @item -nostdinc
12278 @cindex @option{-nostdinc} (@command{gnatfind})
12279 Do not look for sources in the system default directory.
12280
12281 @item -nostdlib
12282 @cindex @option{-nostdlib} (@command{gnatfind})
12283 Do not look for library files in the system default directory.
12284
12285 @item --ext=@var{extension}
12286 @cindex @option{--ext} (@command{gnatfind})
12287 Specify an alternate ali file extension. The default is @code{ali} and other
12288 extensions (e.g. @code{sli} for SPARK library files) may be specified via this
12289 switch. Note that if this switch overrides the default, which means that only
12290 the new extension will be considered.
12291
12292 @item --RTS=@var{rts-path}
12293 @cindex @option{--RTS} (@command{gnatfind})
12294 Specifies the default location of the runtime library. Same meaning as the
12295 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
12296
12297 @item ^-d^/DERIVED_TYPE_INFORMATION^
12298 @cindex @option{^-d^/DERIVED_TYPE_INFORMATION^} (@code{gnatfind})
12299 If this switch is set, then @code{gnatfind} will output the parent type
12300 reference for each matching derived types.
12301
12302 @item ^-e^/EXPRESSIONS^
12303 @cindex @option{^-e^/EXPRESSIONS^} (@command{gnatfind})
12304 By default, @code{gnatfind} accept the simple regular expression set for
12305 @samp{pattern}. If this switch is set, then the pattern will be
12306 considered as full Unix-style regular expression.
12307
12308 @item ^-f^/FULL_PATHNAME^
12309 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatfind})
12310 If this switch is set, the output file names will be preceded by their
12311 directory (if the file was found in the search path). If this switch is
12312 not set, the directory will not be printed.
12313
12314 @item ^-g^/IGNORE_LOCALS^
12315 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatfind})
12316 If this switch is set, information is output only for library-level
12317 entities, ignoring local entities. The use of this switch may accelerate
12318 @code{gnatfind} and @code{gnatxref}.
12319
12320 @item -IDIR
12321 @cindex @option{-IDIR} (@command{gnatfind})
12322 Equivalent to @samp{-aODIR -aIDIR}.
12323
12324 @item -pFILE
12325 @cindex @option{-pFILE} (@command{gnatfind})
12326 Specify a project file (@pxref{GNAT Project Manager}) to use.
12327 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
12328 project file in the current directory.
12329
12330 If a project file is either specified or found by the tools, then the content
12331 of the source directory and object directory lines are added as if they
12332 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and
12333 @samp{^-aO^/OBJECT_SEARCH^}.
12334
12335 @item ^-r^/REFERENCES^
12336 @cindex @option{^-r^/REFERENCES^} (@command{gnatfind})
12337 By default, @code{gnatfind} will output only the information about the
12338 declaration, body or type completion of the entities. If this switch is
12339 set, the @code{gnatfind} will locate every reference to the entities in
12340 the files specified on the command line (or in every file in the search
12341 path if no file is given on the command line).
12342
12343 @item ^-s^/PRINT_LINES^
12344 @cindex @option{^-s^/PRINT_LINES^} (@command{gnatfind})
12345 If this switch is set, then @code{gnatfind} will output the content
12346 of the Ada source file lines were the entity was found.
12347
12348 @item ^-t^/TYPE_HIERARCHY^
12349 @cindex @option{^-t^/TYPE_HIERARCHY^} (@command{gnatfind})
12350 If this switch is set, then @code{gnatfind} will output the type hierarchy for
12351 the specified type. It act like -d option but recursively from parent
12352 type to parent type. When this switch is set it is not possible to
12353 specify more than one file.
12354
12355 @end table
12356
12357 @noindent
12358 All these switches may be in any order on the command line, and may even
12359 appear after the file names. They need not be separated by spaces, thus
12360 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
12361 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
12362
12363 As stated previously, gnatfind will search in every directory in the
12364 search path. You can force it to look only in the current directory if
12365 you specify @code{*} at the end of the command line.
12366
12367 @node Project Files for gnatxref and gnatfind
12368 @section Project Files for @command{gnatxref} and @command{gnatfind}
12369
12370 @noindent
12371 Project files allow a programmer to specify how to compile its
12372 application, where to find sources, etc.  These files are used
12373 @ifclear vms
12374 primarily by GPS, but they can also be used
12375 @end ifclear
12376 by the two tools
12377 @code{gnatxref} and @code{gnatfind}.
12378
12379 A project file name must end with @file{.gpr}. If a single one is
12380 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
12381 extract the information from it. If multiple project files are found, none of
12382 them is read, and you have to use the @samp{-p} switch to specify the one
12383 you want to use.
12384
12385 The following lines can be included, even though most of them have default
12386 values which can be used in most cases.
12387 The lines can be entered in any order in the file.
12388 Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
12389 each line. If you have multiple instances, only the last one is taken into
12390 account.
12391
12392 @table @code
12393 @item src_dir=DIR
12394 [default: @code{"^./^[]^"}]
12395 specifies a directory where to look for source files. Multiple @code{src_dir}
12396 lines can be specified and they will be searched in the order they
12397 are specified.
12398
12399 @item obj_dir=DIR
12400 [default: @code{"^./^[]^"}]
12401 specifies a directory where to look for object and library files. Multiple
12402 @code{obj_dir} lines can be specified, and they will be searched in the order
12403 they are specified
12404
12405 @item comp_opt=SWITCHES
12406 [default: @code{""}]
12407 creates a variable which can be referred to subsequently by using
12408 the @code{$@{comp_opt@}} notation. This is intended to store the default
12409 switches given to @command{gnatmake} and @command{gcc}.
12410
12411 @item bind_opt=SWITCHES
12412 [default: @code{""}]
12413 creates a variable which can be referred to subsequently by using
12414 the @samp{$@{bind_opt@}} notation. This is intended to store the default
12415 switches given to @command{gnatbind}.
12416
12417 @item link_opt=SWITCHES
12418 [default: @code{""}]
12419 creates a variable which can be referred to subsequently by using
12420 the @samp{$@{link_opt@}} notation. This is intended to store the default
12421 switches given to @command{gnatlink}.
12422
12423 @item main=EXECUTABLE
12424 [default: @code{""}]
12425 specifies the name of the executable for the application. This variable can
12426 be referred to in the following lines by using the @samp{$@{main@}} notation.
12427
12428 @ifset vms
12429 @item comp_cmd=COMMAND
12430 [default: @code{"GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"}]
12431 @end ifset
12432 @ifclear vms
12433 @item comp_cmd=COMMAND
12434 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
12435 @end ifclear
12436 specifies the command used to compile a single file in the application.
12437
12438 @ifset vms
12439 @item make_cmd=COMMAND
12440 [default: @code{"GNAT MAKE $@{main@}
12441 /SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@}
12442 /DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@}
12443 /BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"}]
12444 @end ifset
12445 @ifclear vms
12446 @item make_cmd=COMMAND
12447 [default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
12448 -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
12449 -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
12450 @end ifclear
12451 specifies the command used to recompile the whole application.
12452
12453 @item run_cmd=COMMAND
12454 [default: @code{"$@{main@}"}]
12455 specifies the command used to run the application.
12456
12457 @item debug_cmd=COMMAND
12458 [default: @code{"gdb $@{main@}"}]
12459 specifies the command used to debug the application
12460
12461 @end table
12462
12463 @noindent
12464 @command{gnatxref} and @command{gnatfind} only take into account the
12465 @code{src_dir} and @code{obj_dir} lines, and ignore the others.
12466
12467 @node Regular Expressions in gnatfind and gnatxref
12468 @section  Regular Expressions in @code{gnatfind} and @code{gnatxref}
12469
12470 @noindent
12471 As specified in the section about @command{gnatfind}, the pattern can be a
12472 regular expression. Actually, there are to set of regular expressions
12473 which are recognized by the program:
12474
12475 @table @code
12476 @item globbing patterns
12477 These are the most usual regular expression. They are the same that you
12478 generally used in a Unix shell command line, or in a DOS session.
12479
12480 Here is a more formal grammar:
12481 @smallexample
12482 @group
12483 @iftex
12484 @leftskip=.5cm
12485 @end iftex
12486 regexp ::= term
12487 term   ::= elmt            -- matches elmt
12488 term   ::= elmt elmt       -- concatenation (elmt then elmt)
12489 term   ::= *               -- any string of 0 or more characters
12490 term   ::= ?               -- matches any character
12491 term   ::= [char @{char@}]   -- matches any character listed
12492 term   ::= [char - char]   -- matches any character in range
12493 @end group
12494 @end smallexample
12495
12496 @item full regular expression
12497 The second set of regular expressions is much more powerful. This is the
12498 type of regular expressions recognized by utilities such a @file{grep}.
12499
12500 The following is the form of a regular expression, expressed in Ada
12501 reference manual style BNF is as follows
12502
12503 @smallexample
12504 @iftex
12505 @leftskip=.5cm
12506 @end iftex
12507 @group
12508 regexp ::= term @{| term@}   -- alternation (term or term @dots{})
12509
12510 term ::= item @{item@}       -- concatenation (item then item)
12511
12512 item ::= elmt              -- match elmt
12513 item ::= elmt *            -- zero or more elmt's
12514 item ::= elmt +            -- one or more elmt's
12515 item ::= elmt ?            -- matches elmt or nothing
12516 @end group
12517 @group
12518 elmt ::= nschar            -- matches given character
12519 elmt ::= [nschar @{nschar@}]   -- matches any character listed
12520 elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed
12521 elmt ::= [char - char]     -- matches chars in given range
12522 elmt ::= \ char            -- matches given character
12523 elmt ::= .                 -- matches any single character
12524 elmt ::= ( regexp )        -- parens used for grouping
12525
12526 char ::= any character, including special characters
12527 nschar ::= any character except ()[].*+?^^^
12528 @end group
12529 @end smallexample
12530
12531 Following are a few examples:
12532
12533 @table @samp
12534 @item abcde|fghi
12535 will match any of the two strings @samp{abcde} and @samp{fghi},
12536
12537 @item abc*d
12538 will match any string like @samp{abd}, @samp{abcd}, @samp{abccd},
12539 @samp{abcccd}, and so on,
12540
12541 @item [a-z]+
12542 will match any string which has only lowercase characters in it (and at
12543 least one character.
12544
12545 @end table
12546 @end table
12547
12548 @node Examples of gnatxref Usage
12549 @section Examples of @code{gnatxref} Usage
12550
12551 @subsection General Usage
12552
12553 @noindent
12554 For the following examples, we will consider the following units:
12555
12556 @smallexample @c ada
12557 @group
12558 @cartouche
12559 main.ads:
12560 1: with Bar;
12561 2: package Main is
12562 3:     procedure Foo (B : in Integer);
12563 4:     C : Integer;
12564 5: private
12565 6:     D : Integer;
12566 7: end Main;
12567
12568 main.adb:
12569 1: package body Main is
12570 2:     procedure Foo (B : in Integer) is
12571 3:     begin
12572 4:        C := B;
12573 5:        D := B;
12574 6:        Bar.Print (B);
12575 7:        Bar.Print (C);
12576 8:     end Foo;
12577 9: end Main;
12578
12579 bar.ads:
12580 1: package Bar is
12581 2:     procedure Print (B : Integer);
12582 3: end bar;
12583 @end cartouche
12584 @end group
12585 @end smallexample
12586
12587 @table @code
12588
12589 @noindent
12590 The first thing to do is to recompile your application (for instance, in
12591 that case just by doing a @samp{gnatmake main}, so that GNAT generates
12592 the cross-referencing information.
12593 You can then issue any of the following commands:
12594
12595 @item gnatxref main.adb
12596 @code{gnatxref} generates cross-reference information for main.adb
12597 and every unit 'with'ed by main.adb.
12598
12599 The output would be:
12600 @smallexample
12601 @iftex
12602 @leftskip=0cm
12603 @end iftex
12604 B                                                      Type: Integer
12605   Decl: bar.ads           2:22
12606 B                                                      Type: Integer
12607   Decl: main.ads          3:20
12608   Body: main.adb          2:20
12609   Ref:  main.adb          4:13     5:13     6:19
12610 Bar                                                    Type: Unit
12611   Decl: bar.ads           1:9
12612   Ref:  main.adb          6:8      7:8
12613        main.ads           1:6
12614 C                                                      Type: Integer
12615   Decl: main.ads          4:5
12616   Modi: main.adb          4:8
12617   Ref:  main.adb          7:19
12618 D                                                      Type: Integer
12619   Decl: main.ads          6:5
12620   Modi: main.adb          5:8
12621 Foo                                                    Type: Unit
12622   Decl: main.ads          3:15
12623   Body: main.adb          2:15
12624 Main                                                    Type: Unit
12625   Decl: main.ads          2:9
12626   Body: main.adb          1:14
12627 Print                                                   Type: Unit
12628   Decl: bar.ads           2:15
12629   Ref:  main.adb          6:12     7:12
12630 @end smallexample
12631
12632 @noindent
12633 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
12634 its body is in main.adb, line 1, column 14 and is not referenced any where.
12635
12636 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
12637 it referenced in main.adb, line 6 column 12 and line 7 column 12.
12638
12639 @item gnatxref package1.adb package2.ads
12640 @code{gnatxref} will generates cross-reference information for
12641 package1.adb, package2.ads and any other package 'with'ed by any
12642 of these.
12643
12644 @end table
12645
12646 @ifclear vms
12647 @subsection Using gnatxref with vi
12648
12649 @code{gnatxref} can generate a tags file output, which can be used
12650 directly from @command{vi}. Note that the standard version of @command{vi}
12651 will not work properly with overloaded symbols. Consider using another
12652 free implementation of @command{vi}, such as @command{vim}.
12653
12654 @smallexample
12655 $ gnatxref -v gnatfind.adb > tags
12656 @end smallexample
12657
12658 @noindent
12659 will generate the tags file for @code{gnatfind} itself (if the sources
12660 are in the search path!).
12661
12662 From @command{vi}, you can then use the command @samp{:tag @var{entity}}
12663 (replacing @var{entity} by whatever you are looking for), and vi will
12664 display a new file with the corresponding declaration of entity.
12665 @end ifclear
12666
12667 @node Examples of gnatfind Usage
12668 @section Examples of @code{gnatfind} Usage
12669
12670 @table @code
12671
12672 @item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb
12673 Find declarations for all entities xyz referenced at least once in
12674 main.adb. The references are search in every library file in the search
12675 path.
12676
12677 The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
12678 switch is set)
12679
12680 The output will look like:
12681 @smallexample
12682 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
12683 ^directory/^[directory]^main.adb:24:10: xyz <= body
12684 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
12685 @end smallexample
12686
12687 @noindent
12688 that is to say, one of the entities xyz found in main.adb is declared at
12689 line 12 of main.ads (and its body is in main.adb), and another one is
12690 declared at line 45 of foo.ads
12691
12692 @item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb
12693 This is the same command as the previous one, instead @code{gnatfind} will
12694 display the content of the Ada source file lines.
12695
12696 The output will look like:
12697
12698 @smallexample
12699 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
12700    procedure xyz;
12701 ^directory/^[directory]^main.adb:24:10: xyz <= body
12702    procedure xyz is
12703 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
12704    xyz : Integer;
12705 @end smallexample
12706
12707 @noindent
12708 This can make it easier to find exactly the location your are looking
12709 for.
12710
12711 @item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb
12712 Find references to all entities containing an x that are
12713 referenced on line 123 of main.ads.
12714 The references will be searched only in main.ads and foo.adb.
12715
12716 @item gnatfind main.ads:123
12717 Find declarations and bodies for all entities that are referenced on
12718 line 123 of main.ads.
12719
12720 This is the same as @code{gnatfind "*":main.adb:123}.
12721
12722 @item gnatfind ^mydir/^[mydir]^main.adb:123:45
12723 Find the declaration for the entity referenced at column 45 in
12724 line 123 of file main.adb in directory mydir. Note that it
12725 is usual to omit the identifier name when the column is given,
12726 since the column position identifies a unique reference.
12727
12728 The column has to be the beginning of the identifier, and should not
12729 point to any character in the middle of the identifier.
12730
12731 @end table
12732
12733 @c *********************************
12734 @node The GNAT Pretty-Printer gnatpp
12735 @chapter The GNAT Pretty-Printer @command{gnatpp}
12736 @findex gnatpp
12737 @cindex Pretty-Printer
12738
12739 @noindent
12740 ^The @command{gnatpp} tool^GNAT PRETTY^ is an ASIS-based utility
12741 for source reformatting / pretty-printing.
12742 It takes an Ada source file as input and generates a reformatted
12743 version as output.
12744 You can specify various style directives via switches; e.g.,
12745 identifier case conventions, rules of indentation, and comment layout.
12746
12747 To produce a reformatted file, @command{gnatpp} generates and uses the ASIS
12748 tree for the input source and thus requires the input to be syntactically and
12749 semantically legal.
12750 If this condition is not met, @command{gnatpp} will terminate with an
12751 error message; no output file will be generated.
12752
12753 If the source files presented to @command{gnatpp} contain
12754 preprocessing directives, then the output file will
12755 correspond to the generated source after all
12756 preprocessing is carried out. There is no way
12757 using @command{gnatpp} to obtain pretty printed files that
12758 include the preprocessing directives.
12759
12760 If the compilation unit
12761 contained in the input source depends semantically upon units located
12762 outside the current directory, you have to provide the source search path
12763 when invoking @command{gnatpp}, if these units are contained in files with
12764 names that do not follow the GNAT file naming rules, you have to provide
12765 the configuration file describing the corresponding naming scheme;
12766 see the description of the @command{gnatpp}
12767 switches below. Another possibility is to use a project file and to
12768 call @command{gnatpp} through the @command{gnat} driver
12769
12770 The @command{gnatpp} command has the form
12771
12772 @smallexample
12773 @c $ gnatpp @ovar{switches} @var{filename}
12774 @c Expanding @ovar macro inline (explanation in macro def comments)
12775 $ gnatpp @r{[}@var{switches}@r{]} @var{filename} @r{[}-cargs @var{gcc_switches}@r{]}
12776 @end smallexample
12777
12778 @noindent
12779 where
12780 @itemize @bullet
12781 @item
12782 @var{switches} is an optional sequence of switches defining such properties as
12783 the formatting rules, the source search path, and the destination for the
12784 output source file
12785
12786 @item
12787 @var{filename} is the name (including the extension) of the source file to
12788 reformat; ``wildcards'' or several file names on the same gnatpp command are
12789 allowed.  The file name may contain path information; it does not have to
12790 follow the GNAT file naming rules
12791
12792 @item
12793 @samp{@var{gcc_switches}} is a list of switches for
12794 @command{gcc}. They will be passed on to all compiler invocations made by
12795 @command{gnatelim} to generate the ASIS trees. Here you can provide
12796 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
12797 use the @option{-gnatec} switch to set the configuration file,
12798 use the @option{-gnat05} switch if sources should be compiled in
12799 Ada 2005 mode  etc.
12800 @end itemize
12801
12802 @menu
12803 * Switches for gnatpp::
12804 * Formatting Rules::
12805 @end menu
12806
12807 @node Switches for gnatpp
12808 @section Switches for @command{gnatpp}
12809
12810 @noindent
12811 The following subsections describe the various switches accepted by
12812 @command{gnatpp}, organized by category.
12813
12814 @ifclear vms
12815 You specify a switch by supplying a name and generally also a value.
12816 In many cases the values for a switch with a given name are incompatible with
12817 each other
12818 (for example the switch that controls the casing of a reserved word may have
12819 exactly one value: upper case, lower case, or
12820 mixed case) and thus exactly one such switch can be in effect for an
12821 invocation of @command{gnatpp}.
12822 If more than one is supplied, the last one is used.
12823 However, some values for the same switch are mutually compatible.
12824 You may supply several such switches to @command{gnatpp}, but then
12825 each must be specified in full, with both the name and the value.
12826 Abbreviated forms (the name appearing once, followed by each value) are
12827 not permitted.
12828 For example, to set
12829 the alignment of the assignment delimiter both in declarations and in
12830 assignment statements, you must write @option{-A2A3}
12831 (or @option{-A2 -A3}), but not @option{-A23}.
12832 @end ifclear
12833
12834 @ifset vms
12835 In many cases the set of options for a given qualifier are incompatible with
12836 each other (for example the qualifier that controls the casing of a reserved
12837 word may have exactly one option, which specifies either upper case, lower
12838 case, or mixed case), and thus exactly one such option can be in effect for
12839 an invocation of @command{gnatpp}.
12840 If more than one is supplied, the last one is used.
12841 However, some qualifiers have options that are mutually compatible,
12842 and then you may then supply several such options when invoking
12843 @command{gnatpp}.
12844 @end ifset
12845
12846 In most cases, it is obvious whether or not the
12847 ^values for a switch with a given name^options for a given qualifier^
12848 are compatible with each other.
12849 When the semantics might not be evident, the summaries below explicitly
12850 indicate the effect.
12851
12852 @menu
12853 * Alignment Control::
12854 * Casing Control::
12855 * Construct Layout Control::
12856 * General Text Layout Control::
12857 * Other Formatting Options::
12858 * Setting the Source Search Path::
12859 * Output File Control::
12860 * Other gnatpp Switches::
12861 @end menu
12862
12863 @node Alignment Control
12864 @subsection Alignment Control
12865 @cindex Alignment control in @command{gnatpp}
12866
12867 @noindent
12868 Programs can be easier to read if certain constructs are vertically aligned.
12869 By default all alignments are set ON.
12870 Through the @option{^-A0^/ALIGN=OFF^} switch you may reset the default to
12871 OFF, and then use one or more of the other
12872 ^@option{-A@var{n}} switches^@option{/ALIGN} options^
12873 to activate alignment for specific constructs.
12874
12875 @table @option
12876 @cindex @option{^-A@var{n}^/ALIGN^} (@command{gnatpp})
12877
12878 @ifset vms
12879 @item /ALIGN=ON
12880 Set all alignments to ON
12881 @end ifset
12882
12883 @item ^-A0^/ALIGN=OFF^
12884 Set all alignments to OFF
12885
12886 @item ^-A1^/ALIGN=COLONS^
12887 Align @code{:} in declarations
12888
12889 @item ^-A2^/ALIGN=DECLARATIONS^
12890 Align @code{:=} in initializations in declarations
12891
12892 @item ^-A3^/ALIGN=STATEMENTS^
12893 Align @code{:=} in assignment statements
12894
12895 @item ^-A4^/ALIGN=ARROWS^
12896 Align @code{=>} in associations
12897
12898 @item ^-A5^/ALIGN=COMPONENT_CLAUSES^
12899 Align @code{at} keywords in the component clauses in record
12900 representation clauses
12901 @end table
12902
12903 @noindent
12904 The @option{^-A^/ALIGN^} switches are mutually compatible; any combination
12905 is allowed.
12906
12907 @node Casing Control
12908 @subsection Casing Control
12909 @cindex Casing control in @command{gnatpp}
12910
12911 @noindent
12912 @command{gnatpp} allows you to specify the casing for reserved words,
12913 pragma names, attribute designators and identifiers.
12914 For identifiers you may define a
12915 general rule for name casing but also override this rule
12916 via a set of dictionary files.
12917
12918 Three types of casing are supported: lower case, upper case, and mixed case.
12919 Lower and upper case are self-explanatory (but since some letters in
12920 Latin1 and other GNAT-supported character sets
12921 exist only in lower-case form, an upper case conversion will have no
12922 effect on them.)
12923 ``Mixed case'' means that the first letter, and also each letter immediately
12924 following an underscore, are converted to their uppercase forms;
12925 all the other letters are converted to their lowercase forms.
12926
12927 @table @option
12928 @cindex @option{^-a@var{x}^/ATTRIBUTE^} (@command{gnatpp})
12929 @item ^-aL^/ATTRIBUTE_CASING=LOWER_CASE^
12930 Attribute designators are lower case
12931
12932 @item ^-aU^/ATTRIBUTE_CASING=UPPER_CASE^
12933 Attribute designators are upper case
12934
12935 @item ^-aM^/ATTRIBUTE_CASING=MIXED_CASE^
12936 Attribute designators are mixed case (this is the default)
12937
12938 @cindex @option{^-k@var{x}^/KEYWORD_CASING^} (@command{gnatpp})
12939 @item ^-kL^/KEYWORD_CASING=LOWER_CASE^
12940 Keywords (technically, these are known in Ada as @emph{reserved words}) are
12941 lower case (this is the default)
12942
12943 @item ^-kU^/KEYWORD_CASING=UPPER_CASE^
12944 Keywords are upper case
12945
12946 @cindex @option{^-n@var{x}^/NAME_CASING^} (@command{gnatpp})
12947 @item ^-nD^/NAME_CASING=AS_DECLARED^
12948 Name casing for defining occurrences are as they appear in the source file
12949 (this is the default)
12950
12951 @item ^-nU^/NAME_CASING=UPPER_CASE^
12952 Names are in upper case
12953
12954 @item ^-nL^/NAME_CASING=LOWER_CASE^
12955 Names are in lower case
12956
12957 @item ^-nM^/NAME_CASING=MIXED_CASE^
12958 Names are in mixed case
12959
12960 @cindex @option{^-p@var{x}^/PRAGMA_CASING^} (@command{gnatpp})
12961 @item ^-pL^/PRAGMA_CASING=LOWER_CASE^
12962 Pragma names are lower case
12963
12964 @item ^-pU^/PRAGMA_CASING=UPPER_CASE^
12965 Pragma names are upper case
12966
12967 @item ^-pM^/PRAGMA_CASING=MIXED_CASE^
12968 Pragma names are mixed case (this is the default)
12969
12970 @item ^-D@var{file}^/DICTIONARY=@var{file}^
12971 @cindex @option{^-D^/DICTIONARY^} (@command{gnatpp})
12972 Use @var{file} as a @emph{dictionary file} that defines
12973 the casing for a set of specified names,
12974 thereby overriding the effect on these names by
12975 any explicit or implicit
12976 ^-n^/NAME_CASING^ switch.
12977 To supply more than one dictionary file,
12978 use ^several @option{-D} switches^a list of files as options^.
12979
12980 @noindent
12981 @option{gnatpp} implicitly uses a @emph{default dictionary file}
12982 to define the casing for the Ada predefined names and
12983 the names declared in the GNAT libraries.
12984
12985 @item ^-D-^/SPECIFIC_CASING^
12986 @cindex @option{^-D-^/SPECIFIC_CASING^} (@command{gnatpp})
12987 Do not use the default dictionary file;
12988 instead, use the casing
12989 defined by a @option{^-n^/NAME_CASING^} switch and any explicit
12990 dictionary file(s)
12991 @end table
12992
12993 @noindent
12994 The structure of a dictionary file, and details on the conventions
12995 used in the default dictionary file, are defined in @ref{Name Casing}.
12996
12997 The @option{^-D-^/SPECIFIC_CASING^} and
12998 @option{^-D@var{file}^/DICTIONARY=@var{file}^} switches are mutually
12999 compatible.
13000
13001 @node Construct Layout Control
13002 @subsection Construct Layout Control
13003 @cindex Layout control in @command{gnatpp}
13004
13005 @noindent
13006 This group of @command{gnatpp} switches controls the layout of comments and
13007 complex syntactic constructs.  See @ref{Formatting Comments} for details
13008 on their effect.
13009
13010 @table @option
13011 @cindex @option{^-c@var{n}^/COMMENTS_LAYOUT^} (@command{gnatpp})
13012 @item ^-c0^/COMMENTS_LAYOUT=UNTOUCHED^
13013 All the comments remain unchanged
13014
13015 @item ^-c1^/COMMENTS_LAYOUT=DEFAULT^
13016 GNAT-style comment line indentation (this is the default).
13017
13018 @item ^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^
13019 Reference-manual comment line indentation.
13020
13021 @item ^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^
13022 GNAT-style comment beginning
13023
13024 @item ^-c4^/COMMENTS_LAYOUT=REFORMAT^
13025 Reformat comment blocks
13026
13027 @item ^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^
13028 Keep unchanged special form comments
13029
13030 Reformat comment blocks
13031
13032 @cindex @option{^-l@var{n}^/CONSTRUCT_LAYOUT^} (@command{gnatpp})
13033 @item ^-l1^/CONSTRUCT_LAYOUT=GNAT^
13034 GNAT-style layout (this is the default)
13035
13036 @item ^-l2^/CONSTRUCT_LAYOUT=COMPACT^
13037 Compact layout
13038
13039 @item ^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^
13040 Uncompact layout
13041
13042 @cindex @option{^-N^/NOTABS^} (@command{gnatpp})
13043 @item ^-N^/NOTABS^
13044 All the VT characters are removed from the comment text. All the HT characters
13045 are expanded with the sequences of space characters to get to the next tab
13046 stops.
13047
13048 @cindex @option{^--no-separate-is^/NO_SEPARATE_IS^} (@command{gnatpp})
13049 @item ^--no-separate-is^/NO_SEPARATE_IS^
13050 Do not place the keyword @code{is} on a separate line in a subprogram body in
13051 case if the spec occupies more then one line.
13052
13053 @cindex @option{^--separate-label^/SEPARATE_LABEL^} (@command{gnatpp})
13054 @item ^--separate-label^/SEPARATE_LABEL^
13055 Place statement label(s) on a separate line, with the following statement
13056 on the next line.
13057
13058 @cindex @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} (@command{gnatpp})
13059 @item ^--separate-loop-then^/SEPARATE_LOOP_THEN^
13060 Place the keyword @code{loop} in FOR and WHILE loop statements and the
13061 keyword @code{then} in IF statements on a separate line.
13062
13063 @cindex @option{^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^} (@command{gnatpp})
13064 @item ^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^
13065 Do not place the keyword @code{loop} in FOR and WHILE loop statements and the
13066 keyword @code{then} in IF statements on a separate line. This option is
13067 incompatible with @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} option.
13068
13069 @cindex @option{^--use-on-new-line^/USE_ON_NEW_LINE^} (@command{gnatpp})
13070 @item ^--use-on-new-line^/USE_ON_NEW_LINE^
13071 Start each USE clause in a context clause from a separate line.
13072
13073 @cindex @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^} (@command{gnatpp})
13074 @item ^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^
13075 Use a separate line for a loop or block statement name, but do not use an extra
13076 indentation level for the statement itself.
13077
13078 @end table
13079
13080 @ifclear vms
13081 @noindent
13082 The @option{-c1} and @option{-c2} switches are incompatible.
13083 The @option{-c3} and @option{-c4} switches are compatible with each other and
13084 also with @option{-c1} and @option{-c2}. The @option{-c0} switch disables all
13085 the other comment formatting switches.
13086
13087 The @option{-l1}, @option{-l2}, and @option{-l3} switches are incompatible.
13088 @end ifclear
13089
13090 @ifset vms
13091 @noindent
13092 For the @option{/COMMENTS_LAYOUT} qualifier:
13093 @itemize @bullet
13094 @item
13095 The @option{DEFAULT} and @option{STANDARD_INDENT} options are incompatible.
13096 @item
13097 The @option{GNAT_BEGINNING} and @option{REFORMAT} options are compatible with
13098 each other and also with @option{DEFAULT} and @option{STANDARD_INDENT}.
13099 @end itemize
13100
13101 @noindent
13102 The @option{GNAT}, @option{COMPACT}, and @option{UNCOMPACT} options for the
13103 @option{/CONSTRUCT_LAYOUT} qualifier are incompatible.
13104 @end ifset
13105
13106 @node General Text Layout Control
13107 @subsection General Text Layout Control
13108
13109 @noindent
13110 These switches allow control over line length and indentation.
13111
13112 @table @option
13113 @item ^-M@var{nnn}^/LINE_LENGTH_MAX=@var{nnn}^
13114 @cindex @option{^-M^/LINE_LENGTH^} (@command{gnatpp})
13115 Maximum line length, @var{nnn} from 32@dots{}256, the default value is 79
13116
13117 @item ^-i@var{nnn}^/INDENTATION_LEVEL=@var{nnn}^
13118 @cindex @option{^-i^/INDENTATION_LEVEL^} (@command{gnatpp})
13119 Indentation level, @var{nnn} from 1@dots{}9, the default value is 3
13120
13121 @item ^-cl@var{nnn}^/CONTINUATION_INDENT=@var{nnn}^
13122 @cindex @option{^-cl^/CONTINUATION_INDENT^} (@command{gnatpp})
13123 Indentation level for continuation lines (relative to the line being
13124 continued), @var{nnn} from 1@dots{}9.
13125 The default
13126 value is one less then the (normal) indentation level, unless the
13127 indentation is set to 1 (in which case the default value for continuation
13128 line indentation is also 1)
13129 @end table
13130
13131 @node Other Formatting Options
13132 @subsection Other Formatting Options
13133
13134 @noindent
13135 These switches control the inclusion of missing end/exit labels, and
13136 the indentation level in @b{case} statements.
13137
13138 @table @option
13139 @item ^-e^/NO_MISSED_LABELS^
13140 @cindex @option{^-e^/NO_MISSED_LABELS^} (@command{gnatpp})
13141 Do not insert missing end/exit labels. An end label is the name of
13142 a construct that may optionally be repeated at the end of the
13143 construct's declaration;
13144 e.g., the names of packages, subprograms, and tasks.
13145 An exit label is the name of a loop that may appear as target
13146 of an exit statement within the loop.
13147 By default, @command{gnatpp} inserts these end/exit labels when
13148 they are absent from the original source. This option suppresses such
13149 insertion, so that the formatted source reflects the original.
13150
13151 @item ^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^
13152 @cindex @option{^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^} (@command{gnatpp})
13153 Insert a Form Feed character after a pragma Page.
13154
13155 @item ^-T@var{nnn}^/MAX_INDENT=@var{nnn}^
13156 @cindex @option{^-T^/MAX_INDENT^} (@command{gnatpp})
13157 Do not use an additional indentation level for @b{case} alternatives
13158 and variants if there are @var{nnn} or more (the default
13159 value is 10).
13160 If @var{nnn} is 0, an additional indentation level is
13161 used for @b{case} alternatives and variants regardless of their number.
13162 @end table
13163
13164 @node Setting the Source Search Path
13165 @subsection Setting the Source Search Path
13166
13167 @noindent
13168 To define the search path for the input source file, @command{gnatpp}
13169 uses the same switches as the GNAT compiler, with the same effects.
13170
13171 @table @option
13172 @item ^-I^/SEARCH=^@var{dir}
13173 @cindex @option{^-I^/SEARCH^} (@code{gnatpp})
13174 The same as the corresponding gcc switch
13175
13176 @item ^-I-^/NOCURRENT_DIRECTORY^
13177 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatpp})
13178 The same as the corresponding gcc switch
13179
13180 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE^=@var{path}
13181 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@code{gnatpp})
13182 The same as the corresponding gcc switch
13183
13184 @item ^--RTS^/RUNTIME_SYSTEM^=@var{path}
13185 @cindex @option{^--RTS^/RUNTIME_SYSTEM^} (@code{gnatpp})
13186 The same as the corresponding gcc switch
13187
13188 @end table
13189
13190 @node Output File Control
13191 @subsection Output File Control
13192
13193 @noindent
13194 By default the output is sent to the file whose name is obtained by appending
13195 the ^@file{.pp}^@file{$PP}^ suffix to the name of the input file
13196 (if the file with this name already exists, it is unconditionally overwritten).
13197 Thus if the input file is @file{^my_ada_proc.adb^MY_ADA_PROC.ADB^} then
13198 @command{gnatpp} will produce @file{^my_ada_proc.adb.pp^MY_ADA_PROC.ADB$PP^}
13199 as output file.
13200 The output may be redirected by the following switches:
13201
13202 @table @option
13203 @item ^-pipe^/STANDARD_OUTPUT^
13204 @cindex @option{^-pipe^/STANDARD_OUTPUT^} (@code{gnatpp})
13205 Send the output to @code{Standard_Output}
13206
13207 @item ^-o @var{output_file}^/OUTPUT=@var{output_file}^
13208 @cindex @option{^-o^/OUTPUT^} (@code{gnatpp})
13209 Write the output into @var{output_file}.
13210 If @var{output_file} already exists, @command{gnatpp} terminates without
13211 reading or processing the input file.
13212
13213 @item ^-of ^/FORCED_OUTPUT=^@var{output_file}
13214 @cindex @option{^-of^/FORCED_OUTPUT^} (@code{gnatpp})
13215 Write the output into @var{output_file}, overwriting the existing file
13216 (if one is present).
13217
13218 @item ^-r^/REPLACE^
13219 @cindex @option{^-r^/REPLACE^} (@code{gnatpp})
13220 Replace the input source file with the reformatted output, and copy the
13221 original input source into the file whose name is obtained by appending the
13222 ^@file{.npp}^@file{$NPP}^ suffix to the name of the input file.
13223 If a file with this name already exists, @command{gnatpp} terminates without
13224 reading or processing the input file.
13225
13226 @item ^-rf^/OVERRIDING_REPLACE^
13227 @cindex @option{^-rf^/OVERRIDING_REPLACE^} (@code{gnatpp})
13228 Like @option{^-r^/REPLACE^} except that if the file with the specified name
13229 already exists, it is overwritten.
13230
13231 @item ^-rnb^/REPLACE_NO_BACKUP^
13232 @cindex @option{^-rnb^/REPLACE_NO_BACKUP^} (@code{gnatpp})
13233 Replace the input source file with the reformatted output without
13234 creating any backup copy of the input source.
13235
13236 @item ^--eol=@var{xxx}^/END_OF_LINE=@var{xxx}^
13237 @cindex @option{^--eol^/END_OF_LINE^} (@code{gnatpp})
13238 Specifies the format of the reformatted output file. The @var{xxx}
13239 ^string specified with the switch^option^ may be either
13240 @itemize @bullet
13241 @item ``@option{^dos^DOS^}'' MS DOS style, lines end with CR LF characters
13242 @item ``@option{^crlf^CRLF^}''
13243 the same as @option{^crlf^CRLF^}
13244 @item ``@option{^unix^UNIX^}'' UNIX style, lines end with LF character
13245 @item ``@option{^lf^LF^}''
13246 the same as @option{^unix^UNIX^}
13247 @end itemize
13248
13249 @item ^-W^/RESULT_ENCODING=^@var{e}
13250 @cindex @option{^-W^/RESULT_ENCODING=^} (@command{gnatpp})
13251 Specify the wide character encoding method used to write the code in the
13252 result file
13253 @var{e} is one of the following:
13254
13255 @itemize @bullet
13256
13257 @item ^h^HEX^
13258 Hex encoding
13259
13260 @item ^u^UPPER^
13261 Upper half encoding
13262
13263 @item ^s^SHIFT_JIS^
13264 Shift/JIS encoding
13265
13266 @item ^e^EUC^
13267 EUC encoding
13268
13269 @item ^8^UTF8^
13270 UTF-8 encoding
13271
13272 @item ^b^BRACKETS^
13273 Brackets encoding (default value)
13274 @end itemize
13275
13276 @end table
13277
13278 @noindent
13279 Options @option{^-pipe^/STANDARD_OUTPUT^},
13280 @option{^-o^/OUTPUT^} and
13281 @option{^-of^/FORCED_OUTPUT^} are allowed only if the call to gnatpp
13282 contains only one file to reformat.
13283 Option
13284 @option{^--eol^/END_OF_LINE^}
13285 and
13286 @option{^-W^/RESULT_ENCODING^}
13287 cannot be used together
13288 with @option{^-pipe^/STANDARD_OUTPUT^} option.
13289
13290 @node Other gnatpp Switches
13291 @subsection Other @code{gnatpp} Switches
13292
13293 @noindent
13294 The additional @command{gnatpp} switches are defined in this subsection.
13295
13296 @table @option
13297 @item ^-files @var{filename}^/FILES=@var{filename}^
13298 @cindex @option{^-files^/FILES^} (@code{gnatpp})
13299 Take the argument source files from the specified file. This file should be an
13300 ordinary text file containing file names separated by spaces or
13301 line breaks. You can use this switch more than once in the same call to
13302 @command{gnatpp}. You also can combine this switch with an explicit list of
13303 files.
13304
13305 @item ^-v^/VERBOSE^
13306 @cindex @option{^-v^/VERBOSE^} (@code{gnatpp})
13307 Verbose mode;
13308 @command{gnatpp} generates version information and then
13309 a trace of the actions it takes to produce or obtain the ASIS tree.
13310
13311 @item ^-w^/WARNINGS^
13312 @cindex @option{^-w^/WARNINGS^} (@code{gnatpp})
13313 Warning mode;
13314 @command{gnatpp} generates a warning whenever it cannot provide
13315 a required layout in the result source.
13316 @end table
13317
13318 @node Formatting Rules
13319 @section Formatting Rules
13320
13321 @noindent
13322 The following subsections show how @command{gnatpp} treats ``white space'',
13323 comments, program layout, and name casing.
13324 They provide the detailed descriptions of the switches shown above.
13325
13326 @menu
13327 * White Space and Empty Lines::
13328 * Formatting Comments::
13329 * Construct Layout::
13330 * Name Casing::
13331 @end menu
13332
13333 @node White Space and Empty Lines
13334 @subsection White Space and Empty Lines
13335
13336 @noindent
13337 @command{gnatpp} does not have an option to control space characters.
13338 It will add or remove spaces according to the style illustrated by the
13339 examples in the @cite{Ada Reference Manual}.
13340
13341 The only format effectors
13342 (see @cite{Ada Reference Manual}, paragraph 2.1(13))
13343 that will appear in the output file are platform-specific line breaks,
13344 and also format effectors within (but not at the end of) comments.
13345 In particular, each horizontal tab character that is not inside
13346 a comment will be treated as a space and thus will appear in the
13347 output file as zero or more spaces depending on
13348 the reformatting of the line in which it appears.
13349 The only exception is a Form Feed character, which is inserted after a
13350 pragma @code{Page} when @option{-ff} is set.
13351
13352 The output file will contain no lines with trailing ``white space'' (spaces,
13353 format effectors).
13354
13355 Empty lines in the original source are preserved
13356 only if they separate declarations or statements.
13357 In such contexts, a
13358 sequence of two or more empty lines is replaced by exactly one empty line.
13359 Note that a blank line will be removed if it separates two ``comment blocks''
13360 (a comment block is a sequence of whole-line comments).
13361 In order to preserve a visual separation between comment blocks, use an
13362 ``empty comment'' (a line comprising only hyphens) rather than an empty line.
13363 Likewise, if for some reason you wish to have a sequence of empty lines,
13364 use a sequence of empty comments instead.
13365
13366 @node Formatting Comments
13367 @subsection Formatting Comments
13368
13369 @noindent
13370 Comments in Ada code are of two kinds:
13371 @itemize @bullet
13372 @item
13373 a @emph{whole-line comment}, which appears by itself (possibly preceded by
13374 ``white space'') on a line
13375
13376 @item
13377 an @emph{end-of-line comment}, which follows some other Ada lexical element
13378 on the same line.
13379 @end itemize
13380
13381 @noindent
13382 The indentation of a whole-line comment is that of either
13383 the preceding or following line in
13384 the formatted source, depending on switch settings as will be described below.
13385
13386 For an end-of-line comment, @command{gnatpp} leaves the same number of spaces
13387 between the end of the preceding Ada lexical element and the beginning
13388 of the comment as appear in the original source,
13389 unless either the comment has to be split to
13390 satisfy the line length limitation, or else the next line contains a
13391 whole line comment that is considered a continuation of this end-of-line
13392 comment (because it starts at the same position).
13393 In the latter two
13394 cases, the start of the end-of-line comment is moved right to the nearest
13395 multiple of the indentation level.
13396 This may result in a ``line overflow'' (the right-shifted comment extending
13397 beyond the maximum line length), in which case the comment is split as
13398 described below.
13399
13400 There is a difference between @option{^-c1^/COMMENTS_LAYOUT=DEFAULT^}
13401 (GNAT-style comment line indentation)
13402 and @option{^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^}
13403 (reference-manual comment line indentation).
13404 With reference-manual style, a whole-line comment is indented as if it
13405 were a declaration or statement at the same place
13406 (i.e., according to the indentation of the preceding line(s)).
13407 With GNAT style, a whole-line comment that is immediately followed by an
13408 @b{if} or @b{case} statement alternative, a record variant, or the reserved
13409 word @b{begin}, is indented based on the construct that follows it.
13410
13411 For example:
13412 @smallexample @c ada
13413 @cartouche
13414 if A then
13415     null;
13416        -- some comment
13417 else
13418    null;
13419 end if;
13420 @end cartouche
13421 @end smallexample
13422
13423 @noindent
13424 Reference-manual indentation produces:
13425
13426 @smallexample @c ada
13427 @cartouche
13428 if A then
13429    null;
13430    --  some comment
13431 else
13432    null;
13433 end if;
13434 @end cartouche
13435 @end smallexample
13436
13437 @noindent
13438 while GNAT-style indentation produces:
13439
13440 @smallexample @c ada
13441 @cartouche
13442 if A then
13443    null;
13444 --  some comment
13445 else
13446    null;
13447 end if;
13448 @end cartouche
13449 @end smallexample
13450
13451 @noindent
13452 The @option{^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^} switch
13453 (GNAT style comment beginning) has the following
13454 effect:
13455
13456 @itemize @bullet
13457 @item
13458 For each whole-line comment that does not end with two hyphens,
13459 @command{gnatpp} inserts spaces if necessary after the starting two hyphens
13460 to ensure that there are at least two spaces between these hyphens and the
13461 first non-blank character of the comment.
13462 @end itemize
13463
13464 @noindent
13465 For an end-of-line comment, if in the original source the next line is a
13466 whole-line comment that starts at the same position
13467 as the end-of-line comment,
13468 then the whole-line comment (and all whole-line comments
13469 that follow it and that start at the same position)
13470 will start at this position in the output file.
13471
13472 @noindent
13473 That is, if in the original source we have:
13474
13475 @smallexample @c ada
13476 @cartouche
13477 begin
13478 A := B + C;            --  B must be in the range Low1..High1
13479                        --  C must be in the range Low2..High2
13480              --B+C will be in the range Low1+Low2..High1+High2
13481 X := X + 1;
13482 @end cartouche
13483 @end smallexample
13484
13485 @noindent
13486 Then in the formatted source we get
13487
13488 @smallexample @c ada
13489 @cartouche
13490 begin
13491    A := B + C;            --  B must be in the range Low1..High1
13492                           --  C must be in the range Low2..High2
13493    --  B+C will be in the range Low1+Low2..High1+High2
13494    X := X + 1;
13495 @end cartouche
13496 @end smallexample
13497
13498 @noindent
13499 A comment that exceeds the line length limit will be split.
13500 Unless switch
13501 @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} (reformat comment blocks) is set and
13502 the line belongs to a reformattable block, splitting the line generates a
13503 @command{gnatpp} warning.
13504 The @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} switch specifies that whole-line
13505 comments may be reformatted in typical
13506 word processor style (that is, moving words between lines and putting as
13507 many words in a line as possible).
13508
13509 @noindent
13510 The @option{^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^} switch specifies, that comments
13511 that has a special format (that is, a character that is neither a letter nor digit
13512 not white space nor line break immediately following the leading @code{--} of
13513 the comment) should be without any change moved from the argument source
13514 into reformatted source. This switch allows to preserve comments that are used
13515 as a special marks in the code (e.g.@: SPARK annotation).
13516
13517 @node Construct Layout
13518 @subsection Construct Layout
13519
13520 @noindent
13521 In several cases the suggested layout in the Ada Reference Manual includes
13522 an extra level of indentation that many programmers prefer to avoid. The
13523 affected cases include:
13524
13525 @itemize @bullet
13526
13527 @item Record type declaration (RM 3.8)
13528
13529 @item Record representation clause (RM 13.5.1)
13530
13531 @item Loop statement in case if a loop has a statement identifier (RM 5.6)
13532
13533 @item Block statement in case if a block has a statement identifier (RM 5.6)
13534 @end itemize
13535
13536 @noindent
13537 In compact mode (when GNAT style layout or compact layout is set),
13538 the pretty printer uses one level of indentation instead
13539 of two. This is achieved in the record definition and record representation
13540 clause cases by putting the @code{record} keyword on the same line as the
13541 start of the declaration or representation clause, and in the block and loop
13542 case by putting the block or loop header on the same line as the statement
13543 identifier.
13544
13545 @noindent
13546 The difference between GNAT style @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^}
13547 and compact @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^}
13548 layout on the one hand, and uncompact layout
13549 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} on the other hand,
13550 can be illustrated by the following examples:
13551
13552 @iftex
13553 @cartouche
13554 @multitable @columnfractions .5 .5
13555 @item @i{GNAT style, compact layout} @tab @i{Uncompact layout}
13556
13557 @item
13558 @smallexample @c ada
13559 type q is record
13560    a : integer;
13561    b : integer;
13562 end record;
13563 @end smallexample
13564 @tab
13565 @smallexample @c ada
13566 type q is
13567    record
13568       a : integer;
13569       b : integer;
13570    end record;
13571 @end smallexample
13572
13573 @item
13574 @smallexample @c ada
13575 for q use record
13576    a at 0 range  0 .. 31;
13577    b at 4 range  0 .. 31;
13578 end record;
13579 @end smallexample
13580 @tab
13581 @smallexample @c ada
13582 for q use
13583    record
13584       a at 0 range  0 .. 31;
13585       b at 4 range  0 .. 31;
13586    end record;
13587 @end smallexample
13588
13589 @item
13590 @smallexample @c ada
13591 Block : declare
13592    A : Integer := 3;
13593 begin
13594    Proc (A, A);
13595 end Block;
13596 @end smallexample
13597 @tab
13598 @smallexample @c ada
13599 Block :
13600    declare
13601       A : Integer := 3;
13602    begin
13603       Proc (A, A);
13604    end Block;
13605 @end smallexample
13606
13607 @item
13608 @smallexample @c ada
13609 Clear : for J in 1 .. 10 loop
13610    A (J) := 0;
13611 end loop Clear;
13612 @end smallexample
13613 @tab
13614 @smallexample @c ada
13615 Clear :
13616    for J in 1 .. 10 loop
13617       A (J) := 0;
13618    end loop Clear;
13619 @end smallexample
13620 @end multitable
13621 @end cartouche
13622 @end iftex
13623
13624 @ifnottex
13625 @smallexample
13626 @cartouche
13627 GNAT style, compact layout              Uncompact layout
13628
13629 type q is record                        type q is
13630    a : integer;                            record
13631    b : integer;                               a : integer;
13632 end record;                                   b : integer;
13633                                            end record;
13634
13635 for q use record                        for q use
13636    a at 0 range  0 .. 31;                  record
13637    b at 4 range  0 .. 31;                     a at 0 range  0 .. 31;
13638 end record;                                   b at 4 range  0 .. 31;
13639                                            end record;
13640
13641 Block : declare                         Block :
13642    A : Integer := 3;                       declare
13643 begin                                         A : Integer := 3;
13644    Proc (A, A);                            begin
13645 end Block;                                    Proc (A, A);
13646                                            end Block;
13647
13648 Clear : for J in 1 .. 10 loop           Clear :
13649    A (J) := 0;                             for J in 1 .. 10 loop
13650 end loop Clear;                               A (J) := 0;
13651                                            end loop Clear;
13652 @end cartouche
13653 @end smallexample
13654 @end ifnottex
13655
13656 @noindent
13657 A further difference between GNAT style layout and compact layout is that
13658 GNAT style layout inserts empty lines as separation for
13659 compound statements, return statements and bodies.
13660
13661 Note that the layout specified by
13662 @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^}
13663 for named block and loop statements overrides the layout defined by these
13664 constructs by @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^},
13665 @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^} or
13666 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} option.
13667
13668 @node Name Casing
13669 @subsection Name Casing
13670
13671 @noindent
13672 @command{gnatpp} always converts the usage occurrence of a (simple) name to
13673 the same casing as the corresponding defining identifier.
13674
13675 You control the casing for defining occurrences via the
13676 @option{^-n^/NAME_CASING^} switch.
13677 @ifclear vms
13678 With @option{-nD} (``as declared'', which is the default),
13679 @end ifclear
13680 @ifset vms
13681 With @option{/NAME_CASING=AS_DECLARED}, which is the default,
13682 @end ifset
13683 defining occurrences appear exactly as in the source file
13684 where they are declared.
13685 The other ^values for this switch^options for this qualifier^ ---
13686 @option{^-nU^UPPER_CASE^},
13687 @option{^-nL^LOWER_CASE^},
13688 @option{^-nM^MIXED_CASE^} ---
13689 result in
13690 ^upper, lower, or mixed case, respectively^the corresponding casing^.
13691 If @command{gnatpp} changes the casing of a defining
13692 occurrence, it analogously changes the casing of all the
13693 usage occurrences of this name.
13694
13695 If the defining occurrence of a name is not in the source compilation unit
13696 currently being processed by @command{gnatpp}, the casing of each reference to
13697 this name is changed according to the value of the @option{^-n^/NAME_CASING^}
13698 switch (subject to the dictionary file mechanism described below).
13699 Thus @command{gnatpp} acts as though the @option{^-n^/NAME_CASING^} switch
13700 had affected the
13701 casing for the defining occurrence of the name.
13702
13703 Some names may need to be spelled with casing conventions that are not
13704 covered by the upper-, lower-, and mixed-case transformations.
13705 You can arrange correct casing by placing such names in a
13706 @emph{dictionary file},
13707 and then supplying a @option{^-D^/DICTIONARY^} switch.
13708 The casing of names from dictionary files overrides
13709 any @option{^-n^/NAME_CASING^} switch.
13710
13711 To handle the casing of Ada predefined names and the names from GNAT libraries,
13712 @command{gnatpp} assumes a default dictionary file.
13713 The name of each predefined entity is spelled with the same casing as is used
13714 for the entity in the @cite{Ada Reference Manual}.
13715 The name of each entity in the GNAT libraries is spelled with the same casing
13716 as is used in the declaration of that entity.
13717
13718 The @w{@option{^-D-^/SPECIFIC_CASING^}} switch suppresses the use of the
13719 default dictionary file.
13720 Instead, the casing for predefined and GNAT-defined names will be established
13721 by the @option{^-n^/NAME_CASING^} switch or explicit dictionary files.
13722 For example, by default the names @code{Ada.Text_IO} and @code{GNAT.OS_Lib}
13723 will appear as just shown,
13724 even in the presence of a @option{^-nU^/NAME_CASING=UPPER_CASE^} switch.
13725 To ensure that even such names are rendered in uppercase,
13726 additionally supply the @w{@option{^-D-^/SPECIFIC_CASING^}} switch
13727 (or else, less conveniently, place these names in upper case in a dictionary
13728 file).
13729
13730 A dictionary file is
13731 a plain text file; each line in this file can be either a blank line
13732 (containing only space characters and ASCII.HT characters), an Ada comment
13733 line, or the specification of exactly one @emph{casing schema}.
13734
13735 A casing schema is a string that has the following syntax:
13736
13737 @smallexample
13738 @cartouche
13739   @var{casing_schema} ::= @var{identifier} | *@var{simple_identifier}*
13740
13741   @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
13742 @end cartouche
13743 @end smallexample
13744
13745 @noindent
13746 (See @cite{Ada Reference Manual}, Section 2.3) for the definition of the
13747 @var{identifier} lexical element and the @var{letter_or_digit} category.)
13748
13749 The casing schema string can be followed by white space and/or an Ada-style
13750 comment; any amount of white space is allowed before the string.
13751
13752 If a dictionary file is passed as
13753 @ifclear vms
13754 the value of a @option{-D@var{file}} switch
13755 @end ifclear
13756 @ifset vms
13757 an option to the @option{/DICTIONARY} qualifier
13758 @end ifset
13759 then for every
13760 simple name and every identifier, @command{gnatpp} checks if the dictionary
13761 defines the casing for the name or for some of its parts (the term ``subword''
13762 is used below to denote the part of a name which is delimited by ``_'' or by
13763 the beginning or end of the word and which does not contain any ``_'' inside):
13764
13765 @itemize @bullet
13766 @item
13767 if the whole name is in the dictionary, @command{gnatpp} uses for this name
13768 the casing defined by the dictionary; no subwords are checked for this word
13769
13770 @item
13771 for every subword @command{gnatpp} checks if the dictionary contains the
13772 corresponding string of the form @code{*@var{simple_identifier}*},
13773 and if it does, the casing of this @var{simple_identifier} is used
13774 for this subword
13775
13776 @item
13777 if the whole name does not contain any ``_'' inside, and if for this name
13778 the dictionary contains two entries - one of the form @var{identifier},
13779 and another - of the form *@var{simple_identifier}*, then the first one
13780 is applied to define the casing of this name
13781
13782 @item
13783 if more than one dictionary file is passed as @command{gnatpp} switches, each
13784 dictionary adds new casing exceptions and overrides all the existing casing
13785 exceptions set by the previous dictionaries
13786
13787 @item
13788 when @command{gnatpp} checks if the word or subword is in the dictionary,
13789 this check is not case sensitive
13790 @end itemize
13791
13792 @noindent
13793 For example, suppose we have the following source to reformat:
13794
13795 @smallexample @c ada
13796 @cartouche
13797 procedure test is
13798    name1 : integer := 1;
13799    name4_name3_name2 : integer := 2;
13800    name2_name3_name4 : Boolean;
13801    name1_var : Float;
13802 begin
13803    name2_name3_name4 := name4_name3_name2 > name1;
13804 end;
13805 @end cartouche
13806 @end smallexample
13807
13808 @noindent
13809 And suppose we have two dictionaries:
13810
13811 @smallexample
13812 @cartouche
13813 @i{dict1:}
13814    NAME1
13815    *NaMe3*
13816    *Name1*
13817 @end cartouche
13818
13819 @cartouche
13820 @i{dict2:}
13821   *NAME3*
13822 @end cartouche
13823 @end smallexample
13824
13825 @noindent
13826 If @command{gnatpp} is called with the following switches:
13827
13828 @smallexample
13829 @ifclear vms
13830 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
13831 @end ifclear
13832 @ifset vms
13833 @command{gnatpp test.adb /NAME_CASING=MIXED_CASE /DICTIONARY=(dict1, dict2)}
13834 @end ifset
13835 @end smallexample
13836
13837 @noindent
13838 then we will get the following name casing in the @command{gnatpp} output:
13839
13840 @smallexample @c ada
13841 @cartouche
13842 procedure Test is
13843    NAME1             : Integer := 1;
13844    Name4_NAME3_Name2 : Integer := 2;
13845    Name2_NAME3_Name4 : Boolean;
13846    Name1_Var         : Float;
13847 begin
13848    Name2_NAME3_Name4 := Name4_NAME3_Name2 > NAME1;
13849 end Test;
13850 @end cartouche
13851 @end smallexample
13852
13853 @c *********************************
13854 @node The GNAT Metric Tool gnatmetric
13855 @chapter The GNAT Metric Tool @command{gnatmetric}
13856 @findex gnatmetric
13857 @cindex Metric tool
13858
13859 @noindent
13860 ^The @command{gnatmetric} tool^@command{GNAT METRIC}^ is an ASIS-based utility
13861 for computing various program metrics.
13862 It takes an Ada source file as input and generates a file containing the
13863 metrics data as output. Various switches control which
13864 metrics are computed and output.
13865
13866 @command{gnatmetric} generates and uses the ASIS
13867 tree for the input source and thus requires the input to be syntactically and
13868 semantically legal.
13869 If this condition is not met, @command{gnatmetric} will generate
13870 an error message; no metric information for this file will be
13871 computed and reported.
13872
13873 If the compilation unit contained in the input source depends semantically
13874 upon units in files located outside the current directory, you have to provide
13875 the source search path when invoking @command{gnatmetric}.
13876 If it depends semantically upon units that are contained
13877 in files with names that do not follow the GNAT file naming rules, you have to
13878 provide the configuration file describing the corresponding naming scheme (see
13879 the description of the @command{gnatmetric} switches below.)
13880 Alternatively, you may use a project file and invoke @command{gnatmetric}
13881 through the @command{gnat} driver.
13882
13883 The @command{gnatmetric} command has the form
13884
13885 @smallexample
13886 @c $ gnatmetric @ovar{switches} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
13887 @c Expanding @ovar macro inline (explanation in macro def comments)
13888 $ gnatmetric @r{[}@var{switches}@r{]} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
13889 @end smallexample
13890
13891 @noindent
13892 where
13893 @itemize @bullet
13894 @item
13895 @var{switches} specify the metrics to compute and define the destination for
13896 the output
13897
13898 @item
13899 Each @var{filename} is the name (including the extension) of a source
13900 file to process. ``Wildcards'' are allowed, and
13901 the file name may contain path information.
13902 If no @var{filename} is supplied, then the @var{switches} list must contain
13903 at least one
13904 @option{-files} switch (@pxref{Other gnatmetric Switches}).
13905 Including both a @option{-files} switch and one or more
13906 @var{filename} arguments is permitted.
13907
13908 @item
13909 @samp{@var{gcc_switches}} is a list of switches for
13910 @command{gcc}. They will be passed on to all compiler invocations made by
13911 @command{gnatmetric} to generate the ASIS trees. Here you can provide
13912 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
13913 and use the @option{-gnatec} switch to set the configuration file,
13914 use the @option{-gnat05} switch if sources should be compiled in
13915 Ada 2005 mode etc.
13916 @end itemize
13917
13918 @menu
13919 * Switches for gnatmetric::
13920 @end menu
13921
13922 @node Switches for gnatmetric
13923 @section Switches for @command{gnatmetric}
13924
13925 @noindent
13926 The following subsections describe the various switches accepted by
13927 @command{gnatmetric}, organized by category.
13928
13929 @menu
13930 * Output Files Control::
13931 * Disable Metrics For Local Units::
13932 * Specifying a set of metrics to compute::
13933 * Other gnatmetric Switches::
13934 * Generate project-wide metrics::
13935 @end menu
13936
13937 @node Output Files Control
13938 @subsection Output File Control
13939 @cindex Output file control in @command{gnatmetric}
13940
13941 @noindent
13942 @command{gnatmetric} has two output formats. It can generate a
13943 textual (human-readable) form, and also XML. By default only textual
13944 output is generated.
13945
13946 When generating the output in textual form, @command{gnatmetric} creates
13947 for each Ada source file a corresponding text file
13948 containing the computed metrics, except for the case when the set of metrics
13949 specified by gnatmetric parameters consists only of metrics that are computed
13950 for the whole set of analyzed sources, but not for each Ada source.
13951 By default, this file is placed in the same directory as where the source
13952 file is located, and its name is obtained
13953 by appending the ^@file{.metrix}^@file{$METRIX}^ suffix to the name of the
13954 input file.
13955
13956 All the output information generated in XML format is placed in a single
13957 file. By default this file is placed in the current directory and has the
13958 name ^@file{metrix.xml}^@file{METRIX$XML}^.
13959
13960 Some of the computed metrics are summed over the units passed to
13961 @command{gnatmetric}; for example, the total number of lines of code.
13962 By default this information is sent to @file{stdout}, but a file
13963 can be specified with the @option{-og} switch.
13964
13965 The following switches control the @command{gnatmetric} output:
13966
13967 @table @option
13968 @cindex @option{^-x^/XML^} (@command{gnatmetric})
13969 @item ^-x^/XML^
13970 Generate the XML output
13971
13972 @cindex @option{^-xs^/XSD^} (@command{gnatmetric})
13973 @item ^-xs^/XSD^
13974 Generate the XML output and the XML schema file that describes the structure
13975 of the XML metric report, this schema is assigned to the XML file. The schema
13976 file has the same name as the XML output file with @file{.xml} suffix replaced
13977 with @file{.xsd}
13978
13979 @cindex @option{^-nt^/NO_TEXT^} (@command{gnatmetric})
13980 @item ^-nt^/NO_TEXT^
13981 Do not generate the output in text form (implies @option{^-x^/XML^})
13982
13983 @cindex @option{^-d^/DIRECTORY^} (@command{gnatmetric})
13984 @item ^-d @var{output_dir}^/DIRECTORY=@var{output_dir}^
13985 Put text files with detailed metrics into @var{output_dir}
13986
13987 @cindex @option{^-o^/SUFFIX_DETAILS^} (@command{gnatmetric})
13988 @item ^-o @var{file_suffix}^/SUFFIX_DETAILS=@var{file_suffix}^
13989 Use @var{file_suffix}, instead of ^@file{.metrix}^@file{$METRIX}^
13990 in the name of the output file.
13991
13992 @cindex @option{^-og^/GLOBAL_OUTPUT^} (@command{gnatmetric})
13993 @item ^-og @var{file_name}^/GLOBAL_OUTPUT=@var{file_name}^
13994 Put global metrics into @var{file_name}
13995
13996 @cindex @option{^-ox^/XML_OUTPUT^} (@command{gnatmetric})
13997 @item ^-ox @var{file_name}^/XML_OUTPUT=@var{file_name}^
13998 Put the XML output into @var{file_name} (also implies @option{^-x^/XML^})
13999
14000 @cindex @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} (@command{gnatmetric})
14001 @item ^-sfn^/SHORT_SOURCE_FILE_NAME^
14002 Use ``short'' source file names in the output.  (The @command{gnatmetric}
14003 output includes the name(s) of the Ada source file(s) from which the metrics
14004 are computed.  By default each name includes the absolute path. The
14005 @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} switch causes @command{gnatmetric}
14006 to exclude all directory information from the file names that are output.)
14007
14008 @end table
14009
14010 @node Disable Metrics For Local Units
14011 @subsection Disable Metrics For Local Units
14012 @cindex Disable Metrics For Local Units in @command{gnatmetric}
14013
14014 @noindent
14015 @command{gnatmetric} relies on the GNAT compilation model @minus{}
14016 one compilation
14017 unit per one source file. It computes line metrics for the whole source
14018 file, and it also computes syntax
14019 and complexity metrics for the file's outermost unit.
14020
14021 By default, @command{gnatmetric} will also compute all metrics for certain
14022 kinds of locally declared program units:
14023
14024 @itemize @bullet
14025 @item
14026 subprogram (and generic subprogram) bodies;
14027
14028 @item
14029 package (and generic package) specs and bodies;
14030
14031 @item
14032 task object and type specifications and bodies;
14033
14034 @item
14035 protected object and type specifications and bodies.
14036 @end itemize
14037
14038 @noindent
14039 These kinds of entities will be referred to as
14040 @emph{eligible local program units}, or simply @emph{eligible local units},
14041 @cindex Eligible local unit (for @command{gnatmetric})
14042 in the discussion below.
14043
14044 Note that a subprogram declaration, generic instantiation,
14045 or renaming declaration only receives metrics
14046 computation when it appear as the outermost entity
14047 in a source file.
14048
14049 Suppression of metrics computation for eligible local units can be
14050 obtained via the following switch:
14051
14052 @table @option
14053 @cindex @option{^-n@var{x}^/SUPPRESS^} (@command{gnatmetric})
14054 @item ^-nolocal^/SUPPRESS=LOCAL_DETAILS^
14055 Do not compute detailed metrics for eligible local program units
14056
14057 @end table
14058
14059 @node Specifying a set of metrics to compute
14060 @subsection Specifying a set of metrics to compute
14061
14062 @noindent
14063 By default all the metrics are computed and reported. The switches
14064 described in this subsection allow you to control, on an individual
14065 basis, whether metrics are computed and
14066 reported. If at least one positive metric
14067 switch is specified (that is, a switch that defines that a given
14068 metric or set of metrics is to be computed), then only
14069 explicitly specified metrics are reported.
14070
14071 @menu
14072 * Line Metrics Control::
14073 * Syntax Metrics Control::
14074 * Complexity Metrics Control::
14075 * Object-Oriented Metrics Control::
14076 @end menu
14077
14078 @node Line Metrics Control
14079 @subsubsection Line Metrics Control
14080 @cindex Line metrics control in @command{gnatmetric}
14081
14082 @noindent
14083 For any (legal) source file, and for each of its
14084 eligible local program units, @command{gnatmetric} computes the following
14085 metrics:
14086
14087 @itemize @bullet
14088 @item
14089 the total number of lines;
14090
14091 @item
14092 the total number of code lines (i.e., non-blank lines that are not comments)
14093
14094 @item
14095 the number of comment lines
14096
14097 @item
14098 the number of code lines containing end-of-line comments;
14099
14100 @item
14101 the comment percentage: the ratio between the number of lines that contain
14102 comments and the number of all non-blank lines, expressed as a percentage;
14103
14104 @item
14105 the number of empty lines and lines containing only space characters and/or
14106 format effectors (blank lines)
14107
14108 @item
14109 the average number of code lines in subprogram bodies, task bodies, entry
14110 bodies and statement sequences in package bodies (this metric is only computed
14111 across the whole set of the analyzed units)
14112
14113 @end itemize
14114
14115 @noindent
14116 @command{gnatmetric} sums the values of the line metrics for all the
14117 files being processed and then generates the cumulative results. The tool
14118 also computes for all the files being processed the average number of code
14119 lines in bodies.
14120
14121 You can use the following switches to select the specific line metrics
14122 to be computed and reported.
14123
14124 @table @option
14125 @cindex @option{^--lines@var{x}^/LINE_COUNT_METRICS^} (@command{gnatmetric})
14126
14127 @ifclear vms
14128 @cindex @option{--no-lines@var{x}}
14129 @end ifclear
14130
14131 @item ^--lines-all^/LINE_COUNT_METRICS=ALL^
14132 Report all the line metrics
14133
14134 @item ^--no-lines-all^/LINE_COUNT_METRICS=NONE^
14135 Do not report any of line metrics
14136
14137 @item ^--lines^/LINE_COUNT_METRICS=ALL_LINES^
14138 Report the number of all lines
14139
14140 @item ^--no-lines^/LINE_COUNT_METRICS=NOALL_LINES^
14141 Do not report the number of all lines
14142
14143 @item ^--lines-code^/LINE_COUNT_METRICS=CODE_LINES^
14144 Report the number of code lines
14145
14146 @item ^--no-lines-code^/LINE_COUNT_METRICS=NOCODE_LINES^
14147 Do not report the number of code lines
14148
14149 @item ^--lines-comment^/LINE_COUNT_METRICS=COMMENT_LINES^
14150 Report the number of comment lines
14151
14152 @item ^--no-lines-comment^/LINE_COUNT_METRICS=NOCOMMENT_LINES^
14153 Do not report the number of comment lines
14154
14155 @item ^--lines-eol-comment^/LINE_COUNT_METRICS=CODE_COMMENT_LINES^
14156 Report the number of code lines containing
14157 end-of-line comments
14158
14159 @item ^--no-lines-eol-comment^/LINE_COUNT_METRICS=NOCODE_COMMENT_LINES^
14160 Do not report the number of code lines containing
14161 end-of-line comments
14162
14163 @item ^--lines-ratio^/LINE_COUNT_METRICS=COMMENT_PERCENTAGE^
14164 Report the comment percentage in the program text
14165
14166 @item ^--no-lines-ratio^/LINE_COUNT_METRICS=NOCOMMENT_PERCENTAGE^
14167 Do not report the comment percentage in the program text
14168
14169 @item ^--lines-blank^/LINE_COUNT_METRICS=BLANK_LINES^
14170 Report the number of blank lines
14171
14172 @item ^--no-lines-blank^/LINE_COUNT_METRICS=NOBLANK_LINES^
14173 Do not report the number of blank lines
14174
14175 @item ^--lines-average^/LINE_COUNT_METRICS=AVERAGE_BODY_LINES^
14176 Report the average number of code lines in subprogram bodies, task bodies,
14177 entry bodies and statement sequences in package bodies. The metric is computed
14178 and reported for the whole set of processed Ada sources only.
14179
14180 @item ^--no-lines-average^/LINE_COUNT_METRICS=NOAVERAGE_BODY_LINES^
14181 Do not report the average number of code lines in subprogram bodies,
14182 task bodies, entry bodies and statement sequences in package bodies.
14183
14184 @end table
14185
14186 @node Syntax Metrics Control
14187 @subsubsection Syntax Metrics Control
14188 @cindex Syntax metrics control in @command{gnatmetric}
14189
14190 @noindent
14191 @command{gnatmetric} computes various syntactic metrics for the
14192 outermost unit and for each eligible local unit:
14193
14194 @table @emph
14195 @item LSLOC (``Logical Source Lines Of Code'')
14196 The total number of declarations and the total number of statements
14197
14198 @item Maximal static nesting level of inner program units
14199 According to
14200 @cite{Ada Reference Manual}, 10.1(1), ``A program unit is either a
14201 package, a task unit, a protected unit, a
14202 protected entry, a generic unit, or an explicitly declared subprogram other
14203 than an enumeration literal.''
14204
14205 @item Maximal nesting level of composite syntactic constructs
14206 This corresponds to the notion of the
14207 maximum nesting level in the GNAT built-in style checks
14208 (@pxref{Style Checking})
14209 @end table
14210
14211 @noindent
14212 For the outermost unit in the file, @command{gnatmetric} additionally computes
14213 the following metrics:
14214
14215 @table @emph
14216 @item Public subprograms
14217 This metric is computed for package specs. It is the
14218 number of subprograms and generic subprograms declared in the visible
14219 part (including the visible part of nested packages, protected objects, and
14220 protected types).
14221
14222 @item All subprograms
14223 This metric is computed for bodies and subunits. The
14224 metric is equal to a total number of subprogram bodies in the compilation
14225 unit.
14226 Neither generic instantiations nor renamings-as-a-body nor body stubs
14227 are counted. Any subprogram body is counted, independently of its nesting
14228 level and enclosing constructs. Generic bodies and bodies of protected
14229 subprograms are counted in the same way as ``usual'' subprogram bodies.
14230
14231 @item Public types
14232 This metric is computed for package specs and
14233 generic package declarations. It is the total number of types
14234 that can be referenced from outside this compilation unit, plus the
14235 number of types from all the visible parts of all the visible generic
14236 packages. Generic formal types are not counted.  Only types, not subtypes,
14237 are included.
14238
14239 @noindent
14240 Along with the total number of public types, the following
14241 types are counted and reported separately:
14242
14243 @itemize @bullet
14244 @item
14245 Abstract types
14246
14247 @item
14248 Root tagged types (abstract, non-abstract, private, non-private). Type
14249 extensions are @emph{not} counted
14250
14251 @item
14252 Private types (including private extensions)
14253
14254 @item
14255 Task types
14256
14257 @item
14258 Protected types
14259
14260 @end itemize
14261
14262 @item All types
14263 This metric is computed for any compilation unit. It is equal to the total
14264 number of the declarations of different types given in the compilation unit.
14265 The private and the corresponding full type declaration are counted as one
14266 type declaration. Incomplete type declarations and generic formal types
14267 are not counted.
14268 No distinction is made among different kinds of types (abstract,
14269 private etc.); the total number of types is computed and reported.
14270
14271 @end table
14272
14273 @noindent
14274 By default, all the syntax metrics are computed and reported. You can use the
14275 following switches to select specific syntax metrics.
14276
14277 @table @option
14278
14279 @cindex @option{^--syntax@var{x}^/SYNTAX_METRICS^} (@command{gnatmetric})
14280
14281 @ifclear vms
14282 @cindex @option{--no-syntax@var{x}} (@command{gnatmetric})
14283 @end ifclear
14284
14285 @item ^--syntax-all^/SYNTAX_METRICS=ALL^
14286 Report all the syntax metrics
14287
14288 @item ^--no-syntax-all^/SYNTAX_METRICS=NONE^
14289 Do not report any of syntax metrics
14290
14291 @item ^--declarations^/SYNTAX_METRICS=DECLARATIONS^
14292 Report the total number of declarations
14293
14294 @item ^--no-declarations^/SYNTAX_METRICS=NODECLARATIONS^
14295 Do not report the total number of declarations
14296
14297 @item ^--statements^/SYNTAX_METRICS=STATEMENTS^
14298 Report the total number of statements
14299
14300 @item ^--no-statements^/SYNTAX_METRICS=NOSTATEMENTS^
14301 Do not report the total number of statements
14302
14303 @item ^--public-subprograms^/SYNTAX_METRICS=PUBLIC_SUBPROGRAMS^
14304 Report the number of public subprograms in a compilation unit
14305
14306 @item ^--no-public-subprograms^/SYNTAX_METRICS=NOPUBLIC_SUBPROGRAMS^
14307 Do not report the number of public subprograms in a compilation unit
14308
14309 @item ^--all-subprograms^/SYNTAX_METRICS=ALL_SUBPROGRAMS^
14310 Report the number of all the subprograms in a compilation unit
14311
14312 @item ^--no-all-subprograms^/SYNTAX_METRICS=NOALL_SUBPROGRAMS^
14313 Do not report the number of all the subprograms in a compilation unit
14314
14315 @item ^--public-types^/SYNTAX_METRICS=PUBLIC_TYPES^
14316 Report the number of public types in a compilation unit
14317
14318 @item ^--no-public-types^/SYNTAX_METRICS=NOPUBLIC_TYPES^
14319 Do not report the number of public types in a compilation unit
14320
14321 @item ^--all-types^/SYNTAX_METRICS=ALL_TYPES^
14322 Report the number of all the types in a compilation unit
14323
14324 @item ^--no-all-types^/SYNTAX_METRICS=NOALL_TYPES^
14325 Do not report the number of all the types in a compilation unit
14326
14327 @item ^--unit-nesting^/SYNTAX_METRICS=UNIT_NESTING^
14328 Report the maximal program unit nesting level
14329
14330 @item ^--no-unit-nesting^/SYNTAX_METRICS=UNIT_NESTING_OFF^
14331 Do not report the maximal program unit nesting level
14332
14333 @item ^--construct-nesting^/SYNTAX_METRICS=CONSTRUCT_NESTING^
14334 Report the maximal construct nesting level
14335
14336 @item ^--no-construct-nesting^/SYNTAX_METRICS=NOCONSTRUCT_NESTING^
14337 Do not report the maximal construct nesting level
14338
14339 @end table
14340
14341 @node Complexity Metrics Control
14342 @subsubsection Complexity Metrics Control
14343 @cindex Complexity metrics control in @command{gnatmetric}
14344
14345 @noindent
14346 For a program unit that is an executable body (a subprogram body (including
14347 generic bodies), task body, entry body or a package body containing
14348 its own statement sequence) @command{gnatmetric} computes the following
14349 complexity metrics:
14350
14351 @itemize @bullet
14352 @item
14353 McCabe cyclomatic complexity;
14354
14355 @item
14356 McCabe essential complexity;
14357
14358 @item
14359 maximal loop nesting level
14360
14361 @end itemize
14362
14363 @noindent
14364 The McCabe complexity metrics are defined
14365 in @url{http://www.mccabe.com/pdf/nist235r.pdf}
14366
14367 According to McCabe, both control statements and short-circuit control forms
14368 should be taken into account when computing cyclomatic complexity. For each
14369 body, we compute three metric values:
14370
14371 @itemize @bullet
14372 @item
14373 the complexity introduced by control
14374 statements only, without taking into account short-circuit forms,
14375
14376 @item
14377 the complexity introduced by short-circuit control forms only, and
14378
14379 @item
14380 the total
14381 cyclomatic complexity, which is the sum of these two values.
14382 @end itemize
14383
14384 @noindent
14385 When computing cyclomatic and essential complexity, @command{gnatmetric} skips
14386 the code in the exception handlers and in all the nested program units.
14387
14388 By default, all the complexity metrics are computed and reported.
14389 For more fine-grained control you can use
14390 the following switches:
14391
14392 @table @option
14393 @cindex @option{^-complexity@var{x}^/COMPLEXITY_METRICS^} (@command{gnatmetric})
14394
14395 @ifclear vms
14396 @cindex @option{--no-complexity@var{x}}
14397 @end ifclear
14398
14399 @item ^--complexity-all^/COMPLEXITY_METRICS=ALL^
14400 Report all the complexity metrics
14401
14402 @item ^--no-complexity-all^/COMPLEXITY_METRICS=NONE^
14403 Do not report any of complexity metrics
14404
14405 @item ^--complexity-cyclomatic^/COMPLEXITY_METRICS=CYCLOMATIC^
14406 Report the McCabe Cyclomatic Complexity
14407
14408 @item ^--no-complexity-cyclomatic^/COMPLEXITY_METRICS=NOCYCLOMATIC^
14409 Do not report the McCabe Cyclomatic Complexity
14410
14411 @item ^--complexity-essential^/COMPLEXITY_METRICS=ESSENTIAL^
14412 Report the Essential Complexity
14413
14414 @item ^--no-complexity-essential^/COMPLEXITY_METRICS=NOESSENTIAL^
14415 Do not report the Essential Complexity
14416
14417 @item ^--loop-nesting^/COMPLEXITY_METRICS=LOOP_NESTING_ON^
14418 Report maximal loop nesting level
14419
14420 @item ^--no-loop-nesting^/COMPLEXITY_METRICS=NOLOOP_NESTING^
14421 Do not report maximal loop nesting level
14422
14423 @item ^--complexity-average^/COMPLEXITY_METRICS=AVERAGE_COMPLEXITY^
14424 Report the average McCabe Cyclomatic Complexity for all the subprogram bodies,
14425 task bodies, entry bodies and statement sequences in package bodies.
14426 The metric is computed and reported for whole set of processed Ada sources
14427 only.
14428
14429 @item ^--no-complexity-average^/COMPLEXITY_METRICS=NOAVERAGE_COMPLEXITY^
14430 Do not report the average McCabe Cyclomatic Complexity for all the subprogram
14431 bodies, task bodies, entry bodies and statement sequences in package bodies
14432
14433 @cindex @option{^-ne^/NO_EXITS_AS_GOTOS^} (@command{gnatmetric})
14434 @item ^-ne^/NO_EXITS_AS_GOTOS^
14435 Do not consider @code{exit} statements as @code{goto}s when
14436 computing Essential Complexity
14437
14438 @item ^--extra-exit-points^/EXTRA_EXIT_POINTS^
14439 Report the extra exit points for subprogram bodies. As an exit point, this
14440 metric counts @code{return} statements and raise statements in case when the
14441 raised exception is not handled in the same body. In case of a function this
14442 metric subtracts 1 from the number of exit points, because a function body
14443 must contain at least one @code{return} statement.
14444
14445 @item ^--no-extra-exit-points^/NOEXTRA_EXIT_POINTS^
14446 Do not report the extra exit points for subprogram bodies
14447 @end table
14448
14449
14450 @node Object-Oriented Metrics Control
14451 @subsubsection Object-Oriented Metrics Control
14452 @cindex Object-Oriented metrics control in @command{gnatmetric}
14453
14454 @noindent
14455 @cindex Coupling metrics (in in @command{gnatmetric})
14456 Coupling metrics are object-oriented metrics that measure the
14457 dependencies between a given class (or a group of classes) and the
14458 ``external world'' (that is, the other classes in the program). In this
14459 subsection the term ``class'' is used in its
14460 traditional object-oriented programming sense
14461 (an instantiable module that contains data and/or method members).
14462 A @emph{category} (of classes)
14463 is a group of closely related classes that are reused and/or
14464 modified together.
14465
14466 A class @code{K}'s @emph{efferent coupling} is the number of classes
14467 that @code{K} depends upon.
14468 A category's efferent coupling is the number of classes outside the
14469 category that the classes inside the category depend upon.
14470
14471 A class @code{K}'s @emph{afferent coupling} is the number of classes
14472 that depend upon @code{K}.
14473 A category's afferent coupling is the number of classes outside the
14474 category that depend on classes belonging to the category.
14475
14476 Ada's implementation of the object-oriented paradigm does not use the
14477 traditional class notion, so the definition of the coupling
14478 metrics for Ada maps the class and class category notions
14479 onto Ada constructs.
14480
14481 For the coupling metrics, several kinds of modules -- a library package,
14482 a library generic package, and a library generic package instantiation --
14483 that define a tagged type or an interface type are
14484 considered to be a class. A category consists of a library package (or
14485 a library generic package) that defines a tagged or an interface type,
14486 together with all its descendant (generic) packages that define tagged
14487 or interface types. For any package counted as a class,
14488 its body and subunits (if any) are considered
14489 together with its spec when counting the dependencies, and coupling
14490 metrics are reported for spec units only. For dependencies
14491 between classes, the Ada semantic dependencies are considered.
14492 For coupling metrics, only dependencies on units that are considered as
14493 classes, are considered.
14494
14495 When computing coupling metrics, @command{gnatmetric} counts only
14496 dependencies between units that are arguments of the gnatmetric call.
14497 Coupling metrics are program-wide (or project-wide) metrics, so to
14498 get a valid result, you should call @command{gnatmetric} for
14499 the whole set of sources that make up your program. It can be done
14500 by calling @command{gnatmetric} from the GNAT driver with @option{-U}
14501 option (see See @ref{The GNAT Driver and Project Files} for details.
14502
14503 By default, all the coupling metrics are disabled. You can use the following
14504 switches to specify the coupling metrics to be computed and reported:
14505
14506 @table @option
14507
14508 @ifclear vms
14509 @cindex @option{--package@var{x}} (@command{gnatmetric})
14510 @cindex @option{--no-package@var{x}} (@command{gnatmetric})
14511 @cindex @option{--category@var{x}} (@command{gnatmetric})
14512 @cindex @option{--no-category@var{x}} (@command{gnatmetric})
14513 @end ifclear
14514
14515 @ifset vms
14516 @cindex @option{/COUPLING_METRICS} (@command{gnatmetric})
14517 @end ifset
14518
14519 @item ^--coupling-all^/COUPLING_METRICS=ALL^
14520 Report all the coupling metrics
14521
14522 @item ^--no-coupling-all^/COUPLING_METRICS=NONE^
14523 Do not report any of  metrics
14524
14525 @item ^--package-efferent-coupling^/COUPLING_METRICS=PACKAGE_EFFERENT^
14526 Report package efferent coupling
14527
14528 @item ^--no-package-efferent-coupling^/COUPLING_METRICS=NOPACKAGE_EFFERENT^
14529 Do not report package efferent coupling
14530
14531 @item ^--package-afferent-coupling^/COUPLING_METRICS=PACKAGE_AFFERENT^
14532 Report package afferent coupling
14533
14534 @item ^--no-package-afferent-coupling^/COUPLING_METRICS=NOPACKAGE_AFFERENT^
14535 Do not report package afferent coupling
14536
14537 @item ^--category-efferent-coupling^/COUPLING_METRICS=CATEGORY_EFFERENT^
14538 Report category efferent coupling
14539
14540 @item ^--no-category-efferent-coupling^/COUPLING_METRICS=NOCATEGORY_EFFERENT^
14541 Do not report category efferent coupling
14542
14543 @item ^--category-afferent-coupling^/COUPLING_METRICS=CATEGORY_AFFERENT^
14544 Report category afferent coupling
14545
14546 @item ^--no-category-afferent-coupling^/COUPLING_METRICS=NOCATEGORY_AFFERENT^
14547 Do not report category afferent coupling
14548
14549 @end table
14550
14551 @node Other gnatmetric Switches
14552 @subsection Other @code{gnatmetric} Switches
14553
14554 @noindent
14555 Additional @command{gnatmetric} switches are as follows:
14556
14557 @table @option
14558 @item ^-files @var{filename}^/FILES=@var{filename}^
14559 @cindex @option{^-files^/FILES^} (@code{gnatmetric})
14560 Take the argument source files from the specified file. This file should be an
14561 ordinary text file containing file names separated by spaces or
14562 line breaks. You can use this switch more than once in the same call to
14563 @command{gnatmetric}. You also can combine this switch with
14564 an explicit list of files.
14565
14566 @item ^-v^/VERBOSE^
14567 @cindex @option{^-v^/VERBOSE^} (@code{gnatmetric})
14568 Verbose mode;
14569 @command{gnatmetric} generates version information and then
14570 a trace of sources being processed.
14571
14572 @item ^-q^/QUIET^
14573 @cindex @option{^-q^/QUIET^} (@code{gnatmetric})
14574 Quiet mode.
14575 @end table
14576
14577 @node Generate project-wide metrics
14578 @subsection Generate project-wide metrics
14579
14580 In order to compute metrics on all units of a given project, you can use
14581 the @command{gnat} driver along with the @option{-P} option:
14582 @smallexample
14583    gnat metric -Pproj
14584 @end smallexample
14585
14586 @noindent
14587 If the project @code{proj} depends upon other projects, you can compute
14588 the metrics on the project closure using the @option{-U} option:
14589 @smallexample
14590    gnat metric -Pproj -U
14591 @end smallexample
14592
14593 @noindent
14594 Finally, if not all the units are relevant to a particular main
14595 program in the project closure, you can generate metrics for the set
14596 of units needed to create a given main program (unit closure) using
14597 the @option{-U} option followed by the name of the main unit:
14598 @smallexample
14599    gnat metric -Pproj -U main
14600 @end smallexample
14601
14602
14603 @c ***********************************
14604 @node File Name Krunching Using gnatkr
14605 @chapter File Name Krunching Using @code{gnatkr}
14606 @findex gnatkr
14607
14608 @noindent
14609 This chapter discusses the method used by the compiler to shorten
14610 the default file names chosen for Ada units so that they do not
14611 exceed the maximum length permitted. It also describes the
14612 @code{gnatkr} utility that can be used to determine the result of
14613 applying this shortening.
14614 @menu
14615 * About gnatkr::
14616 * Using gnatkr::
14617 * Krunching Method::
14618 * Examples of gnatkr Usage::
14619 @end menu
14620
14621 @node About gnatkr
14622 @section About @code{gnatkr}
14623
14624 @noindent
14625 The default file naming rule in GNAT
14626 is that the file name must be derived from
14627 the unit name. The exact default rule is as follows:
14628 @itemize @bullet
14629 @item
14630 Take the unit name and replace all dots by hyphens.
14631 @item
14632 If such a replacement occurs in the
14633 second character position of a name, and the first character is
14634 ^@samp{a}, @samp{g}, @samp{s}, or @samp{i}, ^@samp{A}, @samp{G}, @samp{S}, or @samp{I},^
14635 then replace the dot by the character
14636 ^@samp{~} (tilde)^@samp{$} (dollar sign)^
14637 instead of a minus.
14638 @end itemize
14639 The reason for this exception is to avoid clashes
14640 with the standard names for children of System, Ada, Interfaces,
14641 and GNAT, which use the prefixes
14642 ^@samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},^@samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},^
14643 respectively.
14644
14645 The @option{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}}
14646 switch of the compiler activates a ``krunching''
14647 circuit that limits file names to nn characters (where nn is a decimal
14648 integer). For example, using OpenVMS,
14649 where the maximum file name length is
14650 39, the value of nn is usually set to 39, but if you want to generate
14651 a set of files that would be usable if ported to a system with some
14652 different maximum file length, then a different value can be specified.
14653 The default value of 39 for OpenVMS need not be specified.
14654
14655 The @code{gnatkr} utility can be used to determine the krunched name for
14656 a given file, when krunched to a specified maximum length.
14657
14658 @node Using gnatkr
14659 @section Using @code{gnatkr}
14660
14661 @noindent
14662 The @code{gnatkr} command has the form
14663
14664 @ifclear vms
14665 @smallexample
14666 @c $ gnatkr @var{name} @ovar{length}
14667 @c Expanding @ovar macro inline (explanation in macro def comments)
14668 $ gnatkr @var{name} @r{[}@var{length}@r{]}
14669 @end smallexample
14670 @end ifclear
14671
14672 @ifset vms
14673 @smallexample
14674 $ gnatkr @var{name} /COUNT=nn
14675 @end smallexample
14676 @end ifset
14677
14678 @noindent
14679 @var{name} is the uncrunched file name, derived from the name of the unit
14680 in the standard manner described in the previous section (i.e., in particular
14681 all dots are replaced by hyphens). The file name may or may not have an
14682 extension (defined as a suffix of the form period followed by arbitrary
14683 characters other than period). If an extension is present then it will
14684 be preserved in the output. For example, when krunching @file{hellofile.ads}
14685 to eight characters, the result will be hellofil.ads.
14686
14687 Note: for compatibility with previous versions of @code{gnatkr} dots may
14688 appear in the name instead of hyphens, but the last dot will always be
14689 taken as the start of an extension. So if @code{gnatkr} is given an argument
14690 such as @file{Hello.World.adb} it will be treated exactly as if the first
14691 period had been a hyphen, and for example krunching to eight characters
14692 gives the result @file{hellworl.adb}.
14693
14694 Note that the result is always all lower case (except on OpenVMS where it is
14695 all upper case). Characters of the other case are folded as required.
14696
14697 @var{length} represents the length of the krunched name. The default
14698 when no argument is given is ^8^39^ characters. A length of zero stands for
14699 unlimited, in other words do not chop except for system files where the
14700 implied crunching length is always eight characters.
14701
14702 @noindent
14703 The output is the krunched name. The output has an extension only if the
14704 original argument was a file name with an extension.
14705
14706 @node Krunching Method
14707 @section Krunching Method
14708
14709 @noindent
14710 The initial file name is determined by the name of the unit that the file
14711 contains. The name is formed by taking the full expanded name of the
14712 unit and replacing the separating dots with hyphens and
14713 using ^lowercase^uppercase^
14714 for all letters, except that a hyphen in the second character position is
14715 replaced by a ^tilde^dollar sign^ if the first character is
14716 ^@samp{a}, @samp{i}, @samp{g}, or @samp{s}^@samp{A}, @samp{I}, @samp{G}, or @samp{S}^.
14717 The extension is @code{.ads} for a
14718 spec and @code{.adb} for a body.
14719 Krunching does not affect the extension, but the file name is shortened to
14720 the specified length by following these rules:
14721
14722 @itemize @bullet
14723 @item
14724 The name is divided into segments separated by hyphens, tildes or
14725 underscores and all hyphens, tildes, and underscores are
14726 eliminated. If this leaves the name short enough, we are done.
14727
14728 @item
14729 If the name is too long, the longest segment is located (left-most
14730 if there are two of equal length), and shortened by dropping
14731 its last character. This is repeated until the name is short enough.
14732
14733 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
14734 to fit the name into 8 characters as required by some operating systems.
14735
14736 @smallexample
14737 our-strings-wide_fixed 22
14738 our strings wide fixed 19
14739 our string  wide fixed 18
14740 our strin   wide fixed 17
14741 our stri    wide fixed 16
14742 our stri    wide fixe  15
14743 our str     wide fixe  14
14744 our str     wid  fixe  13
14745 our str     wid  fix   12
14746 ou  str     wid  fix   11
14747 ou  st      wid  fix   10
14748 ou  st      wi   fix   9
14749 ou  st      wi   fi    8
14750 Final file name: oustwifi.adb
14751 @end smallexample
14752
14753 @item
14754 The file names for all predefined units are always krunched to eight
14755 characters. The krunching of these predefined units uses the following
14756 special prefix replacements:
14757
14758 @table @file
14759 @item ada-
14760 replaced by @file{^a^A^-}
14761
14762 @item gnat-
14763 replaced by @file{^g^G^-}
14764
14765 @item interfaces-
14766 replaced by @file{^i^I^-}
14767
14768 @item system-
14769 replaced by @file{^s^S^-}
14770 @end table
14771
14772 These system files have a hyphen in the second character position. That
14773 is why normal user files replace such a character with a
14774 ^tilde^dollar sign^, to
14775 avoid confusion with system file names.
14776
14777 As an example of this special rule, consider
14778 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
14779
14780 @smallexample
14781 ada-strings-wide_fixed 22
14782 a-  strings wide fixed 18
14783 a-  string  wide fixed 17
14784 a-  strin   wide fixed 16
14785 a-  stri    wide fixed 15
14786 a-  stri    wide fixe  14
14787 a-  str     wide fixe  13
14788 a-  str     wid  fixe  12
14789 a-  str     wid  fix   11
14790 a-  st      wid  fix   10
14791 a-  st      wi   fix   9
14792 a-  st      wi   fi    8
14793 Final file name: a-stwifi.adb
14794 @end smallexample
14795 @end itemize
14796
14797 Of course no file shortening algorithm can guarantee uniqueness over all
14798 possible unit names, and if file name krunching is used then it is your
14799 responsibility to ensure that no name clashes occur. The utility
14800 program @code{gnatkr} is supplied for conveniently determining the
14801 krunched name of a file.
14802
14803 @node Examples of gnatkr Usage
14804 @section Examples of @code{gnatkr} Usage
14805
14806 @smallexample
14807 @iftex
14808 @leftskip=0cm
14809 @end iftex
14810 @ifclear vms
14811 $ gnatkr very_long_unit_name.ads      --> velounna.ads
14812 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
14813 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
14814 $ gnatkr grandparent-parent-child     --> grparchi
14815 @end ifclear
14816 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
14817 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
14818 @end smallexample
14819
14820 @node Preprocessing Using gnatprep
14821 @chapter Preprocessing Using @code{gnatprep}
14822 @findex gnatprep
14823
14824 @noindent
14825 This chapter discusses how to use GNAT's @code{gnatprep} utility for simple
14826 preprocessing.
14827 Although designed for use with GNAT, @code{gnatprep} does not depend on any
14828 special GNAT features.
14829 For further discussion of conditional compilation in general, see
14830 @ref{Conditional Compilation}.
14831
14832 @menu
14833 * Preprocessing Symbols::
14834 * Using gnatprep::
14835 * Switches for gnatprep::
14836 * Form of Definitions File::
14837 * Form of Input Text for gnatprep::
14838 @end menu
14839
14840 @node Preprocessing Symbols
14841 @section Preprocessing Symbols
14842
14843 @noindent
14844 Preprocessing symbols are defined in definition files and referred to in
14845 sources to be preprocessed. A Preprocessing symbol is an identifier, following
14846 normal Ada (case-insensitive) rules for its syntax, with the restriction that
14847 all characters need to be in the ASCII set (no accented letters).
14848
14849 @node Using gnatprep
14850 @section Using @code{gnatprep}
14851
14852 @noindent
14853 To call @code{gnatprep} use
14854
14855 @smallexample
14856 @c $ gnatprep @ovar{switches} @var{infile} @var{outfile} @ovar{deffile}
14857 @c Expanding @ovar macro inline (explanation in macro def comments)
14858 $ gnatprep @r{[}@var{switches}@r{]} @var{infile} @var{outfile} @r{[}@var{deffile}@r{]}
14859 @end smallexample
14860
14861 @noindent
14862 where
14863 @table @var
14864 @item switches
14865 is an optional sequence of switches as described in the next section.
14866
14867 @item infile
14868 is the full name of the input file, which is an Ada source
14869 file containing preprocessor directives.
14870
14871 @item outfile
14872 is the full name of the output file, which is an Ada source
14873 in standard Ada form. When used with GNAT, this file name will
14874 normally have an ads or adb suffix.
14875
14876 @item deffile
14877 is the full name of a text file containing definitions of
14878 preprocessing symbols to be referenced by the preprocessor. This argument is
14879 optional, and can be replaced by the use of the @option{-D} switch.
14880
14881 @end table
14882
14883 @node Switches for gnatprep
14884 @section Switches for @code{gnatprep}
14885
14886 @table @option
14887 @c !sort!
14888
14889 @item ^-b^/BLANK_LINES^
14890 @cindex @option{^-b^/BLANK_LINES^} (@command{gnatprep})
14891 Causes both preprocessor lines and the lines deleted by
14892 preprocessing to be replaced by blank lines in the output source file,
14893 preserving line numbers in the output file.
14894
14895 @item ^-c^/COMMENTS^
14896 @cindex @option{^-c^/COMMENTS^} (@command{gnatprep})
14897 Causes both preprocessor lines and the lines deleted
14898 by preprocessing to be retained in the output source as comments marked
14899 with the special string @code{"--! "}. This option will result in line numbers
14900 being preserved in the output file.
14901
14902 @item ^-C^/REPLACE_IN_COMMENTS^
14903 @cindex @option{^-C^/REPLACE_IN_COMMENTS^} (@command{gnatprep})
14904 Causes comments to be scanned. Normally comments are ignored by gnatprep.
14905 If this option is specified, then comments are scanned and any $symbol
14906 substitutions performed as in program text. This is particularly useful
14907 when structured comments are used (e.g., when writing programs in the
14908 SPARK dialect of Ada). Note that this switch is not available when
14909 doing integrated preprocessing (it would be useless in this context
14910 since comments are ignored by the compiler in any case).
14911
14912 @item ^-Dsymbol=value^/ASSOCIATE="symbol=value"^
14913 @cindex @option{^-D^/ASSOCIATE^} (@command{gnatprep})
14914 Defines a new preprocessing symbol, associated with value. If no value is given
14915 on the command line, then symbol is considered to be @code{True}. This switch
14916 can be used in place of a definition file.
14917
14918 @ifset vms
14919 @item /REMOVE
14920 @cindex @option{/REMOVE} (@command{gnatprep})
14921 This is the default setting which causes lines deleted by preprocessing
14922 to be entirely removed from the output file.
14923 @end ifset
14924
14925 @item ^-r^/REFERENCE^
14926 @cindex @option{^-r^/REFERENCE^} (@command{gnatprep})
14927 Causes a @code{Source_Reference} pragma to be generated that
14928 references the original input file, so that error messages will use
14929 the file name of this original file. The use of this switch implies
14930 that preprocessor lines are not to be removed from the file, so its
14931 use will force @option{^-b^/BLANK_LINES^} mode if
14932 @option{^-c^/COMMENTS^}
14933 has not been specified explicitly.
14934
14935 Note that if the file to be preprocessed contains multiple units, then
14936 it will be necessary to @code{gnatchop} the output file from
14937 @code{gnatprep}. If a @code{Source_Reference} pragma is present
14938 in the preprocessed file, it will be respected by
14939 @code{gnatchop ^-r^/REFERENCE^}
14940 so that the final chopped files will correctly refer to the original
14941 input source file for @code{gnatprep}.
14942
14943 @item ^-s^/SYMBOLS^
14944 @cindex @option{^-s^/SYMBOLS^} (@command{gnatprep})
14945 Causes a sorted list of symbol names and values to be
14946 listed on the standard output file.
14947
14948 @item ^-u^/UNDEFINED^
14949 @cindex @option{^-u^/UNDEFINED^} (@command{gnatprep})
14950 Causes undefined symbols to be treated as having the value FALSE in the context
14951 of a preprocessor test. In the absence of this option, an undefined symbol in
14952 a @code{#if} or @code{#elsif} test will be treated as an error.
14953
14954 @end table
14955
14956 @ifclear vms
14957 @noindent
14958 Note: if neither @option{-b} nor @option{-c} is present,
14959 then preprocessor lines and
14960 deleted lines are completely removed from the output, unless -r is
14961 specified, in which case -b is assumed.
14962 @end ifclear
14963
14964 @node Form of Definitions File
14965 @section Form of Definitions File
14966
14967 @noindent
14968 The definitions file contains lines of the form
14969
14970 @smallexample
14971 symbol := value
14972 @end smallexample
14973
14974 @noindent
14975 where symbol is a preprocessing symbol, and value is one of the following:
14976
14977 @itemize @bullet
14978 @item
14979 Empty, corresponding to a null substitution
14980 @item
14981 A string literal using normal Ada syntax
14982 @item
14983 Any sequence of characters from the set
14984 (letters, digits, period, underline).
14985 @end itemize
14986
14987 @noindent
14988 Comment lines may also appear in the definitions file, starting with
14989 the usual @code{--},
14990 and comments may be added to the definitions lines.
14991
14992 @node Form of Input Text for gnatprep
14993 @section Form of Input Text for @code{gnatprep}
14994
14995 @noindent
14996 The input text may contain preprocessor conditional inclusion lines,
14997 as well as general symbol substitution sequences.
14998
14999 The preprocessor conditional inclusion commands have the form
15000
15001 @smallexample
15002 @group
15003 @cartouche
15004 #if @i{expression} @r{[}then@r{]}
15005    lines
15006 #elsif @i{expression} @r{[}then@r{]}
15007    lines
15008 #elsif @i{expression} @r{[}then@r{]}
15009    lines
15010 @dots{}
15011 #else
15012    lines
15013 #end if;
15014 @end cartouche
15015 @end group
15016 @end smallexample
15017
15018 @noindent
15019 In this example, @i{expression} is defined by the following grammar:
15020 @smallexample
15021 @i{expression} ::=  <symbol>
15022 @i{expression} ::=  <symbol> = "<value>"
15023 @i{expression} ::=  <symbol> = <symbol>
15024 @i{expression} ::=  <symbol> 'Defined
15025 @i{expression} ::=  not @i{expression}
15026 @i{expression} ::=  @i{expression} and @i{expression}
15027 @i{expression} ::=  @i{expression} or @i{expression}
15028 @i{expression} ::=  @i{expression} and then @i{expression}
15029 @i{expression} ::=  @i{expression} or else @i{expression}
15030 @i{expression} ::=  ( @i{expression} )
15031 @end smallexample
15032
15033 The following restriction exists: it is not allowed to have "and" or "or"
15034 following "not" in the same expression without parentheses. For example, this
15035 is not allowed:
15036
15037 @smallexample
15038    not X or Y
15039 @end smallexample
15040
15041 This should be one of the following:
15042
15043 @smallexample
15044    (not X) or Y
15045    not (X or Y)
15046 @end smallexample
15047
15048 @noindent
15049 For the first test (@i{expression} ::= <symbol>) the symbol must have
15050 either the value true or false, that is to say the right-hand of the
15051 symbol definition must be one of the (case-insensitive) literals
15052 @code{True} or @code{False}. If the value is true, then the
15053 corresponding lines are included, and if the value is false, they are
15054 excluded.
15055
15056 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
15057 the symbol has been defined in the definition file or by a @option{-D}
15058 switch on the command line. Otherwise, the test is false.
15059
15060 The equality tests are case insensitive, as are all the preprocessor lines.
15061
15062 If the symbol referenced is not defined in the symbol definitions file,
15063 then the effect depends on whether or not switch @option{-u}
15064 is specified. If so, then the symbol is treated as if it had the value
15065 false and the test fails. If this switch is not specified, then
15066 it is an error to reference an undefined symbol. It is also an error to
15067 reference a symbol that is defined with a value other than @code{True}
15068 or @code{False}.
15069
15070 The use of the @code{not} operator inverts the sense of this logical test.
15071 The @code{not} operator cannot be combined with the @code{or} or @code{and}
15072 operators, without parentheses. For example, "if not X or Y then" is not
15073 allowed, but "if (not X) or Y then" and "if not (X or Y) then" are.
15074
15075 The @code{then} keyword is optional as shown
15076
15077 The @code{#} must be the first non-blank character on a line, but
15078 otherwise the format is free form. Spaces or tabs may appear between
15079 the @code{#} and the keyword. The keywords and the symbols are case
15080 insensitive as in normal Ada code. Comments may be used on a
15081 preprocessor line, but other than that, no other tokens may appear on a
15082 preprocessor line. Any number of @code{elsif} clauses can be present,
15083 including none at all. The @code{else} is optional, as in Ada.
15084
15085 The @code{#} marking the start of a preprocessor line must be the first
15086 non-blank character on the line, i.e., it must be preceded only by
15087 spaces or horizontal tabs.
15088
15089 Symbol substitution outside of preprocessor lines is obtained by using
15090 the sequence
15091
15092 @smallexample
15093 $symbol
15094 @end smallexample
15095
15096 @noindent
15097 anywhere within a source line, except in a comment or within a
15098 string literal. The identifier
15099 following the @code{$} must match one of the symbols defined in the symbol
15100 definition file, and the result is to substitute the value of the
15101 symbol in place of @code{$symbol} in the output file.
15102
15103 Note that although the substitution of strings within a string literal
15104 is not possible, it is possible to have a symbol whose defined value is
15105 a string literal. So instead of setting XYZ to @code{hello} and writing:
15106
15107 @smallexample
15108 Header : String := "$XYZ";
15109 @end smallexample
15110
15111 @noindent
15112 you should set XYZ to @code{"hello"} and write:
15113
15114 @smallexample
15115 Header : String := $XYZ;
15116 @end smallexample
15117
15118 @noindent
15119 and then the substitution will occur as desired.
15120
15121 @node The GNAT Library Browser gnatls
15122 @chapter The GNAT Library Browser @code{gnatls}
15123 @findex gnatls
15124 @cindex Library browser
15125
15126 @noindent
15127 @code{gnatls} is a tool that outputs information about compiled
15128 units. It gives the relationship between objects, unit names and source
15129 files. It can also be used to check the source dependencies of a unit
15130 as well as various characteristics.
15131
15132 Note: to invoke @code{gnatls} with a project file, use the @code{gnat}
15133 driver (see @ref{The GNAT Driver and Project Files}).
15134
15135 @menu
15136 * Running gnatls::
15137 * Switches for gnatls::
15138 * Examples of gnatls Usage::
15139 @end menu
15140
15141 @node Running gnatls
15142 @section Running @code{gnatls}
15143
15144 @noindent
15145 The @code{gnatls} command has the form
15146
15147 @smallexample
15148 $ gnatls switches @var{object_or_ali_file}
15149 @end smallexample
15150
15151 @noindent
15152 The main argument is the list of object or @file{ali} files
15153 (@pxref{The Ada Library Information Files})
15154 for which information is requested.
15155
15156 In normal mode, without additional option, @code{gnatls} produces a
15157 four-column listing. Each line represents information for a specific
15158 object. The first column gives the full path of the object, the second
15159 column gives the name of the principal unit in this object, the third
15160 column gives the status of the source and the fourth column gives the
15161 full path of the source representing this unit.
15162 Here is a simple example of use:
15163
15164 @smallexample
15165 $ gnatls *.o
15166 ^./^[]^demo1.o            demo1            DIF demo1.adb
15167 ^./^[]^demo2.o            demo2             OK demo2.adb
15168 ^./^[]^hello.o            h1                OK hello.adb
15169 ^./^[]^instr-child.o      instr.child      MOK instr-child.adb
15170 ^./^[]^instr.o            instr             OK instr.adb
15171 ^./^[]^tef.o              tef              DIF tef.adb
15172 ^./^[]^text_io_example.o  text_io_example   OK text_io_example.adb
15173 ^./^[]^tgef.o             tgef             DIF tgef.adb
15174 @end smallexample
15175
15176 @noindent
15177 The first line can be interpreted as follows: the main unit which is
15178 contained in
15179 object file @file{demo1.o} is demo1, whose main source is in
15180 @file{demo1.adb}. Furthermore, the version of the source used for the
15181 compilation of demo1 has been modified (DIF). Each source file has a status
15182 qualifier which can be:
15183
15184 @table @code
15185 @item OK (unchanged)
15186 The version of the source file used for the compilation of the
15187 specified unit corresponds exactly to the actual source file.
15188
15189 @item MOK (slightly modified)
15190 The version of the source file used for the compilation of the
15191 specified unit differs from the actual source file but not enough to
15192 require recompilation. If you use gnatmake with the qualifier
15193 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
15194 MOK will not be recompiled.
15195
15196 @item DIF (modified)
15197 No version of the source found on the path corresponds to the source
15198 used to build this object.
15199
15200 @item ??? (file not found)
15201 No source file was found for this unit.
15202
15203 @item HID (hidden,  unchanged version not first on PATH)
15204 The version of the source that corresponds exactly to the source used
15205 for compilation has been found on the path but it is hidden by another
15206 version of the same source that has been modified.
15207
15208 @end table
15209
15210 @node Switches for gnatls
15211 @section Switches for @code{gnatls}
15212
15213 @noindent
15214 @code{gnatls} recognizes the following switches:
15215
15216 @table @option
15217 @c !sort!
15218 @cindex @option{--version} @command{gnatls}
15219 Display Copyright and version, then exit disregarding all other options.
15220
15221 @item --help
15222 @cindex @option{--help} @command{gnatls}
15223 If @option{--version} was not used, display usage, then exit disregarding
15224 all other options.
15225
15226 @item ^-a^/ALL_UNITS^
15227 @cindex @option{^-a^/ALL_UNITS^} (@code{gnatls})
15228 Consider all units, including those of the predefined Ada library.
15229 Especially useful with @option{^-d^/DEPENDENCIES^}.
15230
15231 @item ^-d^/DEPENDENCIES^
15232 @cindex @option{^-d^/DEPENDENCIES^} (@code{gnatls})
15233 List sources from which specified units depend on.
15234
15235 @item ^-h^/OUTPUT=OPTIONS^
15236 @cindex @option{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
15237 Output the list of options.
15238
15239 @item ^-o^/OUTPUT=OBJECTS^
15240 @cindex @option{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
15241 Only output information about object files.
15242
15243 @item ^-s^/OUTPUT=SOURCES^
15244 @cindex @option{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
15245 Only output information about source files.
15246
15247 @item ^-u^/OUTPUT=UNITS^
15248 @cindex @option{^-u^/OUTPUT=UNITS^} (@code{gnatls})
15249 Only output information about compilation units.
15250
15251 @item ^-files^/FILES^=@var{file}
15252 @cindex @option{^-files^/FILES^} (@code{gnatls})
15253 Take as arguments the files listed in text file @var{file}.
15254 Text file @var{file} may contain empty lines that are ignored.
15255 Each nonempty line should contain the name of an existing file.
15256 Several such switches may be specified simultaneously.
15257
15258 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
15259 @itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
15260 @itemx ^-I^/SEARCH=^@var{dir}
15261 @itemx  ^-I-^/NOCURRENT_DIRECTORY^
15262 @itemx -nostdinc
15263 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatls})
15264 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatls})
15265 @cindex @option{^-I^/SEARCH^} (@code{gnatls})
15266 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatls})
15267 Source path manipulation. Same meaning as the equivalent @command{gnatmake}
15268 flags (@pxref{Switches for gnatmake}).
15269
15270 @item --RTS=@var{rts-path}
15271 @cindex @option{--RTS} (@code{gnatls})
15272 Specifies the default location of the runtime library. Same meaning as the
15273 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
15274
15275 @item ^-v^/OUTPUT=VERBOSE^
15276 @cindex @option{^-v^/OUTPUT=VERBOSE^} (@code{gnatls})
15277 Verbose mode. Output the complete source, object and project paths. Do not use
15278 the default column layout but instead use long format giving as much as
15279 information possible on each requested units, including special
15280 characteristics such as:
15281
15282 @table @code
15283 @item  Preelaborable
15284 The unit is preelaborable in the Ada sense.
15285
15286 @item No_Elab_Code
15287 No elaboration code has been produced by the compiler for this unit.
15288
15289 @item Pure
15290 The unit is pure in the Ada sense.
15291
15292 @item Elaborate_Body
15293 The unit contains a pragma Elaborate_Body.
15294
15295 @item Remote_Types
15296 The unit contains a pragma Remote_Types.
15297
15298 @item Shared_Passive
15299 The unit contains a pragma Shared_Passive.
15300
15301 @item Predefined
15302 This unit is part of the predefined environment and cannot be modified
15303 by the user.
15304
15305 @item Remote_Call_Interface
15306 The unit contains a pragma Remote_Call_Interface.
15307
15308 @end table
15309
15310 @end table
15311
15312 @node Examples of gnatls Usage
15313 @section Example of @code{gnatls} Usage
15314 @ifclear vms
15315
15316 @noindent
15317 Example of using the verbose switch. Note how the source and
15318 object paths are affected by the -I switch.
15319
15320 @smallexample
15321 $ gnatls -v -I.. demo1.o
15322
15323 GNATLS 5.03w (20041123-34)
15324 Copyright 1997-2004 Free Software Foundation, Inc.
15325
15326 Source Search Path:
15327    <Current_Directory>
15328    ../
15329    /home/comar/local/adainclude/
15330
15331 Object Search Path:
15332    <Current_Directory>
15333    ../
15334    /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
15335
15336 Project Search Path:
15337    <Current_Directory>
15338    /home/comar/local/lib/gnat/
15339
15340 ./demo1.o
15341    Unit =>
15342      Name   => demo1
15343      Kind   => subprogram body
15344      Flags  => No_Elab_Code
15345      Source => demo1.adb    modified
15346 @end smallexample
15347
15348 @noindent
15349 The following is an example of use of the dependency list.
15350 Note the use of the -s switch
15351 which gives a straight list of source files. This can be useful for
15352 building specialized scripts.
15353
15354 @smallexample
15355 $ gnatls -d demo2.o
15356 ./demo2.o   demo2        OK demo2.adb
15357                          OK gen_list.ads
15358                          OK gen_list.adb
15359                          OK instr.ads
15360                          OK instr-child.ads
15361
15362 $ gnatls -d -s -a demo1.o
15363 demo1.adb
15364 /home/comar/local/adainclude/ada.ads
15365 /home/comar/local/adainclude/a-finali.ads
15366 /home/comar/local/adainclude/a-filico.ads
15367 /home/comar/local/adainclude/a-stream.ads
15368 /home/comar/local/adainclude/a-tags.ads
15369 gen_list.ads
15370 gen_list.adb
15371 /home/comar/local/adainclude/gnat.ads
15372 /home/comar/local/adainclude/g-io.ads
15373 instr.ads
15374 /home/comar/local/adainclude/system.ads
15375 /home/comar/local/adainclude/s-exctab.ads
15376 /home/comar/local/adainclude/s-finimp.ads
15377 /home/comar/local/adainclude/s-finroo.ads
15378 /home/comar/local/adainclude/s-secsta.ads
15379 /home/comar/local/adainclude/s-stalib.ads
15380 /home/comar/local/adainclude/s-stoele.ads
15381 /home/comar/local/adainclude/s-stratt.ads
15382 /home/comar/local/adainclude/s-tasoli.ads
15383 /home/comar/local/adainclude/s-unstyp.ads
15384 /home/comar/local/adainclude/unchconv.ads
15385 @end smallexample
15386 @end ifclear
15387
15388 @ifset vms
15389 @smallexample
15390 GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
15391
15392 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
15393 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
15394 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
15395 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
15396 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
15397 demo1.adb
15398 gen_list.ads
15399 gen_list.adb
15400 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
15401 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
15402 instr.ads
15403 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
15404 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
15405 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
15406 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
15407 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
15408 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
15409 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
15410 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
15411 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
15412 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
15413 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
15414 @end smallexample
15415 @end ifset
15416
15417 @node Cleaning Up Using gnatclean
15418 @chapter Cleaning Up Using @code{gnatclean}
15419 @findex gnatclean
15420 @cindex Cleaning tool
15421
15422 @noindent
15423 @code{gnatclean} is a tool that allows the deletion of files produced by the
15424 compiler, binder and linker, including ALI files, object files, tree files,
15425 expanded source files, library files, interface copy source files, binder
15426 generated files and executable files.
15427
15428 @menu
15429 * Running gnatclean::
15430 * Switches for gnatclean::
15431 @c * Examples of gnatclean Usage::
15432 @end menu
15433
15434 @node Running gnatclean
15435 @section Running @code{gnatclean}
15436
15437 @noindent
15438 The @code{gnatclean} command has the form:
15439
15440 @smallexample
15441 $ gnatclean switches @var{names}
15442 @end smallexample
15443
15444 @noindent
15445 @var{names} is a list of source file names. Suffixes @code{.^ads^ADS^} and
15446 @code{^adb^ADB^} may be omitted. If a project file is specified using switch
15447 @code{^-P^/PROJECT_FILE=^}, then @var{names} may be completely omitted.
15448
15449 @noindent
15450 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
15451 if switch @code{^-c^/COMPILER_FILES_ONLY^} is not specified, by the binder and
15452 the linker. In informative-only mode, specified by switch
15453 @code{^-n^/NODELETE^}, the list of files that would have been deleted in
15454 normal mode is listed, but no file is actually deleted.
15455
15456 @node Switches for gnatclean
15457 @section Switches for @code{gnatclean}
15458
15459 @noindent
15460 @code{gnatclean} recognizes the following switches:
15461
15462 @table @option
15463 @c !sort!
15464 @cindex @option{--version} @command{gnatclean}
15465 Display Copyright and version, then exit disregarding all other options.
15466
15467 @item --help
15468 @cindex @option{--help} @command{gnatclean}
15469 If @option{--version} was not used, display usage, then exit disregarding
15470 all other options.
15471
15472 @item ^--subdirs^/SUBDIRS^=subdir
15473 Actual object directory of each project file is the subdirectory subdir of the
15474 object directory specified or defauted in the project file.
15475
15476 @item ^--unchecked-shared-lib-imports^/UNCHECKED_SHARED_LIB_IMPORTS^
15477 By default, shared library projects are not allowed to import static library
15478 projects. When this switch is used on the command line, this restriction is
15479 relaxed.
15480
15481 @item ^-c^/COMPILER_FILES_ONLY^
15482 @cindex @option{^-c^/COMPILER_FILES_ONLY^} (@code{gnatclean})
15483 Only attempt to delete the files produced by the compiler, not those produced
15484 by the binder or the linker. The files that are not to be deleted are library
15485 files, interface copy files, binder generated files and executable files.
15486
15487 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
15488 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatclean})
15489 Indicate that ALI and object files should normally be found in directory
15490 @var{dir}.
15491
15492 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
15493 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatclean})
15494 When using project files, if some errors or warnings are detected during
15495 parsing and verbose mode is not in effect (no use of switch
15496 ^-v^/VERBOSE^), then error lines start with the full path name of the project
15497 file, rather than its simple file name.
15498
15499 @item ^-h^/HELP^
15500 @cindex @option{^-h^/HELP^} (@code{gnatclean})
15501 Output a message explaining the usage of @code{^gnatclean^gnatclean^}.
15502
15503 @item ^-n^/NODELETE^
15504 @cindex @option{^-n^/NODELETE^} (@code{gnatclean})
15505 Informative-only mode. Do not delete any files. Output the list of the files
15506 that would have been deleted if this switch was not specified.
15507
15508 @item ^-P^/PROJECT_FILE=^@var{project}
15509 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatclean})
15510 Use project file @var{project}. Only one such switch can be used.
15511 When cleaning a project file, the files produced by the compilation of the
15512 immediate sources or inherited sources of the project files are to be
15513 deleted. This is not depending on the presence or not of executable names
15514 on the command line.
15515
15516 @item ^-q^/QUIET^
15517 @cindex @option{^-q^/QUIET^} (@code{gnatclean})
15518 Quiet output. If there are no errors, do not output anything, except in
15519 verbose mode (switch ^-v^/VERBOSE^) or in informative-only mode
15520 (switch ^-n^/NODELETE^).
15521
15522 @item ^-r^/RECURSIVE^
15523 @cindex @option{^-r^/RECURSIVE^} (@code{gnatclean})
15524 When a project file is specified (using switch ^-P^/PROJECT_FILE=^),
15525 clean all imported and extended project files, recursively. If this switch
15526 is not specified, only the files related to the main project file are to be
15527 deleted. This switch has no effect if no project file is specified.
15528
15529 @item ^-v^/VERBOSE^
15530 @cindex @option{^-v^/VERBOSE^} (@code{gnatclean})
15531 Verbose mode.
15532
15533 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
15534 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (@code{gnatclean})
15535 Indicates the verbosity of the parsing of GNAT project files.
15536 @xref{Switches Related to Project Files}.
15537
15538 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
15539 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (@code{gnatclean})
15540 Indicates that external variable @var{name} has the value @var{value}.
15541 The Project Manager will use this value for occurrences of
15542 @code{external(name)} when parsing the project file.
15543 @xref{Switches Related to Project Files}.
15544
15545 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
15546 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatclean})
15547 When searching for ALI and object files, look in directory
15548 @var{dir}.
15549
15550 @item ^-I^/SEARCH=^@var{dir}
15551 @cindex @option{^-I^/SEARCH^} (@code{gnatclean})
15552 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}}.
15553
15554 @item ^-I-^/NOCURRENT_DIRECTORY^
15555 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatclean})
15556 @cindex Source files, suppressing search
15557 Do not look for ALI or object files in the directory
15558 where @code{gnatclean} was invoked.
15559
15560 @end table
15561
15562 @c @node Examples of gnatclean Usage
15563 @c @section Examples of @code{gnatclean} Usage
15564
15565 @ifclear vms
15566 @node GNAT and Libraries
15567 @chapter GNAT and Libraries
15568 @cindex Library, building, installing, using
15569
15570 @noindent
15571 This chapter describes how to build and use libraries with GNAT, and also shows
15572 how to recompile the GNAT run-time library. You should be familiar with the
15573 Project Manager facility (@pxref{GNAT Project Manager}) before reading this
15574 chapter.
15575
15576 @menu
15577 * Introduction to Libraries in GNAT::
15578 * General Ada Libraries::
15579 * Stand-alone Ada Libraries::
15580 * Rebuilding the GNAT Run-Time Library::
15581 @end menu
15582
15583 @node Introduction to Libraries in GNAT
15584 @section Introduction to Libraries in GNAT
15585
15586 @noindent
15587 A library is, conceptually, a collection of objects which does not have its
15588 own main thread of execution, but rather provides certain services to the
15589 applications that use it. A library can be either statically linked with the
15590 application, in which case its code is directly included in the application,
15591 or, on platforms that support it, be dynamically linked, in which case
15592 its code is shared by all applications making use of this library.
15593
15594 GNAT supports both types of libraries.
15595 In the static case, the compiled code can be provided in different ways. The
15596 simplest approach is to provide directly the set of objects resulting from
15597 compilation of the library source files. Alternatively, you can group the
15598 objects into an archive using whatever commands are provided by the operating
15599 system. For the latter case, the objects are grouped into a shared library.
15600
15601 In the GNAT environment, a library has three types of components:
15602 @itemize @bullet
15603 @item
15604 Source files.
15605 @item
15606 @file{ALI} files.
15607 @xref{The Ada Library Information Files}.
15608 @item
15609 Object files, an archive or a shared library.
15610 @end itemize
15611
15612 @noindent
15613 A GNAT library may expose all its source files, which is useful for
15614 documentation purposes. Alternatively, it may expose only the units needed by
15615 an external user to make use of the library. That is to say, the specs
15616 reflecting the library services along with all the units needed to compile
15617 those specs, which can include generic bodies or any body implementing an
15618 inlined routine. In the case of @emph{stand-alone libraries} those exposed
15619 units are called @emph{interface units} (@pxref{Stand-alone Ada Libraries}).
15620
15621 All compilation units comprising an application, including those in a library,
15622 need to be elaborated in an order partially defined by Ada's semantics. GNAT
15623 computes the elaboration order from the @file{ALI} files and this is why they
15624 constitute a mandatory part of GNAT libraries.
15625 @emph{Stand-alone libraries} are the exception to this rule because a specific
15626 library elaboration routine is produced independently of the application(s)
15627 using the library.
15628
15629 @node General Ada Libraries
15630 @section General Ada Libraries
15631
15632 @menu
15633 * Building a library::
15634 * Installing a library::
15635 * Using a library::
15636 @end menu
15637
15638 @node Building a library
15639 @subsection Building a library
15640
15641 @noindent
15642 The easiest way to build a library is to use the Project Manager,
15643 which supports a special type of project called a @emph{Library Project}
15644 (@pxref{Library Projects}).
15645
15646 A project is considered a library project, when two project-level attributes
15647 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
15648 control different aspects of library configuration, additional optional
15649 project-level attributes can be specified:
15650 @table @code
15651 @item Library_Kind
15652 This attribute controls whether the library is to be static or dynamic
15653
15654 @item Library_Version
15655 This attribute specifies the library version; this value is used
15656 during dynamic linking of shared libraries to determine if the currently
15657 installed versions of the binaries are compatible.
15658
15659 @item Library_Options
15660 @item Library_GCC
15661 These attributes specify additional low-level options to be used during
15662 library generation, and redefine the actual application used to generate
15663 library.
15664 @end table
15665
15666 @noindent
15667 The GNAT Project Manager takes full care of the library maintenance task,
15668 including recompilation of the source files for which objects do not exist
15669 or are not up to date, assembly of the library archive, and installation of
15670 the library (i.e., copying associated source, object and @file{ALI} files
15671 to the specified location).
15672
15673 Here is a simple library project file:
15674 @smallexample @c ada
15675 project My_Lib is
15676    for Source_Dirs use ("src1", "src2");
15677    for Object_Dir use "obj";
15678    for Library_Name use "mylib";
15679    for Library_Dir use "lib";
15680    for Library_Kind use "dynamic";
15681 end My_lib;
15682 @end smallexample
15683
15684 @noindent
15685 and the compilation command to build and install the library:
15686
15687 @smallexample @c ada
15688   $ gnatmake -Pmy_lib
15689 @end smallexample
15690
15691 @noindent
15692 It is not entirely trivial to perform manually all the steps required to
15693 produce a library. We recommend that you use the GNAT Project Manager
15694 for this task. In special cases where this is not desired, the necessary
15695 steps are discussed below.
15696
15697 There are various possibilities for compiling the units that make up the
15698 library: for example with a Makefile (@pxref{Using the GNU make Utility}) or
15699 with a conventional script. For simple libraries, it is also possible to create
15700 a dummy main program which depends upon all the packages that comprise the
15701 interface of the library. This dummy main program can then be given to
15702 @command{gnatmake}, which will ensure that all necessary objects are built.
15703
15704 After this task is accomplished, you should follow the standard procedure
15705 of the underlying operating system to produce the static or shared library.
15706
15707 Here is an example of such a dummy program:
15708 @smallexample @c ada
15709 @group
15710 with My_Lib.Service1;
15711 with My_Lib.Service2;
15712 with My_Lib.Service3;
15713 procedure My_Lib_Dummy is
15714 begin
15715    null;
15716 end;
15717 @end group
15718 @end smallexample
15719
15720 @noindent
15721 Here are the generic commands that will build an archive or a shared library.
15722
15723 @smallexample
15724 # compiling the library
15725 $ gnatmake -c my_lib_dummy.adb
15726
15727 # we don't need the dummy object itself
15728 $ rm my_lib_dummy.o my_lib_dummy.ali
15729
15730 # create an archive with the remaining objects
15731 $ ar rc libmy_lib.a *.o
15732 # some systems may require "ranlib" to be run as well
15733
15734 # or create a shared library
15735 $ gcc -shared -o libmy_lib.so *.o
15736 # some systems may require the code to have been compiled with -fPIC
15737
15738 # remove the object files that are now in the library
15739 $ rm *.o
15740
15741 # Make the ALI files read-only so that gnatmake will not try to
15742 # regenerate the objects that are in the library
15743 $ chmod -w *.ali
15744 @end smallexample
15745
15746 @noindent
15747 Please note that the library must have a name of the form @file{lib@var{xxx}.a}
15748 or @file{lib@var{xxx}.so} (or @file{lib@var{xxx}.dll} on Windows) in order to
15749 be accessed by the directive @option{-l@var{xxx}} at link time.
15750
15751 @node Installing a library
15752 @subsection Installing a library
15753 @cindex @code{ADA_PROJECT_PATH}
15754 @cindex @code{GPR_PROJECT_PATH}
15755
15756 @noindent
15757 If you use project files, library installation is part of the library build
15758 process (@pxref{Installing a library with project files}).
15759
15760 When project files are not an option, it is also possible, but not recommended,
15761 to install the library so that the sources needed to use the library are on the
15762 Ada source path and the ALI files & libraries be on the Ada Object path (see
15763 @ref{Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
15764 administrator can place general-purpose libraries in the default compiler
15765 paths, by specifying the libraries' location in the configuration files
15766 @file{ada_source_path} and @file{ada_object_path}. These configuration files
15767 must be located in the GNAT installation tree at the same place as the gcc spec
15768 file. The location of the gcc spec file can be determined as follows:
15769 @smallexample
15770 $ gcc -v
15771 @end smallexample
15772
15773 @noindent
15774 The configuration files mentioned above have a simple format: each line
15775 must contain one unique directory name.
15776 Those names are added to the corresponding path
15777 in their order of appearance in the file. The names can be either absolute
15778 or relative; in the latter case, they are relative to where theses files
15779 are located.
15780
15781 The files @file{ada_source_path} and @file{ada_object_path} might not be
15782 present in a
15783 GNAT installation, in which case, GNAT will look for its run-time library in
15784 the directories @file{adainclude} (for the sources) and @file{adalib} (for the
15785 objects and @file{ALI} files). When the files exist, the compiler does not
15786 look in @file{adainclude} and @file{adalib}, and thus the
15787 @file{ada_source_path} file
15788 must contain the location for the GNAT run-time sources (which can simply
15789 be @file{adainclude}). In the same way, the @file{ada_object_path} file must
15790 contain the location for the GNAT run-time objects (which can simply
15791 be @file{adalib}).
15792
15793 You can also specify a new default path to the run-time library at compilation
15794 time with the switch @option{--RTS=rts-path}. You can thus choose / change
15795 the run-time library you want your program to be compiled with. This switch is
15796 recognized by @command{gcc}, @command{gnatmake}, @command{gnatbind},
15797 @command{gnatls}, @command{gnatfind} and @command{gnatxref}.
15798
15799 It is possible to install a library before or after the standard GNAT
15800 library, by reordering the lines in the configuration files. In general, a
15801 library must be installed before the GNAT library if it redefines
15802 any part of it.
15803
15804 @node Using a library
15805 @subsection Using a library
15806
15807 @noindent Once again, the project facility greatly simplifies the use of
15808 libraries. In this context, using a library is just a matter of adding a
15809 @code{with} clause in the user project. For instance, to make use of the
15810 library @code{My_Lib} shown in examples in earlier sections, you can
15811 write:
15812
15813 @smallexample @c projectfile
15814 with "my_lib";
15815 project My_Proj is
15816   @dots{}
15817 end My_Proj;
15818 @end smallexample
15819
15820 Even if you have a third-party, non-Ada library, you can still use GNAT's
15821 Project Manager facility to provide a wrapper for it. For example, the
15822 following project, when @code{with}ed by your main project, will link with the
15823 third-party library @file{liba.a}:
15824
15825 @smallexample @c projectfile
15826 @group
15827 project Liba is
15828    for Externally_Built use "true";
15829    for Source_Files use ();
15830    for Library_Dir use "lib";
15831    for Library_Name use "a";
15832    for Library_Kind use "static";
15833 end Liba;
15834 @end group
15835 @end smallexample
15836 This is an alternative to the use of @code{pragma Linker_Options}. It is
15837 especially interesting in the context of systems with several interdependent
15838 static libraries where finding a proper linker order is not easy and best be
15839 left to the tools having visibility over project dependence information.
15840
15841 @noindent
15842 In order to use an Ada library manually, you need to make sure that this
15843 library is on both your source and object path
15844 (see @ref{Search Paths and the Run-Time Library (RTL)}
15845 and @ref{Search Paths for gnatbind}). Furthermore, when the objects are grouped
15846 in an archive or a shared library, you need to specify the desired
15847 library at link time.
15848
15849 For example, you can use the library @file{mylib} installed in
15850 @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
15851
15852 @smallexample
15853 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
15854   -largs -lmy_lib
15855 @end smallexample
15856
15857 @noindent
15858 This can be expressed more simply:
15859 @smallexample
15860 $ gnatmake my_appl
15861 @end smallexample
15862 @noindent
15863 when the following conditions are met:
15864 @itemize @bullet
15865 @item
15866 @file{/dir/my_lib_src} has been added by the user to the environment
15867 variable @env{ADA_INCLUDE_PATH}, or by the administrator to the file
15868 @file{ada_source_path}
15869 @item
15870 @file{/dir/my_lib_obj} has been added by the user to the environment
15871 variable @env{ADA_OBJECTS_PATH}, or by the administrator to the file
15872 @file{ada_object_path}
15873 @item
15874 a pragma @code{Linker_Options} has been added to one of the sources.
15875 For example:
15876
15877 @smallexample @c ada
15878 pragma Linker_Options ("-lmy_lib");
15879 @end smallexample
15880 @end itemize
15881
15882 @node Stand-alone Ada Libraries
15883 @section Stand-alone Ada Libraries
15884 @cindex Stand-alone library, building, using
15885
15886 @menu
15887 * Introduction to Stand-alone Libraries::
15888 * Building a Stand-alone Library::
15889 * Creating a Stand-alone Library to be used in a non-Ada context::
15890 * Restrictions in Stand-alone Libraries::
15891 @end menu
15892
15893 @node Introduction to Stand-alone Libraries
15894 @subsection Introduction to Stand-alone Libraries
15895
15896 @noindent
15897 A Stand-alone Library (abbreviated ``SAL'') is a library that contains the
15898 necessary code to
15899 elaborate the Ada units that are included in the library. In contrast with
15900 an ordinary library, which consists of all sources, objects and @file{ALI}
15901 files of the
15902 library, a SAL may specify a restricted subset of compilation units
15903 to serve as a library interface. In this case, the fully
15904 self-sufficient set of files will normally consist of an objects
15905 archive, the sources of interface units' specs, and the @file{ALI}
15906 files of interface units.
15907 If an interface spec contains a generic unit or an inlined subprogram,
15908 the body's
15909 source must also be provided; if the units that must be provided in the source
15910 form depend on other units, the source and @file{ALI} files of those must
15911 also be provided.
15912
15913 The main purpose of a SAL is to minimize the recompilation overhead of client
15914 applications when a new version of the library is installed. Specifically,
15915 if the interface sources have not changed, client applications do not need to
15916 be recompiled. If, furthermore, a SAL is provided in the shared form and its
15917 version, controlled by @code{Library_Version} attribute, is not changed,
15918 then the clients do not need to be relinked.
15919
15920 SALs also allow the library providers to minimize the amount of library source
15921 text exposed to the clients.  Such ``information hiding'' might be useful or
15922 necessary for various reasons.
15923
15924 Stand-alone libraries are also well suited to be used in an executable whose
15925 main routine is not written in Ada.
15926
15927 @node Building a Stand-alone Library
15928 @subsection Building a Stand-alone Library
15929
15930 @noindent
15931 GNAT's Project facility provides a simple way of building and installing
15932 stand-alone libraries; see @ref{Stand-alone Library Projects}.
15933 To be a Stand-alone Library Project, in addition to the two attributes
15934 that make a project a Library Project (@code{Library_Name} and
15935 @code{Library_Dir}; see @ref{Library Projects}), the attribute
15936 @code{Library_Interface} must be defined.  For example:
15937
15938 @smallexample @c projectfile
15939 @group
15940    for Library_Dir use "lib_dir";
15941    for Library_Name use "dummy";
15942    for Library_Interface use ("int1", "int1.child");
15943 @end group
15944 @end smallexample
15945
15946 @noindent
15947 Attribute @code{Library_Interface} has a non-empty string list value,
15948 each string in the list designating a unit contained in an immediate source
15949 of the project file.
15950
15951 When a Stand-alone Library is built, first the binder is invoked to build
15952 a package whose name depends on the library name
15953 (@file{^b~dummy.ads/b^B$DUMMY.ADS/B^} in the example above).
15954 This binder-generated package includes initialization and
15955 finalization procedures whose
15956 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
15957 in the example
15958 above). The object corresponding to this package is included in the library.
15959
15960 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
15961 calling of these procedures if a static SAL is built, or if a shared SAL
15962 is built
15963 with the project-level attribute @code{Library_Auto_Init} set to
15964 @code{"false"}.
15965
15966 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
15967 (those that are listed in attribute @code{Library_Interface}) are copied to
15968 the Library Directory. As a consequence, only the Interface Units may be
15969 imported from Ada units outside of the library. If other units are imported,
15970 the binding phase will fail.
15971
15972 The attribute @code{Library_Src_Dir} may be specified for a
15973 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
15974 single string value. Its value must be the path (absolute or relative to the
15975 project directory) of an existing directory. This directory cannot be the
15976 object directory or one of the source directories, but it can be the same as
15977 the library directory. The sources of the Interface
15978 Units of the library that are needed by an Ada client of the library will be
15979 copied to the designated directory, called the Interface Copy directory.
15980 These sources include the specs of the Interface Units, but they may also
15981 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
15982 are used, or when there is a generic unit in the spec. Before the sources
15983 are copied to the Interface Copy directory, an attempt is made to delete all
15984 files in the Interface Copy directory.
15985
15986 Building stand-alone libraries by hand is somewhat tedious, but for those
15987 occasions when it is necessary here are the steps that you need to perform:
15988 @itemize @bullet
15989 @item
15990 Compile all library sources.
15991
15992 @item
15993 Invoke the binder with the switch @option{-n} (No Ada main program),
15994 with all the @file{ALI} files of the interfaces, and
15995 with the switch @option{-L} to give specific names to the @code{init}
15996 and @code{final} procedures.  For example:
15997 @smallexample
15998   gnatbind -n int1.ali int2.ali -Lsal1
15999 @end smallexample
16000
16001 @item
16002 Compile the binder generated file:
16003 @smallexample
16004   gcc -c b~int2.adb
16005 @end smallexample
16006
16007 @item
16008 Link the dynamic library with all the necessary object files,
16009 indicating to the linker the names of the @code{init} (and possibly
16010 @code{final}) procedures for automatic initialization (and finalization).
16011 The built library should be placed in a directory different from
16012 the object directory.
16013
16014 @item
16015 Copy the @code{ALI} files of the interface to the library directory,
16016 add in this copy an indication that it is an interface to a SAL
16017 (i.e., add a word @option{SL} on the line in the @file{ALI} file that starts
16018 with letter ``P'') and make the modified copy of the @file{ALI} file
16019 read-only.
16020 @end itemize
16021
16022 @noindent
16023 Using SALs is not different from using other libraries
16024 (see @ref{Using a library}).
16025
16026 @node Creating a Stand-alone Library to be used in a non-Ada context
16027 @subsection Creating a Stand-alone Library to be used in a non-Ada context
16028
16029 @noindent
16030 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
16031 a non-Ada context.
16032
16033 The only extra step required is to ensure that library interface subprograms
16034 are compatible with the main program, by means of @code{pragma Export}
16035 or @code{pragma Convention}.
16036
16037 Here is an example of simple library interface for use with C main program:
16038
16039 @smallexample @c ada
16040 package My_Package is
16041
16042    procedure Do_Something;
16043    pragma Export (C, Do_Something, "do_something");
16044
16045    procedure Do_Something_Else;
16046    pragma Export (C, Do_Something_Else, "do_something_else");
16047
16048 end My_Package;
16049 @end smallexample
16050
16051 @noindent
16052 On the foreign language side, you must provide a ``foreign'' view of the
16053 library interface; remember that it should contain elaboration routines in
16054 addition to interface subprograms.
16055
16056 The example below shows the content of @code{mylib_interface.h} (note
16057 that there is no rule for the naming of this file, any name can be used)
16058 @smallexample
16059 /* the library elaboration procedure */
16060 extern void mylibinit (void);
16061
16062 /* the library finalization procedure */
16063 extern void mylibfinal (void);
16064
16065 /* the interface exported by the library */
16066 extern void do_something (void);
16067 extern void do_something_else (void);
16068 @end smallexample
16069
16070 @noindent
16071 Libraries built as explained above can be used from any program, provided
16072 that the elaboration procedures (named @code{mylibinit} in the previous
16073 example) are called before the library services are used. Any number of
16074 libraries can be used simultaneously, as long as the elaboration
16075 procedure of each library is called.
16076
16077 Below is an example of a C program that uses the @code{mylib} library.
16078
16079 @smallexample
16080 #include "mylib_interface.h"
16081
16082 int
16083 main (void)
16084 @{
16085    /* First, elaborate the library before using it */
16086    mylibinit ();
16087
16088    /* Main program, using the library exported entities */
16089    do_something ();
16090    do_something_else ();
16091
16092    /* Library finalization at the end of the program */
16093    mylibfinal ();
16094    return 0;
16095 @}
16096 @end smallexample
16097
16098 @noindent
16099 Note that invoking any library finalization procedure generated by
16100 @code{gnatbind} shuts down the Ada run-time environment.
16101 Consequently, the
16102 finalization of all Ada libraries must be performed at the end of the program.
16103 No call to these libraries or to the Ada run-time library should be made
16104 after the finalization phase.
16105
16106 @node Restrictions in Stand-alone Libraries
16107 @subsection Restrictions in Stand-alone Libraries
16108
16109 @noindent
16110 The pragmas listed below should be used with caution inside libraries,
16111 as they can create incompatibilities with other Ada libraries:
16112 @itemize @bullet
16113 @item pragma @code{Locking_Policy}
16114 @item pragma @code{Queuing_Policy}
16115 @item pragma @code{Task_Dispatching_Policy}
16116 @item pragma @code{Unreserve_All_Interrupts}
16117 @end itemize
16118
16119 @noindent
16120 When using a library that contains such pragmas, the user must make sure
16121 that all libraries use the same pragmas with the same values. Otherwise,
16122 @code{Program_Error} will
16123 be raised during the elaboration of the conflicting
16124 libraries. The usage of these pragmas and its consequences for the user
16125 should therefore be well documented.
16126
16127 Similarly, the traceback in the exception occurrence mechanism should be
16128 enabled or disabled in a consistent manner across all libraries.
16129 Otherwise, Program_Error will be raised during the elaboration of the
16130 conflicting libraries.
16131
16132 If the @code{Version} or @code{Body_Version}
16133 attributes are used inside a library, then you need to
16134 perform a @code{gnatbind} step that specifies all @file{ALI} files in all
16135 libraries, so that version identifiers can be properly computed.
16136 In practice these attributes are rarely used, so this is unlikely
16137 to be a consideration.
16138
16139 @node  Rebuilding the GNAT Run-Time Library
16140 @section Rebuilding the GNAT Run-Time Library
16141 @cindex GNAT Run-Time Library, rebuilding
16142 @cindex Building the GNAT Run-Time Library
16143 @cindex Rebuilding the GNAT Run-Time Library
16144 @cindex Run-Time Library, rebuilding
16145
16146 @noindent
16147 It may be useful to recompile the GNAT library in various contexts, the
16148 most important one being the use of partition-wide configuration pragmas
16149 such as @code{Normalize_Scalars}. A special Makefile called
16150 @code{Makefile.adalib} is provided to that effect and can be found in
16151 the directory containing the GNAT library. The location of this
16152 directory depends on the way the GNAT environment has been installed and can
16153 be determined by means of the command:
16154
16155 @smallexample
16156 $ gnatls -v
16157 @end smallexample
16158
16159 @noindent
16160 The last entry in the object search path usually contains the
16161 gnat library. This Makefile contains its own documentation and in
16162 particular the set of instructions needed to rebuild a new library and
16163 to use it.
16164
16165 @node Using the GNU make Utility
16166 @chapter Using the GNU @code{make} Utility
16167 @findex make
16168
16169 @noindent
16170 This chapter offers some examples of makefiles that solve specific
16171 problems. It does not explain how to write a makefile (@pxref{Top,, GNU
16172 make, make, GNU @code{make}}), nor does it try to replace the
16173 @command{gnatmake} utility (@pxref{The GNAT Make Program gnatmake}).
16174
16175 All the examples in this section are specific to the GNU version of
16176 make. Although @command{make} is a standard utility, and the basic language
16177 is the same, these examples use some advanced features found only in
16178 @code{GNU make}.
16179
16180 @menu
16181 * Using gnatmake in a Makefile::
16182 * Automatically Creating a List of Directories::
16183 * Generating the Command Line Switches::
16184 * Overcoming Command Line Length Limits::
16185 @end menu
16186
16187 @node Using gnatmake in a Makefile
16188 @section Using gnatmake in a Makefile
16189 @findex makefile
16190 @cindex GNU make
16191
16192 @noindent
16193 Complex project organizations can be handled in a very powerful way by
16194 using GNU make combined with gnatmake. For instance, here is a Makefile
16195 which allows you to build each subsystem of a big project into a separate
16196 shared library. Such a makefile allows you to significantly reduce the link
16197 time of very big applications while maintaining full coherence at
16198 each step of the build process.
16199
16200 The list of dependencies are handled automatically by
16201 @command{gnatmake}. The Makefile is simply used to call gnatmake in each of
16202 the appropriate directories.
16203
16204 Note that you should also read the example on how to automatically
16205 create the list of directories
16206 (@pxref{Automatically Creating a List of Directories})
16207 which might help you in case your project has a lot of subdirectories.
16208
16209 @smallexample
16210 @iftex
16211 @leftskip=0cm
16212 @font@heightrm=cmr8
16213 @heightrm
16214 @end iftex
16215 ## This Makefile is intended to be used with the following directory
16216 ## configuration:
16217 ##  - The sources are split into a series of csc (computer software components)
16218 ##    Each of these csc is put in its own directory.
16219 ##    Their name are referenced by the directory names.
16220 ##    They will be compiled into shared library (although this would also work
16221 ##    with static libraries
16222 ##  - The main program (and possibly other packages that do not belong to any
16223 ##    csc is put in the top level directory (where the Makefile is).
16224 ##       toplevel_dir __ first_csc  (sources) __ lib (will contain the library)
16225 ##                    \_ second_csc (sources) __ lib (will contain the library)
16226 ##                    \_ @dots{}
16227 ## Although this Makefile is build for shared library, it is easy to modify
16228 ## to build partial link objects instead (modify the lines with -shared and
16229 ## gnatlink below)
16230 ##
16231 ## With this makefile, you can change any file in the system or add any new
16232 ## file, and everything will be recompiled correctly (only the relevant shared
16233 ## objects will be recompiled, and the main program will be re-linked).
16234
16235 # The list of computer software component for your project. This might be
16236 # generated automatically.
16237 CSC_LIST=aa bb cc
16238
16239 # Name of the main program (no extension)
16240 MAIN=main
16241
16242 # If we need to build objects with -fPIC, uncomment the following line
16243 #NEED_FPIC=-fPIC
16244
16245 # The following variable should give the directory containing libgnat.so
16246 # You can get this directory through 'gnatls -v'. This is usually the last
16247 # directory in the Object_Path.
16248 GLIB=@dots{}
16249
16250 # The directories for the libraries
16251 # (This macro expands the list of CSC to the list of shared libraries, you
16252 # could simply use the expanded form:
16253 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
16254 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
16255
16256 $@{MAIN@}: objects $@{LIB_DIR@}
16257     gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
16258     gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
16259
16260 objects::
16261     # recompile the sources
16262     gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
16263
16264 # Note: In a future version of GNAT, the following commands will be simplified
16265 # by a new tool, gnatmlib
16266 $@{LIB_DIR@}:
16267     mkdir -p $@{dir $@@ @}
16268     cd $@{dir $@@ @} && gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
16269     cd $@{dir $@@ @} && cp -f ../*.ali .
16270
16271 # The dependencies for the modules
16272 # Note that we have to force the expansion of *.o, since in some cases
16273 # make won't be able to do it itself.
16274 aa/lib/libaa.so: $@{wildcard aa/*.o@}
16275 bb/lib/libbb.so: $@{wildcard bb/*.o@}
16276 cc/lib/libcc.so: $@{wildcard cc/*.o@}
16277
16278 # Make sure all of the shared libraries are in the path before starting the
16279 # program
16280 run::
16281     LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
16282
16283 clean::
16284     $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
16285     $@{RM@} $@{CSC_LIST:%=%/*.ali@}
16286     $@{RM@} $@{CSC_LIST:%=%/*.o@}
16287     $@{RM@} *.o *.ali $@{MAIN@}
16288 @end smallexample
16289
16290 @node Automatically Creating a List of Directories
16291 @section Automatically Creating a List of Directories
16292
16293 @noindent
16294 In most makefiles, you will have to specify a list of directories, and
16295 store it in a variable. For small projects, it is often easier to
16296 specify each of them by hand, since you then have full control over what
16297 is the proper order for these directories, which ones should be
16298 included.
16299
16300 However, in larger projects, which might involve hundreds of
16301 subdirectories, it might be more convenient to generate this list
16302 automatically.
16303
16304 The example below presents two methods. The first one, although less
16305 general, gives you more control over the list. It involves wildcard
16306 characters, that are automatically expanded by @command{make}. Its
16307 shortcoming is that you need to explicitly specify some of the
16308 organization of your project, such as for instance the directory tree
16309 depth, whether some directories are found in a separate tree, @enddots{}
16310
16311 The second method is the most general one. It requires an external
16312 program, called @command{find}, which is standard on all Unix systems. All
16313 the directories found under a given root directory will be added to the
16314 list.
16315
16316 @smallexample
16317 @iftex
16318 @leftskip=0cm
16319 @font@heightrm=cmr8
16320 @heightrm
16321 @end iftex
16322 # The examples below are based on the following directory hierarchy:
16323 # All the directories can contain any number of files
16324 # ROOT_DIRECTORY ->  a  ->  aa  ->  aaa
16325 #                       ->  ab
16326 #                       ->  ac
16327 #                ->  b  ->  ba  ->  baa
16328 #                       ->  bb
16329 #                       ->  bc
16330 # This Makefile creates a variable called DIRS, that can be reused any time
16331 # you need this list (see the other examples in this section)
16332
16333 # The root of your project's directory hierarchy
16334 ROOT_DIRECTORY=.
16335
16336 ####
16337 # First method: specify explicitly the list of directories
16338 # This allows you to specify any subset of all the directories you need.
16339 ####
16340
16341 DIRS := a/aa/ a/ab/ b/ba/
16342
16343 ####
16344 # Second method: use wildcards
16345 # Note that the argument(s) to wildcard below should end with a '/'.
16346 # Since wildcards also return file names, we have to filter them out
16347 # to avoid duplicate directory names.
16348 # We thus use make's @code{dir} and @code{sort} functions.
16349 # It sets DIRs to the following value (note that the directories aaa and baa
16350 # are not given, unless you change the arguments to wildcard).
16351 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
16352 ####
16353
16354 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
16355                     $@{ROOT_DIRECTORY@}/*/*/@}@}@}
16356
16357 ####
16358 # Third method: use an external program
16359 # This command is much faster if run on local disks, avoiding NFS slowdowns.
16360 # This is the most complete command: it sets DIRs to the following value:
16361 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
16362 ####
16363
16364 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
16365
16366 @end smallexample
16367
16368 @node Generating the Command Line Switches
16369 @section Generating the Command Line Switches
16370
16371 @noindent
16372 Once you have created the list of directories as explained in the
16373 previous section (@pxref{Automatically Creating a List of Directories}),
16374 you can easily generate the command line arguments to pass to gnatmake.
16375
16376 For the sake of completeness, this example assumes that the source path
16377 is not the same as the object path, and that you have two separate lists
16378 of directories.
16379
16380 @smallexample
16381 # see "Automatically creating a list of directories" to create
16382 # these variables
16383 SOURCE_DIRS=
16384 OBJECT_DIRS=
16385
16386 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
16387 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
16388
16389 all:
16390         gnatmake $@{GNATMAKE_SWITCHES@} main_unit
16391 @end smallexample
16392
16393 @node Overcoming Command Line Length Limits
16394 @section Overcoming Command Line Length Limits
16395
16396 @noindent
16397 One problem that might be encountered on big projects is that many
16398 operating systems limit the length of the command line. It is thus hard to give
16399 gnatmake the list of source and object directories.
16400
16401 This example shows how you can set up environment variables, which will
16402 make @command{gnatmake} behave exactly as if the directories had been
16403 specified on the command line, but have a much higher length limit (or
16404 even none on most systems).
16405
16406 It assumes that you have created a list of directories in your Makefile,
16407 using one of the methods presented in
16408 @ref{Automatically Creating a List of Directories}.
16409 For the sake of completeness, we assume that the object
16410 path (where the ALI files are found) is different from the sources patch.
16411
16412 Note a small trick in the Makefile below: for efficiency reasons, we
16413 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
16414 expanded immediately by @code{make}. This way we overcome the standard
16415 make behavior which is to expand the variables only when they are
16416 actually used.
16417
16418 On Windows, if you are using the standard Windows command shell, you must
16419 replace colons with semicolons in the assignments to these variables.
16420
16421 @smallexample
16422 @iftex
16423 @leftskip=0cm
16424 @font@heightrm=cmr8
16425 @heightrm
16426 @end iftex
16427 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECT_PATH.
16428 # This is the same thing as putting the -I arguments on the command line.
16429 # (the equivalent of using -aI on the command line would be to define
16430 #  only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECT_PATH).
16431 # You can of course have different values for these variables.
16432 #
16433 # Note also that we need to keep the previous values of these variables, since
16434 # they might have been set before running 'make' to specify where the GNAT
16435 # library is installed.
16436
16437 # see "Automatically creating a list of directories" to create these
16438 # variables
16439 SOURCE_DIRS=
16440 OBJECT_DIRS=
16441
16442 empty:=
16443 space:=$@{empty@} $@{empty@}
16444 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
16445 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
16446 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
16447 ADA_OBJECT_PATH += $@{OBJECT_LIST@}
16448 export ADA_INCLUDE_PATH
16449 export ADA_OBJECT_PATH
16450
16451 all:
16452         gnatmake main_unit
16453 @end smallexample
16454 @end ifclear
16455
16456 @node Memory Management Issues
16457 @chapter Memory Management Issues
16458
16459 @noindent
16460 This chapter describes some useful memory pools provided in the GNAT library
16461 and in particular the GNAT Debug Pool facility, which can be used to detect
16462 incorrect uses of access values (including ``dangling references'').
16463 @ifclear vms
16464 It also describes the @command{gnatmem} tool, which can be used to track down
16465 ``memory leaks''.
16466 @end ifclear
16467
16468 @menu
16469 * Some Useful Memory Pools::
16470 * The GNAT Debug Pool Facility::
16471 @ifclear vms
16472 * The gnatmem Tool::
16473 @end ifclear
16474 @end menu
16475
16476 @node Some Useful Memory Pools
16477 @section Some Useful Memory Pools
16478 @findex Memory Pool
16479 @cindex storage, pool
16480
16481 @noindent
16482 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
16483 storage pool. Allocations use the standard system call @code{malloc} while
16484 deallocations use the standard system call @code{free}. No reclamation is
16485 performed when the pool goes out of scope. For performance reasons, the
16486 standard default Ada allocators/deallocators do not use any explicit storage
16487 pools but if they did, they could use this storage pool without any change in
16488 behavior. That is why this storage pool is used  when the user
16489 manages to make the default implicit allocator explicit as in this example:
16490 @smallexample @c ada
16491    type T1 is access Something;
16492     -- no Storage pool is defined for T2
16493    type T2 is access Something_Else;
16494    for T2'Storage_Pool use T1'Storage_Pool;
16495    -- the above is equivalent to
16496    for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
16497 @end smallexample
16498
16499 @noindent
16500 The @code{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
16501 pool. The allocation strategy is similar to @code{Pool_Local}'s
16502 except that the all
16503 storage allocated with this pool is reclaimed when the pool object goes out of
16504 scope. This pool provides a explicit mechanism similar to the implicit one
16505 provided by several Ada 83 compilers for allocations performed through a local
16506 access type and whose purpose was to reclaim memory when exiting the
16507 scope of a given local access. As an example, the following program does not
16508 leak memory even though it does not perform explicit deallocation:
16509
16510 @smallexample @c ada
16511 with System.Pool_Local;
16512 procedure Pooloc1 is
16513    procedure Internal is
16514       type A is access Integer;
16515       X : System.Pool_Local.Unbounded_Reclaim_Pool;
16516       for A'Storage_Pool use X;
16517       v : A;
16518    begin
16519       for I in  1 .. 50 loop
16520          v := new Integer;
16521       end loop;
16522    end Internal;
16523 begin
16524    for I in  1 .. 100 loop
16525       Internal;
16526    end loop;
16527 end Pooloc1;
16528 @end smallexample
16529
16530 @noindent
16531 The @code{System.Pool_Size} package implements the Stack_Bounded_Pool used when
16532 @code{Storage_Size} is specified for an access type.
16533 The whole storage for the pool is
16534 allocated at once, usually on the stack at the point where the access type is
16535 elaborated. It is automatically reclaimed when exiting the scope where the
16536 access type is defined. This package is not intended to be used directly by the
16537 user and it is implicitly used for each such declaration:
16538
16539 @smallexample @c ada
16540    type T1 is access Something;
16541    for T1'Storage_Size use 10_000;
16542 @end smallexample
16543
16544 @node The GNAT Debug Pool Facility
16545 @section The GNAT Debug Pool Facility
16546 @findex Debug Pool
16547 @cindex storage, pool, memory corruption
16548
16549 @noindent
16550 The use of unchecked deallocation and unchecked conversion can easily
16551 lead to incorrect memory references. The problems generated by such
16552 references are usually difficult to tackle because the symptoms can be
16553 very remote from the origin of the problem. In such cases, it is
16554 very helpful to detect the problem as early as possible. This is the
16555 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
16556
16557 In order to use the GNAT specific debugging pool, the user must
16558 associate a debug pool object with each of the access types that may be
16559 related to suspected memory problems. See Ada Reference Manual 13.11.
16560 @smallexample @c ada
16561 type Ptr is access Some_Type;
16562 Pool : GNAT.Debug_Pools.Debug_Pool;
16563 for Ptr'Storage_Pool use Pool;
16564 @end smallexample
16565
16566 @noindent
16567 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
16568 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
16569 allow the user to redefine allocation and deallocation strategies. They
16570 also provide a checkpoint for each dereference, through the use of
16571 the primitive operation @code{Dereference} which is implicitly called at
16572 each dereference of an access value.
16573
16574 Once an access type has been associated with a debug pool, operations on
16575 values of the type may raise four distinct exceptions,
16576 which correspond to four potential kinds of memory corruption:
16577 @itemize @bullet
16578 @item
16579 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
16580 @item
16581 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
16582 @item
16583 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
16584 @item
16585 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
16586 @end itemize
16587
16588 @noindent
16589 For types associated with a Debug_Pool, dynamic allocation is performed using
16590 the standard GNAT allocation routine. References to all allocated chunks of
16591 memory are kept in an internal dictionary. Several deallocation strategies are
16592 provided, whereupon the user can choose to release the memory to the system,
16593 keep it allocated for further invalid access checks, or fill it with an easily
16594 recognizable pattern for debug sessions. The memory pattern is the old IBM
16595 hexadecimal convention: @code{16#DEADBEEF#}.
16596
16597 See the documentation in the file g-debpoo.ads for more information on the
16598 various strategies.
16599
16600 Upon each dereference, a check is made that the access value denotes a
16601 properly allocated memory location. Here is a complete example of use of
16602 @code{Debug_Pools}, that includes typical instances of  memory corruption:
16603 @smallexample @c ada
16604 @iftex
16605 @leftskip=0cm
16606 @end iftex
16607 with Gnat.Io; use Gnat.Io;
16608 with Unchecked_Deallocation;
16609 with Unchecked_Conversion;
16610 with GNAT.Debug_Pools;
16611 with System.Storage_Elements;
16612 with Ada.Exceptions; use Ada.Exceptions;
16613 procedure Debug_Pool_Test is
16614
16615    type T is access Integer;
16616    type U is access all T;
16617
16618    P : GNAT.Debug_Pools.Debug_Pool;
16619    for T'Storage_Pool use P;
16620
16621    procedure Free is new Unchecked_Deallocation (Integer, T);
16622    function UC is new Unchecked_Conversion (U, T);
16623    A, B : aliased T;
16624
16625    procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
16626
16627 begin
16628    Info (P);
16629    A := new Integer;
16630    B := new Integer;
16631    B := A;
16632    Info (P);
16633    Free (A);
16634    begin
16635       Put_Line (Integer'Image(B.all));
16636    exception
16637       when E : others => Put_Line ("raised: " & Exception_Name (E));
16638    end;
16639    begin
16640       Free (B);
16641    exception
16642       when E : others => Put_Line ("raised: " & Exception_Name (E));
16643    end;
16644    B := UC(A'Access);
16645    begin
16646       Put_Line (Integer'Image(B.all));
16647    exception
16648       when E : others => Put_Line ("raised: " & Exception_Name (E));
16649    end;
16650    begin
16651       Free (B);
16652    exception
16653       when E : others => Put_Line ("raised: " & Exception_Name (E));
16654    end;
16655    Info (P);
16656 end Debug_Pool_Test;
16657 @end smallexample
16658
16659 @noindent
16660 The debug pool mechanism provides the following precise diagnostics on the
16661 execution of this erroneous program:
16662 @smallexample
16663 Debug Pool info:
16664   Total allocated bytes :  0
16665   Total deallocated bytes :  0
16666   Current Water Mark:  0
16667   High Water Mark:  0
16668
16669 Debug Pool info:
16670   Total allocated bytes :  8
16671   Total deallocated bytes :  0
16672   Current Water Mark:  8
16673   High Water Mark:  8
16674
16675 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
16676 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
16677 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
16678 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
16679 Debug Pool info:
16680   Total allocated bytes :  8
16681   Total deallocated bytes :  4
16682   Current Water Mark:  4
16683   High Water Mark:  8
16684 @end smallexample
16685
16686 @ifclear vms
16687 @node The gnatmem Tool
16688 @section The @command{gnatmem} Tool
16689 @findex gnatmem
16690
16691 @noindent
16692 The @code{gnatmem} utility monitors dynamic allocation and
16693 deallocation activity in a program, and displays information about
16694 incorrect deallocations and possible sources of memory leaks.
16695 It is designed to work in association with a static runtime library
16696 only and in this context provides three types of information:
16697 @itemize @bullet
16698 @item
16699 General information concerning memory management, such as the total
16700 number of allocations and deallocations, the amount of allocated
16701 memory and the high water mark, i.e.@: the largest amount of allocated
16702 memory in the course of program execution.
16703
16704 @item
16705 Backtraces for all incorrect deallocations, that is to say deallocations
16706 which do not correspond to a valid allocation.
16707
16708 @item
16709 Information on each allocation that is potentially the origin of a memory
16710 leak.
16711 @end itemize
16712
16713 @menu
16714 * Running gnatmem::
16715 * Switches for gnatmem::
16716 * Example of gnatmem Usage::
16717 @end menu
16718
16719 @node Running gnatmem
16720 @subsection Running @code{gnatmem}
16721
16722 @noindent
16723 @code{gnatmem} makes use of the output created by the special version of
16724 allocation and deallocation routines that record call information. This
16725 allows to obtain accurate dynamic memory usage history at a minimal cost to
16726 the execution speed. Note however, that @code{gnatmem} is not supported on
16727 all platforms (currently, it is supported on AIX, HP-UX, GNU/Linux,
16728 Solaris and Windows NT/2000/XP (x86).
16729
16730 @noindent
16731 The @code{gnatmem} command has the form
16732
16733 @smallexample
16734 @c    $ gnatmem @ovar{switches} user_program
16735 @c Expanding @ovar macro inline (explanation in macro def comments)
16736       $ gnatmem @r{[}@var{switches}@r{]} @var{user_program}
16737 @end smallexample
16738
16739 @noindent
16740 The program must have been linked with the instrumented version of the
16741 allocation and deallocation routines. This is done by linking with the
16742 @file{libgmem.a} library. For correct symbolic backtrace information,
16743 the user program should be compiled with debugging options
16744 (see @ref{Switches for gcc}). For example to build @file{my_program}:
16745
16746 @smallexample
16747 $ gnatmake -g my_program -largs -lgmem
16748 @end smallexample
16749
16750 @noindent
16751 As library @file{libgmem.a} contains an alternate body for package
16752 @code{System.Memory}, @file{s-memory.adb} should not be compiled and linked
16753 when an executable is linked with library @file{libgmem.a}. It is then not
16754 recommended to use @command{gnatmake} with switch @option{^-a^/ALL_FILES^}.
16755
16756 @noindent
16757 When @file{my_program} is executed, the file @file{gmem.out} is produced.
16758 This file contains information about all allocations and deallocations
16759 performed by the program. It is produced by the instrumented allocations and
16760 deallocations routines and will be used by @code{gnatmem}.
16761
16762 In order to produce symbolic backtrace information for allocations and
16763 deallocations performed by the GNAT run-time library, you need to use a
16764 version of that library that has been compiled with the @option{-g} switch
16765 (see @ref{Rebuilding the GNAT Run-Time Library}).
16766
16767 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
16768 examine. If the location of @file{gmem.out} file was not explicitly supplied by
16769 @option{-i} switch, gnatmem will assume that this file can be found in the
16770 current directory. For example, after you have executed @file{my_program},
16771 @file{gmem.out} can be analyzed by @code{gnatmem} using the command:
16772
16773 @smallexample
16774 $ gnatmem my_program
16775 @end smallexample
16776
16777 @noindent
16778 This will produce the output with the following format:
16779
16780 *************** debut cc
16781 @smallexample
16782 $ gnatmem my_program
16783
16784 Global information
16785 ------------------
16786    Total number of allocations        :  45
16787    Total number of deallocations      :   6
16788    Final Water Mark (non freed mem)   :  11.29 Kilobytes
16789    High Water Mark                    :  11.40 Kilobytes
16790
16791 .
16792 .
16793 .
16794 Allocation Root # 2
16795 -------------------
16796  Number of non freed allocations    :  11
16797  Final Water Mark (non freed mem)   :   1.16 Kilobytes
16798  High Water Mark                    :   1.27 Kilobytes
16799  Backtrace                          :
16800    my_program.adb:23 my_program.alloc
16801 .
16802 .
16803 .
16804 @end smallexample
16805
16806 The first block of output gives general information. In this case, the
16807 Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
16808 Unchecked_Deallocation routine occurred.
16809
16810 @noindent
16811 Subsequent paragraphs display  information on all allocation roots.
16812 An allocation root is a specific point in the execution of the program
16813 that generates some dynamic allocation, such as a ``@code{@b{new}}''
16814 construct. This root is represented by an execution backtrace (or subprogram
16815 call stack). By default the backtrace depth for allocations roots is 1, so
16816 that a root corresponds exactly to a source location. The backtrace can
16817 be made deeper, to make the root more specific.
16818
16819 @node Switches for gnatmem
16820 @subsection Switches for @code{gnatmem}
16821
16822 @noindent
16823 @code{gnatmem} recognizes the following switches:
16824
16825 @table @option
16826
16827 @item -q
16828 @cindex @option{-q} (@code{gnatmem})
16829 Quiet. Gives the minimum output needed to identify the origin of the
16830 memory leaks. Omits statistical information.
16831
16832 @item @var{N}
16833 @cindex @var{N} (@code{gnatmem})
16834 N is an integer literal (usually between 1 and 10) which controls the
16835 depth of the backtraces defining allocation root. The default value for
16836 N is 1. The deeper the backtrace, the more precise the localization of
16837 the root. Note that the total number of roots can depend on this
16838 parameter. This parameter must be specified @emph{before} the name of the
16839 executable to be analyzed, to avoid ambiguity.
16840
16841 @item -b n
16842 @cindex @option{-b} (@code{gnatmem})
16843 This switch has the same effect as just depth parameter.
16844
16845 @item -i @var{file}
16846 @cindex @option{-i} (@code{gnatmem})
16847 Do the @code{gnatmem} processing starting from @file{file}, rather than
16848 @file{gmem.out} in the current directory.
16849
16850 @item -m n
16851 @cindex @option{-m} (@code{gnatmem})
16852 This switch causes @code{gnatmem} to mask the allocation roots that have less
16853 than n leaks. The default value is 1. Specifying the value of 0 will allow to
16854 examine even the roots that didn't result in leaks.
16855
16856 @item -s order
16857 @cindex @option{-s} (@code{gnatmem})
16858 This switch causes @code{gnatmem} to sort the allocation roots according to the
16859 specified order of sort criteria, each identified by a single letter. The
16860 currently supported criteria are @code{n, h, w} standing respectively for
16861 number of unfreed allocations, high watermark, and final watermark
16862 corresponding to a specific root. The default order is @code{nwh}.
16863
16864 @end table
16865
16866 @node Example of gnatmem Usage
16867 @subsection Example of @code{gnatmem} Usage
16868
16869 @noindent
16870 The following example shows the use of @code{gnatmem}
16871 on a simple memory-leaking program.
16872 Suppose that we have the following Ada program:
16873
16874 @smallexample @c ada
16875 @group
16876 @cartouche
16877 with Unchecked_Deallocation;
16878 procedure Test_Gm is
16879
16880    type T is array (1..1000) of Integer;
16881    type Ptr is access T;
16882    procedure Free is new Unchecked_Deallocation (T, Ptr);
16883    A : Ptr;
16884
16885    procedure My_Alloc is
16886    begin
16887       A := new T;
16888    end My_Alloc;
16889
16890    procedure My_DeAlloc is
16891       B : Ptr := A;
16892    begin
16893       Free (B);
16894    end My_DeAlloc;
16895
16896 begin
16897    My_Alloc;
16898    for I in 1 .. 5 loop
16899       for J in I .. 5 loop
16900          My_Alloc;
16901       end loop;
16902       My_Dealloc;
16903    end loop;
16904 end;
16905 @end cartouche
16906 @end group
16907 @end smallexample
16908
16909 @noindent
16910 The program needs to be compiled with debugging option and linked with
16911 @code{gmem} library:
16912
16913 @smallexample
16914 $ gnatmake -g test_gm -largs -lgmem
16915 @end smallexample
16916
16917 @noindent
16918 Then we execute the program as usual:
16919
16920 @smallexample
16921 $ test_gm
16922 @end smallexample
16923
16924 @noindent
16925 Then @code{gnatmem} is invoked simply with
16926 @smallexample
16927 $ gnatmem test_gm
16928 @end smallexample
16929
16930 @noindent
16931 which produces the following output (result may vary on different platforms):
16932
16933 @smallexample
16934 Global information
16935 ------------------
16936    Total number of allocations        :  18
16937    Total number of deallocations      :   5
16938    Final Water Mark (non freed mem)   :  53.00 Kilobytes
16939    High Water Mark                    :  56.90 Kilobytes
16940
16941 Allocation Root # 1
16942 -------------------
16943  Number of non freed allocations    :  11
16944  Final Water Mark (non freed mem)   :  42.97 Kilobytes
16945  High Water Mark                    :  46.88 Kilobytes
16946  Backtrace                          :
16947    test_gm.adb:11 test_gm.my_alloc
16948
16949 Allocation Root # 2
16950 -------------------
16951  Number of non freed allocations    :   1
16952  Final Water Mark (non freed mem)   :  10.02 Kilobytes
16953  High Water Mark                    :  10.02 Kilobytes
16954  Backtrace                          :
16955    s-secsta.adb:81 system.secondary_stack.ss_init
16956
16957 Allocation Root # 3
16958 -------------------
16959  Number of non freed allocations    :   1
16960  Final Water Mark (non freed mem)   :  12 Bytes
16961  High Water Mark                    :  12 Bytes
16962  Backtrace                          :
16963    s-secsta.adb:181 system.secondary_stack.ss_init
16964 @end smallexample
16965
16966 @noindent
16967 Note that the GNAT run time contains itself a certain number of
16968 allocations that have no  corresponding deallocation,
16969 as shown here for root #2 and root
16970 #3. This is a normal behavior when the number of non-freed allocations
16971 is one, it allocates dynamic data structures that the run time needs for
16972 the complete lifetime of the program. Note also that there is only one
16973 allocation root in the user program with a single line back trace:
16974 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
16975 program shows that 'My_Alloc' is called at 2 different points in the
16976 source (line 21 and line 24). If those two allocation roots need to be
16977 distinguished, the backtrace depth parameter can be used:
16978
16979 @smallexample
16980 $ gnatmem 3 test_gm
16981 @end smallexample
16982
16983 @noindent
16984 which will give the following output:
16985
16986 @smallexample
16987 Global information
16988 ------------------
16989    Total number of allocations        :  18
16990    Total number of deallocations      :   5
16991    Final Water Mark (non freed mem)   :  53.00 Kilobytes
16992    High Water Mark                    :  56.90 Kilobytes
16993
16994 Allocation Root # 1
16995 -------------------
16996  Number of non freed allocations    :  10
16997  Final Water Mark (non freed mem)   :  39.06 Kilobytes
16998  High Water Mark                    :  42.97 Kilobytes
16999  Backtrace                          :
17000    test_gm.adb:11 test_gm.my_alloc
17001    test_gm.adb:24 test_gm
17002    b_test_gm.c:52 main
17003
17004 Allocation Root # 2
17005 -------------------
17006  Number of non freed allocations    :   1
17007  Final Water Mark (non freed mem)   :  10.02 Kilobytes
17008  High Water Mark                    :  10.02 Kilobytes
17009  Backtrace                          :
17010    s-secsta.adb:81  system.secondary_stack.ss_init
17011    s-secsta.adb:283 <system__secondary_stack___elabb>
17012    b_test_gm.c:33   adainit
17013
17014 Allocation Root # 3
17015 -------------------
17016  Number of non freed allocations    :   1
17017  Final Water Mark (non freed mem)   :   3.91 Kilobytes
17018  High Water Mark                    :   3.91 Kilobytes
17019  Backtrace                          :
17020    test_gm.adb:11 test_gm.my_alloc
17021    test_gm.adb:21 test_gm
17022    b_test_gm.c:52 main
17023
17024 Allocation Root # 4
17025 -------------------
17026  Number of non freed allocations    :   1
17027  Final Water Mark (non freed mem)   :  12 Bytes
17028  High Water Mark                    :  12 Bytes
17029  Backtrace                          :
17030    s-secsta.adb:181 system.secondary_stack.ss_init
17031    s-secsta.adb:283 <system__secondary_stack___elabb>
17032    b_test_gm.c:33   adainit
17033 @end smallexample
17034
17035 @noindent
17036 The allocation root #1 of the first example has been split in 2 roots #1
17037 and #3 thanks to the more precise associated backtrace.
17038
17039 @end ifclear
17040
17041 @node Stack Related Facilities
17042 @chapter Stack Related Facilities
17043
17044 @noindent
17045 This chapter describes some useful tools associated with stack
17046 checking and analysis. In
17047 particular, it deals with dynamic and static stack usage measurements.
17048
17049 @menu
17050 * Stack Overflow Checking::
17051 * Static Stack Usage Analysis::
17052 * Dynamic Stack Usage Analysis::
17053 @end menu
17054
17055 @node Stack Overflow Checking
17056 @section Stack Overflow Checking
17057 @cindex Stack Overflow Checking
17058 @cindex -fstack-check
17059
17060 @noindent
17061 For most operating systems, @command{gcc} does not perform stack overflow
17062 checking by default. This means that if the main environment task or
17063 some other task exceeds the available stack space, then unpredictable
17064 behavior will occur. Most native systems offer some level of protection by
17065 adding a guard page at the end of each task stack. This mechanism is usually
17066 not enough for dealing properly with stack overflow situations because
17067 a large local variable could ``jump'' above the guard page.
17068 Furthermore, when the
17069 guard page is hit, there may not be any space left on the stack for executing
17070 the exception propagation code. Enabling stack checking avoids
17071 such situations.
17072
17073 To activate stack checking, compile all units with the gcc option
17074 @option{-fstack-check}. For example:
17075
17076 @smallexample
17077 gcc -c -fstack-check package1.adb
17078 @end smallexample
17079
17080 @noindent
17081 Units compiled with this option will generate extra instructions to check
17082 that any use of the stack (for procedure calls or for declaring local
17083 variables in declare blocks) does not exceed the available stack space.
17084 If the space is exceeded, then a @code{Storage_Error} exception is raised.
17085
17086 For declared tasks, the stack size is controlled by the size
17087 given in an applicable @code{Storage_Size} pragma or by the value specified
17088 at bind time with @option{-d} (@pxref{Switches for gnatbind}) or is set to
17089 the default size as defined in the GNAT runtime otherwise.
17090
17091 For the environment task, the stack size depends on
17092 system defaults and is unknown to the compiler. Stack checking
17093 may still work correctly if a fixed
17094 size stack is allocated, but this cannot be guaranteed.
17095 @ifclear vms
17096 To ensure that a clean exception is signalled for stack
17097 overflow, set the environment variable
17098 @env{GNAT_STACK_LIMIT} to indicate the maximum
17099 stack area that can be used, as in:
17100 @cindex GNAT_STACK_LIMIT
17101
17102 @smallexample
17103 SET GNAT_STACK_LIMIT 1600
17104 @end smallexample
17105
17106 @noindent
17107 The limit is given in kilobytes, so the above declaration would
17108 set the stack limit of the environment task to 1.6 megabytes.
17109 Note that the only purpose of this usage is to limit the amount
17110 of stack used by the environment task. If it is necessary to
17111 increase the amount of stack for the environment task, then this
17112 is an operating systems issue, and must be addressed with the
17113 appropriate operating systems commands.
17114 @end ifclear
17115 @ifset vms
17116 To have a fixed size stack in the environment task, the stack must be put
17117 in the P0 address space and its size specified.  Use these switches to
17118 create a p0 image:
17119
17120 @smallexample
17121 gnatmake my_progs -largs "-Wl,--opt=STACK=4000,/p0image"
17122 @end smallexample
17123
17124 @noindent
17125 The quotes are required to keep case.  The number after @samp{STACK=} is the
17126 size of the environmental task stack in pagelets (512 bytes).  In this example
17127 the stack size is about 2 megabytes.
17128
17129 @noindent
17130 A consequence of the @option{/p0image} qualifier is also to makes RMS buffers
17131 be placed in P0 space.  Refer to @cite{HP OpenVMS Linker Utility Manual} for
17132 more details about the @option{/p0image} qualifier and the @option{stack}
17133 option.
17134 @end ifset
17135
17136 @node Static Stack Usage Analysis
17137 @section Static Stack Usage Analysis
17138 @cindex Static Stack Usage Analysis
17139 @cindex -fstack-usage
17140
17141 @noindent
17142 A unit compiled with @option{-fstack-usage} will generate an extra file
17143 that specifies
17144 the maximum amount of stack used, on a per-function basis.
17145 The file has the same
17146 basename as the target object file with a @file{.su} extension.
17147 Each line of this file is made up of three fields:
17148
17149 @itemize
17150 @item
17151 The name of the function.
17152 @item
17153 A number of bytes.
17154 @item
17155 One or more qualifiers: @code{static}, @code{dynamic}, @code{bounded}.
17156 @end itemize
17157
17158 The second field corresponds to the size of the known part of the function
17159 frame.
17160
17161 The qualifier @code{static} means that the function frame size
17162 is purely static.
17163 It usually means that all local variables have a static size.
17164 In this case, the second field is a reliable measure of the function stack
17165 utilization.
17166
17167 The qualifier @code{dynamic} means that the function frame size is not static.
17168 It happens mainly when some local variables have a dynamic size. When this
17169 qualifier appears alone, the second field is not a reliable measure
17170 of the function stack analysis. When it is qualified with  @code{bounded}, it
17171 means that the second field is a reliable maximum of the function stack
17172 utilization.
17173
17174 @node Dynamic Stack Usage Analysis
17175 @section Dynamic Stack Usage Analysis
17176
17177 @noindent
17178 It is possible to measure the maximum amount of stack used by a task, by
17179 adding a switch to @command{gnatbind}, as:
17180
17181 @smallexample
17182 $ gnatbind -u0 file
17183 @end smallexample
17184
17185 @noindent
17186 With this option, at each task termination, its stack usage is  output on
17187 @file{stderr}.
17188 It is not always convenient to output the stack usage when the program
17189 is still running. Hence, it is possible to delay this output until program
17190 termination. for a given number of tasks specified as the argument of the
17191 @option{-u} option. For instance:
17192
17193 @smallexample
17194 $ gnatbind -u100 file
17195 @end smallexample
17196
17197 @noindent
17198 will buffer the stack usage information of the first 100 tasks to terminate and
17199 output this info at program termination. Results are displayed in four
17200 columns:
17201
17202 @noindent
17203 Index | Task Name | Stack Size | Stack Usage [Value +/- Variation]
17204
17205 @noindent
17206 where:
17207
17208 @table @emph
17209 @item Index
17210 is a number associated with each task.
17211
17212 @item Task Name
17213 is the name of the task analyzed.
17214
17215 @item Stack Size
17216 is the maximum size for the stack.
17217
17218 @item Stack Usage
17219 is the measure done by the stack analyzer. In order to prevent overflow, the stack
17220 is not entirely analyzed, and it's not possible to know exactly how
17221 much has actually been used. The report thus contains the theoretical stack usage
17222 (Value) and the possible variation (Variation) around this value.
17223
17224 @end table
17225
17226 @noindent
17227 The environment task stack, e.g., the stack that contains the main unit, is
17228 only processed when the environment variable GNAT_STACK_LIMIT is set.
17229
17230
17231 @c *********************************
17232 @c *            GNATCHECK          *
17233 @c *********************************
17234 @node Verifying Properties Using gnatcheck
17235 @chapter Verifying Properties Using @command{gnatcheck}
17236 @findex gnatcheck
17237 @cindex @command{gnatcheck}
17238
17239 @noindent
17240 The @command{gnatcheck} tool is an ASIS-based utility that checks properties
17241 of Ada source files according to a given set of semantic rules.
17242 @cindex ASIS
17243
17244 In order to check compliance with a given rule, @command{gnatcheck} has to
17245 semantically analyze the Ada sources.
17246 Therefore, checks can only be performed on
17247 legal Ada units. Moreover, when a unit depends semantically upon units located
17248 outside the current directory, the source search path has to be provided when
17249 calling @command{gnatcheck}, either through a specified project file or
17250 through @command{gnatcheck} switches.
17251
17252 A number of rules are predefined in @command{gnatcheck} and are described
17253 later in this chapter.
17254
17255 For full details, refer to @cite{GNATcheck Reference Manual} document.
17256
17257
17258 @c *********************************
17259 @node Creating Sample Bodies Using gnatstub
17260 @chapter Creating Sample Bodies Using @command{gnatstub}
17261 @findex gnatstub
17262
17263 @noindent
17264 @command{gnatstub} creates body stubs, that is, empty but compilable bodies
17265 for library unit declarations.
17266
17267 Note: to invoke @code{gnatstub} with a project file, use the @code{gnat}
17268 driver (see @ref{The GNAT Driver and Project Files}).
17269
17270 To create a body stub, @command{gnatstub} has to compile the library
17271 unit declaration. Therefore, bodies can be created only for legal
17272 library units. Moreover, if a library unit depends semantically upon
17273 units located outside the current directory, you have to provide
17274 the source search path when calling @command{gnatstub}, see the description
17275 of @command{gnatstub} switches below.
17276
17277 By default, all the program unit body stubs generated by @code{gnatstub}
17278 raise the predefined @code{Program_Error} exception, which will catch
17279 accidental calls of generated stubs. This behavior can be changed with
17280 option @option{^--no-exception^/NO_EXCEPTION^} (see below).
17281
17282 @menu
17283 * Running gnatstub::
17284 * Switches for gnatstub::
17285 @end menu
17286
17287 @node Running gnatstub
17288 @section Running @command{gnatstub}
17289
17290 @noindent
17291 @command{gnatstub} has the command-line interface of the form
17292
17293 @smallexample
17294 @c $ gnatstub @ovar{switches} @var{filename} @ovar{directory}
17295 @c Expanding @ovar macro inline (explanation in macro def comments)
17296 $ gnatstub @r{[}@var{switches}@r{]} @var{filename} @r{[}@var{directory}@r{]} @r{[}-cargs @var{gcc_switches}@r{]}
17297 @end smallexample
17298
17299 @noindent
17300 where
17301 @table @var
17302 @item filename
17303 is the name of the source file that contains a library unit declaration
17304 for which a body must be created. The file name may contain the path
17305 information.
17306 The file name does not have to follow the GNAT file name conventions. If the
17307 name
17308 does not follow GNAT file naming conventions, the name of the body file must
17309 be provided
17310 explicitly as the value of the @option{^-o^/BODY=^@var{body-name}} option.
17311 If the file name follows the GNAT file naming
17312 conventions and the name of the body file is not provided,
17313 @command{gnatstub}
17314 creates the name
17315 of the body file from the argument file name by replacing the @file{.ads}
17316 suffix
17317 with the @file{.adb} suffix.
17318
17319 @item directory
17320 indicates the directory in which the body stub is to be placed (the default
17321 is the
17322 current directory)
17323
17324 @item @samp{@var{gcc_switches}} is a list of switches for
17325 @command{gcc}. They will be passed on to all compiler invocations made by
17326 @command{gnatelim} to generate the ASIS trees. Here you can provide
17327 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
17328 use the @option{-gnatec} switch to set the configuration file,
17329 use the @option{-gnat05} switch if sources should be compiled in
17330 Ada 2005 mode etc.
17331
17332 @item switches
17333 is an optional sequence of switches as described in the next section
17334 @end table
17335
17336 @node Switches for gnatstub
17337 @section Switches for @command{gnatstub}
17338
17339 @table @option
17340 @c !sort!
17341
17342 @item ^-f^/FULL^
17343 @cindex @option{^-f^/FULL^} (@command{gnatstub})
17344 If the destination directory already contains a file with the name of the
17345 body file
17346 for the argument spec file, replace it with the generated body stub.
17347
17348 @item ^-hs^/HEADER=SPEC^
17349 @cindex @option{^-hs^/HEADER=SPEC^} (@command{gnatstub})
17350 Put the comment header (i.e., all the comments preceding the
17351 compilation unit) from the source of the library unit declaration
17352 into the body stub.
17353
17354 @item ^-hg^/HEADER=GENERAL^
17355 @cindex @option{^-hg^/HEADER=GENERAL^} (@command{gnatstub})
17356 Put a sample comment header into the body stub.
17357
17358 @item ^--header-file=@var{filename}^/FROM_HEADER_FILE=@var{filename}^
17359 @cindex @option{^--header-file^/FROM_HEADER_FILE=^} (@command{gnatstub})
17360 Use the content of the file as the comment header for a generated body stub.
17361
17362 @ifclear vms
17363 @item -IDIR
17364 @cindex @option{-IDIR} (@command{gnatstub})
17365 @itemx -I-
17366 @cindex @option{-I-} (@command{gnatstub})
17367 @end ifclear
17368 @ifset vms
17369 @item /NOCURRENT_DIRECTORY
17370 @cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub})
17371 @end ifset
17372 ^These switches have ^This switch has^ the same meaning as in calls to
17373 @command{gcc}.
17374 ^They define ^It defines ^ the source search path in the call to
17375 @command{gcc} issued
17376 by @command{gnatstub} to compile an argument source file.
17377
17378 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE=^@var{PATH}
17379 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatstub})
17380 This switch has the same meaning as in calls to @command{gcc}.
17381 It defines the additional configuration file to be passed to the call to
17382 @command{gcc} issued
17383 by @command{gnatstub} to compile an argument source file.
17384
17385 @item ^-gnatyM^/MAX_LINE_LENGTH=^@var{n}
17386 @cindex @option{^-gnatyM^/MAX_LINE_LENGTH^} (@command{gnatstub})
17387 (@var{n} is a non-negative integer). Set the maximum line length in the
17388 body stub to @var{n}; the default is 79. The maximum value that can be
17389 specified is 32767. Note that in the special case of configuration
17390 pragma files, the maximum is always 32767 regardless of whether or
17391 not this switch appears.
17392
17393 @item ^-gnaty^/STYLE_CHECKS=^@var{n}
17394 @cindex @option{^-gnaty^/STYLE_CHECKS=^} (@command{gnatstub})
17395 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
17396 the generated body sample to @var{n}.
17397 The default indentation is 3.
17398
17399 @item ^-gnatyo^/ORDERED_SUBPROGRAMS^
17400 @cindex @option{^-gnato^/ORDERED_SUBPROGRAMS^} (@command{gnatstub})
17401 Order local bodies alphabetically. (By default local bodies are ordered
17402 in the same way as the corresponding local specs in the argument spec file.)
17403
17404 @item ^-i^/INDENTATION=^@var{n}
17405 @cindex @option{^-i^/INDENTATION^} (@command{gnatstub})
17406 Same as @option{^-gnaty^/STYLE_CHECKS=^@var{n}}
17407
17408 @item ^-k^/TREE_FILE=SAVE^
17409 @cindex @option{^-k^/TREE_FILE=SAVE^} (@command{gnatstub})
17410 Do not remove the tree file (i.e., the snapshot of the compiler internal
17411 structures used by @command{gnatstub}) after creating the body stub.
17412
17413 @item ^-l^/LINE_LENGTH=^@var{n}
17414 @cindex @option{^-l^/LINE_LENGTH^} (@command{gnatstub})
17415 Same as @option{^-gnatyM^/MAX_LINE_LENGTH=^@var{n}}
17416
17417 @item ^--no-exception^/NO_EXCEPTION^
17418 @cindex @option{^--no-exception^/NO_EXCEPTION^} (@command{gnatstub})
17419 Avoind raising PROGRAM_ERROR in the generated bodies of program unit stubs.
17420 This is not always possible for function stubs.
17421
17422 @item ^--no-local-header^/NO_LOCAL_HEADER^
17423 @cindex @option{^--no-local-header^/NO_LOCAL_HEADER^} (@command{gnatstub})
17424 Do not place local comment header with unit name before body stub for a
17425 unit.
17426
17427 @item ^-o ^/BODY=^@var{body-name}
17428 @cindex @option{^-o^/BODY^} (@command{gnatstub})
17429 Body file name.  This should be set if the argument file name does not
17430 follow
17431 the GNAT file naming
17432 conventions. If this switch is omitted the default name for the body will be
17433 obtained
17434 from the argument file name according to the GNAT file naming conventions.
17435
17436 @item ^-q^/QUIET^
17437 @cindex @option{^-q^/QUIET^} (@command{gnatstub})
17438 Quiet mode: do not generate a confirmation when a body is
17439 successfully created, and do not generate a message when a body is not
17440 required for an
17441 argument unit.
17442
17443 @item ^-r^/TREE_FILE=REUSE^
17444 @cindex @option{^-r^/TREE_FILE=REUSE^} (@command{gnatstub})
17445 Reuse the tree file (if it exists) instead of creating it.  Instead of
17446 creating the tree file for the library unit declaration, @command{gnatstub}
17447 tries to find it in the current directory and use it for creating
17448 a body. If the tree file is not found, no body is created. This option
17449 also implies @option{^-k^/SAVE^}, whether or not
17450 the latter is set explicitly.
17451
17452 @item ^-t^/TREE_FILE=OVERWRITE^
17453 @cindex @option{^-t^/TREE_FILE=OVERWRITE^} (@command{gnatstub})
17454 Overwrite the existing tree file.  If the current directory already
17455 contains the file which, according to the GNAT file naming rules should
17456 be considered as a tree file for the argument source file,
17457 @command{gnatstub}
17458 will refuse to create the tree file needed to create a sample body
17459 unless this option is set.
17460
17461 @item ^-v^/VERBOSE^
17462 @cindex @option{^-v^/VERBOSE^} (@command{gnatstub})
17463 Verbose mode: generate version information.
17464
17465 @end table
17466
17467 @c *********************************
17468 @node Generating Ada Bindings for C and C++ headers
17469 @chapter Generating Ada Bindings for C and C++ headers
17470 @findex binding
17471
17472 @noindent
17473 GNAT now comes with a binding generator for C and C++ headers which is
17474 intended to do 95% of the tedious work of generating Ada specs from C
17475 or C++ header files.
17476
17477 Note that this capability is not intended to generate 100% correct Ada specs,
17478 and will is some cases require manual adjustments, although it can often
17479 be used out of the box in practice.
17480
17481 Some of the known limitations include:
17482
17483 @itemize @bullet
17484 @item only very simple character constant macros are translated into Ada
17485 constants. Function macros (macros with arguments) are partially translated
17486 as comments, to be completed manually if needed.
17487 @item some extensions (e.g. vector types) are not supported
17488 @item pointers to pointers or complex structures are mapped to System.Address
17489 @item identifiers with identical name (except casing) will generate compilation
17490       errors (e.g. @code{shm_get} vs @code{SHM_GET}).
17491 @end itemize
17492
17493 The code generated is using the Ada 2005 syntax, which makes it
17494 easier to interface with other languages than previous versions of Ada.
17495
17496 @menu
17497 * Running the binding generator::
17498 * Generating bindings for C++ headers::
17499 * Switches::
17500 @end menu
17501
17502 @node Running the binding generator
17503 @section Running the binding generator
17504
17505 @noindent
17506 The binding generator is part of the @command{gcc} compiler and can be
17507 invoked via the @option{-fdump-ada-spec} switch, which will generate Ada
17508 spec files for the header files specified on the command line, and all
17509 header files needed by these files transitivitely. For example:
17510
17511 @smallexample
17512 $ g++ -c -fdump-ada-spec -C /usr/include/time.h
17513 $ gcc -c -gnat05 *.ads
17514 @end smallexample
17515
17516 will generate, under GNU/Linux, the following files: @file{time_h.ads},
17517 @file{bits_time_h.ads}, @file{stddef_h.ads}, @file{bits_types_h.ads} which
17518 correspond to the files @file{/usr/include/time.h},
17519 @file{/usr/include/bits/time.h}, etc@dots{}, and will then compile in Ada 2005
17520 mode these Ada specs.
17521
17522 The @code{-C} switch tells @command{gcc} to extract comments from headers,
17523 and will attempt to generate corresponding Ada comments.
17524
17525 If you want to generate a single Ada file and not the transitive closure, you
17526 can use instead the @option{-fdump-ada-spec-slim} switch.
17527
17528 Note that we recommend when possible to use the @command{g++} driver to
17529 generate bindings, even for most C headers, since this will in general
17530 generate better Ada specs. For generating bindings for C++ headers, it is
17531 mandatory to use the @command{g++} command, or @command{gcc -x c++} which
17532 is equivalent in this case. If @command{g++} cannot work on your C headers
17533 because of incompatibilities between C and C++, then you can fallback to
17534 @command{gcc} instead.
17535
17536 For an example of better bindings generated from the C++ front-end,
17537 the name of the parameters (when available) are actually ignored by the C
17538 front-end. Consider the following C header:
17539
17540 @smallexample
17541 extern void foo (int variable);
17542 @end smallexample
17543
17544 with the C front-end, @code{variable} is ignored, and the above is handled as:
17545
17546 @smallexample
17547 extern void foo (int);
17548 @end smallexample
17549
17550 generating a generic:
17551
17552 @smallexample
17553 procedure foo (param1 : int);
17554 @end smallexample
17555
17556 with the C++ front-end, the name is available, and we generate:
17557
17558 @smallexample
17559 procedure foo (variable : int);
17560 @end smallexample
17561
17562 In some cases, the generated bindings will be more complete or more meaningful
17563 when defining some macros, which you can do via the @option{-D} switch. This
17564 is for example the case with @file{Xlib.h} under GNU/Linux:
17565
17566 @smallexample
17567 g++ -c -fdump-ada-spec -DXLIB_ILLEGAL_ACCESS -C /usr/include/X11/Xlib.h
17568 @end smallexample
17569
17570 The above will generate more complete bindings than a straight call without
17571 the @option{-DXLIB_ILLEGAL_ACCESS} switch.
17572
17573 In other cases, it is not possible to parse a header file in a stand alone
17574 manner, because other include files need to be included first. In this
17575 case, the solution is to create a small header file including the needed
17576 @code{#include} and possible @code{#define} directives. For example, to
17577 generate Ada bindings for @file{readline/readline.h}, you need to first
17578 include @file{stdio.h}, so you can create a file with the following two
17579 lines in e.g. @file{readline1.h}:
17580
17581 @smallexample
17582 #include <stdio.h>
17583 #include <readline/readline.h>
17584 @end smallexample
17585
17586 and then generate Ada bindings from this file:
17587
17588 @smallexample
17589 $ g++ -c -fdump-ada-spec readline1.h
17590 @end smallexample
17591
17592 @node Generating bindings for C++ headers
17593 @section Generating bindings for C++ headers
17594
17595 @noindent
17596 Generating bindings for C++ headers is done using the same options, always
17597 with the @command{g++} compiler.
17598
17599 In this mode, C++ classes will be mapped to Ada tagged types, constructors
17600 will be mapped using the @code{CPP_Constructor} pragma, and when possible,
17601 multiple inheritance of abstract classes will be mapped to Ada interfaces
17602 (@xref{Interfacing to C++,,,gnat_rm, GNAT Reference Manual}, for additional
17603 information on interfacing to C++).
17604
17605 For example, given the following C++ header file:
17606
17607 @smallexample
17608 @group
17609 @cartouche
17610 class Carnivore @{
17611 public:
17612    virtual int Number_Of_Teeth () = 0;
17613 @};
17614
17615 class Domestic @{
17616 public:
17617    virtual void Set_Owner (char* Name) = 0;
17618 @};
17619
17620 class Animal @{
17621 public:
17622   int Age_Count;
17623   virtual void Set_Age (int New_Age);
17624 @};
17625
17626 class Dog : Animal, Carnivore, Domestic @{
17627  public:
17628   int  Tooth_Count;
17629   char *Owner;
17630
17631   virtual int  Number_Of_Teeth ();
17632   virtual void Set_Owner (char* Name);
17633
17634   Dog();
17635 @};
17636 @end cartouche
17637 @end group
17638 @end smallexample
17639
17640 The corresponding Ada code is generated:
17641
17642 @smallexample @c ada
17643 @group
17644 @cartouche
17645   package Class_Carnivore is
17646     type Carnivore is limited interface;
17647     pragma Import (CPP, Carnivore);
17648
17649     function Number_Of_Teeth (this : access Carnivore) return int is abstract;
17650   end;
17651   use Class_Carnivore;
17652
17653   package Class_Domestic is
17654     type Domestic is limited interface;
17655     pragma Import (CPP, Domestic);
17656
17657     procedure Set_Owner
17658       (this : access Domestic;
17659        Name : Interfaces.C.Strings.chars_ptr) is abstract;
17660   end;
17661   use Class_Domestic;
17662
17663   package Class_Animal is
17664     type Animal is tagged limited record
17665       Age_Count : aliased int;
17666     end record;
17667     pragma Import (CPP, Animal);
17668
17669     procedure Set_Age (this : access Animal; New_Age : int);
17670     pragma Import (CPP, Set_Age, "_ZN6Animal7Set_AgeEi");
17671   end;
17672   use Class_Animal;
17673
17674   package Class_Dog is
17675     type Dog is new Animal and Carnivore and Domestic with record
17676       Tooth_Count : aliased int;
17677       Owner : Interfaces.C.Strings.chars_ptr;
17678     end record;
17679     pragma Import (CPP, Dog);
17680
17681     function Number_Of_Teeth (this : access Dog) return int;
17682     pragma Import (CPP, Number_Of_Teeth, "_ZN3Dog15Number_Of_TeethEv");
17683
17684     procedure Set_Owner
17685       (this : access Dog; Name : Interfaces.C.Strings.chars_ptr);
17686     pragma Import (CPP, Set_Owner, "_ZN3Dog9Set_OwnerEPc");
17687
17688     function New_Dog return Dog;
17689     pragma CPP_Constructor (New_Dog);
17690     pragma Import (CPP, New_Dog, "_ZN3DogC1Ev");
17691   end;
17692   use Class_Dog;
17693 @end cartouche
17694 @end group
17695 @end smallexample
17696
17697 @node Switches
17698 @section Switches
17699
17700 @table @option
17701 @item -fdump-ada-spec
17702 @cindex @option{-fdump-ada-spec} (@command{gcc})
17703 Generate Ada spec files for the given header files transitively (including
17704 all header files that these headers depend upon).
17705
17706 @item -fdump-ada-spec-slim
17707 @cindex @option{-fdump-ada-spec-slim} (@command{gcc})
17708 Generate Ada spec files for the header files specified on the command line
17709 only.
17710
17711 @item -C
17712 @cindex @option{-C} (@command{gcc})
17713 Extract comments from headers and generate Ada comments in the Ada spec files.
17714 @end table
17715
17716 @node Other Utility Programs
17717 @chapter Other Utility Programs
17718
17719 @noindent
17720 This chapter discusses some other utility programs available in the Ada
17721 environment.
17722
17723 @menu
17724 * Using Other Utility Programs with GNAT::
17725 * The External Symbol Naming Scheme of GNAT::
17726 * Converting Ada Files to html with gnathtml::
17727 * Installing gnathtml::
17728 @ifset vms
17729 * LSE::
17730 * Profiling::
17731 @end ifset
17732 @end menu
17733
17734 @node Using Other Utility Programs with GNAT
17735 @section Using Other Utility Programs with GNAT
17736
17737 @noindent
17738 The object files generated by GNAT are in standard system format and in
17739 particular the debugging information uses this format. This means
17740 programs generated by GNAT can be used with existing utilities that
17741 depend on these formats.
17742
17743 @ifclear vms
17744 In general, any utility program that works with C will also often work with
17745 Ada programs generated by GNAT. This includes software utilities such as
17746 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
17747 as Purify.
17748 @end ifclear
17749
17750 @node The External Symbol Naming Scheme of GNAT
17751 @section The External Symbol Naming Scheme of GNAT
17752
17753 @noindent
17754 In order to interpret the output from GNAT, when using tools that are
17755 originally intended for use with other languages, it is useful to
17756 understand the conventions used to generate link names from the Ada
17757 entity names.
17758
17759 All link names are in all lowercase letters. With the exception of library
17760 procedure names, the mechanism used is simply to use the full expanded
17761 Ada name with dots replaced by double underscores. For example, suppose
17762 we have the following package spec:
17763
17764 @smallexample @c ada
17765 @group
17766 @cartouche
17767 package QRS is
17768    MN : Integer;
17769 end QRS;
17770 @end cartouche
17771 @end group
17772 @end smallexample
17773
17774 @noindent
17775 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
17776 the corresponding link name is @code{qrs__mn}.
17777 @findex Export
17778 Of course if a @code{pragma Export} is used this may be overridden:
17779
17780 @smallexample @c ada
17781 @group
17782 @cartouche
17783 package Exports is
17784    Var1 : Integer;
17785    pragma Export (Var1, C, External_Name => "var1_name");
17786    Var2 : Integer;
17787    pragma Export (Var2, C, Link_Name => "var2_link_name");
17788 end Exports;
17789 @end cartouche
17790 @end group
17791 @end smallexample
17792
17793 @noindent
17794 In this case, the link name for @var{Var1} is whatever link name the
17795 C compiler would assign for the C function @var{var1_name}. This typically
17796 would be either @var{var1_name} or @var{_var1_name}, depending on operating
17797 system conventions, but other possibilities exist. The link name for
17798 @var{Var2} is @var{var2_link_name}, and this is not operating system
17799 dependent.
17800
17801 @findex _main
17802 One exception occurs for library level procedures. A potential ambiguity
17803 arises between the required name @code{_main} for the C main program,
17804 and the name we would otherwise assign to an Ada library level procedure
17805 called @code{Main} (which might well not be the main program).
17806
17807 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
17808 names. So if we have a library level procedure such as
17809
17810 @smallexample @c ada
17811 @group
17812 @cartouche
17813 procedure Hello (S : String);
17814 @end cartouche
17815 @end group
17816 @end smallexample
17817
17818 @noindent
17819 the external name of this procedure will be @var{_ada_hello}.
17820
17821
17822 @node Converting Ada Files to html with gnathtml
17823 @section Converting Ada Files to HTML with @code{gnathtml}
17824
17825 @noindent
17826 This @code{Perl} script allows Ada source files to be browsed using
17827 standard Web browsers. For installation procedure, see the section
17828 @xref{Installing gnathtml}.
17829
17830 Ada reserved keywords are highlighted in a bold font and Ada comments in
17831 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
17832 switch to suppress the generation of cross-referencing information, user
17833 defined variables and types will appear in a different color; you will
17834 be able to click on any identifier and go to its declaration.
17835
17836 The command line is as follow:
17837 @smallexample
17838 @c $ perl gnathtml.pl @ovar{^switches^options^} @var{ada-files}
17839 @c Expanding @ovar macro inline (explanation in macro def comments)
17840 $ perl gnathtml.pl @r{[}@var{^switches^options^}@r{]} @var{ada-files}
17841 @end smallexample
17842
17843 @noindent
17844 You can pass it as many Ada files as you want. @code{gnathtml} will generate
17845 an html file for every ada file, and a global file called @file{index.htm}.
17846 This file is an index of every identifier defined in the files.
17847
17848 The available ^switches^options^ are the following ones:
17849
17850 @table @option
17851 @item -83
17852 @cindex @option{-83} (@code{gnathtml})
17853 Only the Ada 83 subset of keywords will be highlighted.
17854
17855 @item -cc @var{color}
17856 @cindex @option{-cc} (@code{gnathtml})
17857 This option allows you to change the color used for comments. The default
17858 value is green. The color argument can be any name accepted by html.
17859
17860 @item -d
17861 @cindex @option{-d} (@code{gnathtml})
17862 If the Ada files depend on some other files (for instance through
17863 @code{with} clauses, the latter files will also be converted to html.
17864 Only the files in the user project will be converted to html, not the files
17865 in the run-time library itself.
17866
17867 @item -D
17868 @cindex @option{-D} (@code{gnathtml})
17869 This command is the same as @option{-d} above, but @command{gnathtml} will
17870 also look for files in the run-time library, and generate html files for them.
17871
17872 @item -ext @var{extension}
17873 @cindex @option{-ext} (@code{gnathtml})
17874 This option allows you to change the extension of the generated HTML files.
17875 If you do not specify an extension, it will default to @file{htm}.
17876
17877 @item -f
17878 @cindex @option{-f} (@code{gnathtml})
17879 By default, gnathtml will generate html links only for global entities
17880 ('with'ed units, global variables and types,@dots{}).  If you specify
17881 @option{-f} on the command line, then links will be generated for local
17882 entities too.
17883
17884 @item -l @var{number}
17885 @cindex @option{-l} (@code{gnathtml})
17886 If this ^switch^option^ is provided and @var{number} is not 0, then
17887 @code{gnathtml} will number the html files every @var{number} line.
17888
17889 @item -I @var{dir}
17890 @cindex @option{-I} (@code{gnathtml})
17891 Specify a directory to search for library files (@file{.ALI} files) and
17892 source files. You can provide several -I switches on the command line,
17893 and the directories will be parsed in the order of the command line.
17894
17895 @item -o @var{dir}
17896 @cindex @option{-o} (@code{gnathtml})
17897 Specify the output directory for html files. By default, gnathtml will
17898 saved the generated html files in a subdirectory named @file{html/}.
17899
17900 @item -p @var{file}
17901 @cindex @option{-p} (@code{gnathtml})
17902 If you are using Emacs and the most recent Emacs Ada mode, which provides
17903 a full Integrated Development Environment for compiling, checking,
17904 running and debugging applications, you may use @file{.gpr} files
17905 to give the directories where Emacs can find sources and object files.
17906
17907 Using this ^switch^option^, you can tell gnathtml to use these files.
17908 This allows you to get an html version of your application, even if it
17909 is spread over multiple directories.
17910
17911 @item -sc @var{color}
17912 @cindex @option{-sc} (@code{gnathtml})
17913 This ^switch^option^ allows you to change the color used for symbol
17914 definitions.
17915 The default value is red. The color argument can be any name accepted by html.
17916
17917 @item -t @var{file}
17918 @cindex @option{-t} (@code{gnathtml})
17919 This ^switch^option^ provides the name of a file. This file contains a list of
17920 file names to be converted, and the effect is exactly as though they had
17921 appeared explicitly on the command line. This
17922 is the recommended way to work around the command line length limit on some
17923 systems.
17924
17925 @end table
17926
17927 @node Installing gnathtml
17928 @section Installing @code{gnathtml}
17929
17930 @noindent
17931 @code{Perl} needs to be installed on your machine to run this script.
17932 @code{Perl} is freely available for almost every architecture and
17933 Operating System via the Internet.
17934
17935 On Unix systems, you  may want to modify  the  first line of  the script
17936 @code{gnathtml},  to explicitly  tell  the Operating  system  where Perl
17937 is. The syntax of this line is:
17938 @smallexample
17939 #!full_path_name_to_perl
17940 @end smallexample
17941
17942 @noindent
17943 Alternatively, you may run the script using the following command line:
17944
17945 @smallexample
17946 @c $ perl gnathtml.pl @ovar{switches} @var{files}
17947 @c Expanding @ovar macro inline (explanation in macro def comments)
17948 $ perl gnathtml.pl @r{[}@var{switches}@r{]} @var{files}
17949 @end smallexample
17950
17951 @ifset vms
17952 @node LSE
17953 @section LSE
17954 @findex LSE
17955
17956 @noindent
17957 The GNAT distribution provides an Ada 95 template for the HP Language
17958 Sensitive Editor (LSE), a component of DECset. In order to
17959 access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
17960
17961 @node Profiling
17962 @section Profiling
17963 @findex PCA
17964
17965 @noindent
17966 GNAT supports The HP Performance Coverage Analyzer (PCA), a component
17967 of DECset. To use it proceed as outlined under ``HELP PCA'', except for running
17968 the collection phase with the /DEBUG qualifier.
17969
17970 @smallexample
17971 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
17972 $ DEFINE LIB$DEBUG PCA$COLLECTOR
17973 $ RUN/DEBUG <PROGRAM_NAME>
17974 @end smallexample
17975 @noindent
17976 @end ifset
17977
17978 @ifclear vms
17979 @c ******************************
17980 @node Code Coverage and Profiling
17981 @chapter Code Coverage and Profiling
17982 @cindex Code Coverage
17983 @cindex Profiling
17984
17985 @noindent
17986 This chapter describes how to use @code{gcov} - coverage testing tool - and
17987 @code{gprof} - profiler tool - on your Ada programs.
17988
17989 @menu
17990 * Code Coverage of Ada Programs using gcov::
17991 * Profiling an Ada Program using gprof::
17992 @end menu
17993
17994 @node Code Coverage of Ada Programs using gcov
17995 @section Code Coverage of Ada Programs using gcov
17996 @cindex gcov
17997 @cindex -fprofile-arcs
17998 @cindex -ftest-coverage
17999 @cindex -coverage
18000 @cindex Code Coverage
18001
18002 @noindent
18003 @code{gcov} is a test coverage program: it analyzes the execution of a given
18004 program on selected tests, to help you determine the portions of the program
18005 that are still untested.
18006
18007 @code{gcov} is part of the GCC suite, and is described in detail in the GCC
18008 User's Guide. You can refer to this documentation for a more complete
18009 description.
18010
18011 This chapter provides a quick startup guide, and
18012 details some Gnat-specific features.
18013
18014 @menu
18015 * Quick startup guide::
18016 * Gnat specifics::
18017 @end menu
18018
18019 @node Quick startup guide
18020 @subsection Quick startup guide
18021
18022 In order to perform coverage analysis of a program using @code{gcov}, 3
18023 steps are needed:
18024
18025 @itemize @bullet
18026 @item
18027 Code instrumentation during the compilation process
18028 @item
18029 Execution of the instrumented program
18030 @item
18031 Execution of the @code{gcov} tool to generate the result.
18032 @end itemize
18033
18034 The code instrumentation needed by gcov is created at the object level:
18035 The source code is not modified in any way, because the instrumentation code is
18036 inserted by gcc during the compilation process. To compile your code with code
18037 coverage activated, you need to recompile your whole project using the
18038 switches
18039 @code{-fprofile-arcs} and @code{-ftest-coverage}, and link it using
18040 @code{-fprofile-arcs}.
18041
18042 @smallexample
18043 $ gnatmake -P my_project.gpr -f -cargs -fprofile-arcs -ftest-coverage \
18044    -largs -fprofile-arcs
18045 @end smallexample
18046
18047 This compilation process will create @file{.gcno} files together with
18048 the usual object files.
18049
18050 Once the program is compiled with coverage instrumentation, you can
18051 run it as many times as needed - on portions of a test suite for
18052 example. The first execution will produce @file{.gcda} files at the
18053 same location as the @file{.gcno} files.  The following executions
18054 will update those files, so that a cumulative result of the covered
18055 portions of the program is generated.
18056
18057 Finally, you need to call the @code{gcov} tool. The different options of
18058 @code{gcov} are available in the GCC User's Guide, section 'Invoking gcov'.
18059
18060 This will create annotated source files with a @file{.gcov} extension:
18061 @file{my_main.adb} file will be analysed in @file{my_main.adb.gcov}.
18062
18063 @node Gnat specifics
18064 @subsection Gnat specifics
18065
18066 Because Ada semantics, portions of the source code may be shared among
18067 several object files. This is the case for example when generics are
18068 involved, when inlining is active  or when declarations generate  initialisation
18069 calls. In order to take
18070 into account this shared code, you need to call @code{gcov} on all
18071 source files of the tested program at once.
18072
18073 The list of source files might exceed the system's maximum command line
18074 length. In order to bypass this limitation, a new mechanism has been
18075 implemented in @code{gcov}: you can now list all your project's files into a
18076 text file, and provide this file to gcov as a parameter,  preceded by a @@
18077 (e.g. @samp{gcov @@mysrclist.txt}).
18078
18079 Note that on AIX compiling a static library with @code{-fprofile-arcs} is
18080 not supported as there can be unresolved symbols during the final link.
18081
18082 @node Profiling an Ada Program using gprof
18083 @section Profiling an Ada Program using gprof
18084 @cindex gprof
18085 @cindex -pg
18086 @cindex Profiling
18087
18088 @noindent
18089 This section is not meant to be an exhaustive documentation of @code{gprof}.
18090 Full documentation for it can be found in the GNU Profiler User's Guide
18091 documentation that is part of this GNAT distribution.
18092
18093 Profiling a program helps determine the parts of a program that are executed
18094 most often, and are therefore the most time-consuming.
18095
18096 @code{gprof} is the standard GNU profiling tool; it has been enhanced to
18097 better handle Ada programs and multitasking.
18098 It is currently supported on the following platforms
18099 @itemize @bullet
18100 @item
18101 linux x86/x86_64
18102 @item
18103 solaris sparc/sparc64/x86
18104 @item
18105 windows x86
18106 @end itemize
18107
18108 @noindent
18109 In order to profile a program using @code{gprof}, 3 steps are needed:
18110
18111 @itemize @bullet
18112 @item
18113 Code instrumentation, requiring a full recompilation of the project with the
18114 proper switches.
18115 @item
18116 Execution of the program under the analysis conditions, i.e. with the desired
18117 input.
18118 @item
18119 Analysis of the results using the @code{gprof} tool.
18120 @end itemize
18121
18122 @noindent
18123 The following sections detail the different steps, and indicate how
18124 to interpret the results:
18125 @menu
18126 * Compilation for profiling::
18127 * Program execution::
18128 * Running gprof::
18129 * Interpretation of profiling results::
18130 @end menu
18131
18132 @node Compilation for profiling
18133 @subsection Compilation for profiling
18134 @cindex -pg
18135 @cindex Profiling
18136
18137 In order to profile a program the first step is to tell the compiler
18138 to generate the necessary profiling information. The compiler switch to be used
18139 is @code{-pg}, which must be added to other compilation switches. This
18140 switch needs to be specified both during compilation and link stages, and can
18141 be specified once when using gnatmake:
18142
18143 @smallexample
18144 gnatmake -f -pg -P my_project
18145 @end smallexample
18146
18147 @noindent
18148 Note that only the objects that were compiled with the @samp{-pg} switch will
18149 be profiled; if you need to profile your whole project, use the @samp{-f}
18150 gnatmake switch to force full recompilation.
18151
18152 @node Program execution
18153 @subsection Program execution
18154
18155 @noindent
18156 Once the program has been compiled for profiling, you can run it as usual.
18157
18158 The only constraint imposed by profiling is that the program must terminate
18159 normally. An interrupted program (via a Ctrl-C, kill, etc.) will not be
18160 properly analyzed.
18161
18162 Once the program completes execution, a data file called @file{gmon.out} is
18163 generated in the directory where the program was launched from. If this file
18164 already exists, it will be overwritten.
18165
18166 @node Running gprof
18167 @subsection Running gprof
18168
18169 @noindent
18170 The @code{gprof} tool is called as follow:
18171
18172 @smallexample
18173 gprof my_prog gmon.out
18174 @end smallexample
18175
18176 @noindent
18177 or simpler:
18178
18179 @smallexample
18180 gprof my_prog
18181 @end smallexample
18182
18183 @noindent
18184 The complete form of the gprof command line is the following:
18185
18186 @smallexample
18187 gprof [^switches^options^] [executable [data-file]]
18188 @end smallexample
18189
18190 @noindent
18191 @code{gprof} supports numerous ^switch^options^. The order of these
18192 ^switch^options^ does not matter. The full list of options can be found in
18193 the GNU Profiler User's Guide documentation that comes with this documentation.
18194
18195 The following is the subset of those switches that is most relevant:
18196
18197 @table @option
18198
18199 @item --demangle[=@var{style}]
18200 @itemx --no-demangle
18201 @cindex @option{--demangle} (@code{gprof})
18202 These options control whether symbol names should be demangled when
18203 printing output.  The default is to demangle C++ symbols.  The
18204 @code{--no-demangle} option may be used to turn off demangling. Different
18205 compilers have different mangling styles.  The optional demangling style
18206 argument can be used to choose an appropriate demangling style for your
18207 compiler, in particular Ada symbols generated by GNAT can be demangled using
18208 @code{--demangle=gnat}.
18209
18210 @item -e @var{function_name}
18211 @cindex @option{-e} (@code{gprof})
18212 The @samp{-e @var{function}} option tells @code{gprof} not to print
18213 information about the function @var{function_name} (and its
18214 children@dots{}) in the call graph.  The function will still be listed
18215 as a child of any functions that call it, but its index number will be
18216 shown as @samp{[not printed]}.  More than one @samp{-e} option may be
18217 given; only one @var{function_name} may be indicated with each @samp{-e}
18218 option.
18219
18220 @item -E @var{function_name}
18221 @cindex @option{-E} (@code{gprof})
18222 The @code{-E @var{function}} option works like the @code{-e} option, but
18223 execution time spent in the function (and children who were not called from
18224 anywhere else), will not be used to compute the percentages-of-time for
18225 the call graph.  More than one @samp{-E} option may be given; only one
18226 @var{function_name} may be indicated with each @samp{-E} option.
18227
18228 @item -f @var{function_name}
18229 @cindex @option{-f} (@code{gprof})
18230 The @samp{-f @var{function}} option causes @code{gprof} to limit the
18231 call graph to the function @var{function_name} and its children (and
18232 their children@dots{}).  More than one @samp{-f} option may be given;
18233 only one @var{function_name} may be indicated with each @samp{-f}
18234 option.
18235
18236 @item -F @var{function_name}
18237 @cindex @option{-F} (@code{gprof})
18238 The @samp{-F @var{function}} option works like the @code{-f} option, but
18239 only time spent in the function and its children (and their
18240 children@dots{}) will be used to determine total-time and
18241 percentages-of-time for the call graph.  More than one @samp{-F} option
18242 may be given; only one @var{function_name} may be indicated with each
18243 @samp{-F} option.  The @samp{-F} option overrides the @samp{-E} option.
18244
18245 @end table
18246
18247 @node Interpretation of profiling results
18248 @subsection Interpretation of profiling results
18249
18250 @noindent
18251
18252 The results of the profiling analysis are represented by two arrays: the
18253 'flat profile' and the 'call graph'. Full documentation of those outputs
18254 can be found in the GNU Profiler User's Guide.
18255
18256 The flat profile shows the time spent in each function of the program, and how
18257 many time it has been called. This allows you to locate easily the most
18258 time-consuming functions.
18259
18260 The call graph shows, for each subprogram, the subprograms that call it,
18261 and the subprograms that it calls. It also provides an estimate of the time
18262 spent in each of those callers/called subprograms.
18263 @end ifclear
18264
18265 @c ******************************
18266 @node Running and Debugging Ada Programs
18267 @chapter Running and Debugging Ada Programs
18268 @cindex Debugging
18269
18270 @noindent
18271 This chapter discusses how to debug Ada programs.
18272 @ifset vms
18273 It applies to GNAT on the Alpha OpenVMS platform;
18274 for I64 OpenVMS please refer to the @cite{OpenVMS Debugger Manual},
18275 since HP has implemented Ada support in the OpenVMS debugger on I64.
18276 @end ifset
18277
18278 An incorrect Ada program may be handled in three ways by the GNAT compiler:
18279
18280 @enumerate
18281 @item
18282 The illegality may be a violation of the static semantics of Ada. In
18283 that case GNAT diagnoses the constructs in the program that are illegal.
18284 It is then a straightforward matter for the user to modify those parts of
18285 the program.
18286
18287 @item
18288 The illegality may be a violation of the dynamic semantics of Ada. In
18289 that case the program compiles and executes, but may generate incorrect
18290 results, or may terminate abnormally with some exception.
18291
18292 @item
18293 When presented with a program that contains convoluted errors, GNAT
18294 itself may terminate abnormally without providing full diagnostics on
18295 the incorrect user program.
18296 @end enumerate
18297
18298 @menu
18299 * The GNAT Debugger GDB::
18300 * Running GDB::
18301 * Introduction to GDB Commands::
18302 * Using Ada Expressions::
18303 * Calling User-Defined Subprograms::
18304 * Using the Next Command in a Function::
18305 * Ada Exceptions::
18306 * Ada Tasks::
18307 * Debugging Generic Units::
18308 * Remote Debugging using gdbserver::
18309 * GNAT Abnormal Termination or Failure to Terminate::
18310 * Naming Conventions for GNAT Source Files::
18311 * Getting Internal Debugging Information::
18312 * Stack Traceback::
18313 @end menu
18314
18315 @cindex Debugger
18316 @findex gdb
18317
18318 @node The GNAT Debugger GDB
18319 @section The GNAT Debugger GDB
18320
18321 @noindent
18322 @code{GDB} is a general purpose, platform-independent debugger that
18323 can be used to debug mixed-language programs compiled with @command{gcc},
18324 and in particular is capable of debugging Ada programs compiled with
18325 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
18326 complex Ada data structures.
18327
18328 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
18329 @ifset vms
18330 located in the GNU:[DOCS] directory,
18331 @end ifset
18332 for full details on the usage of @code{GDB}, including a section on
18333 its usage on programs. This manual should be consulted for full
18334 details. The section that follows is a brief introduction to the
18335 philosophy and use of @code{GDB}.
18336
18337 When GNAT programs are compiled, the compiler optionally writes debugging
18338 information into the generated object file, including information on
18339 line numbers, and on declared types and variables. This information is
18340 separate from the generated code. It makes the object files considerably
18341 larger, but it does not add to the size of the actual executable that
18342 will be loaded into memory, and has no impact on run-time performance. The
18343 generation of debug information is triggered by the use of the
18344 ^-g^/DEBUG^ switch in the @command{gcc} or @command{gnatmake} command
18345 used to carry out the compilations. It is important to emphasize that
18346 the use of these options does not change the generated code.
18347
18348 The debugging information is written in standard system formats that
18349 are used by many tools, including debuggers and profilers. The format
18350 of the information is typically designed to describe C types and
18351 semantics, but GNAT implements a translation scheme which allows full
18352 details about Ada types and variables to be encoded into these
18353 standard C formats. Details of this encoding scheme may be found in
18354 the file exp_dbug.ads in the GNAT source distribution. However, the
18355 details of this encoding are, in general, of no interest to a user,
18356 since @code{GDB} automatically performs the necessary decoding.
18357
18358 When a program is bound and linked, the debugging information is
18359 collected from the object files, and stored in the executable image of
18360 the program. Again, this process significantly increases the size of
18361 the generated executable file, but it does not increase the size of
18362 the executable program itself. Furthermore, if this program is run in
18363 the normal manner, it runs exactly as if the debug information were
18364 not present, and takes no more actual memory.
18365
18366 However, if the program is run under control of @code{GDB}, the
18367 debugger is activated.  The image of the program is loaded, at which
18368 point it is ready to run.  If a run command is given, then the program
18369 will run exactly as it would have if @code{GDB} were not present. This
18370 is a crucial part of the @code{GDB} design philosophy.  @code{GDB} is
18371 entirely non-intrusive until a breakpoint is encountered.  If no
18372 breakpoint is ever hit, the program will run exactly as it would if no
18373 debugger were present. When a breakpoint is hit, @code{GDB} accesses
18374 the debugging information and can respond to user commands to inspect
18375 variables, and more generally to report on the state of execution.
18376
18377 @c **************
18378 @node Running GDB
18379 @section Running GDB
18380
18381 @noindent
18382 This section describes how to initiate the debugger.
18383 @c The above sentence is really just filler, but it was otherwise
18384 @c clumsy to get the first paragraph nonindented given the conditional
18385 @c nature of the description
18386
18387 @ifclear vms
18388 The debugger can be launched from a @code{GPS} menu or
18389 directly from the command line. The description below covers the latter use.
18390 All the commands shown can be used in the @code{GPS} debug console window,
18391 but there are usually more GUI-based ways to achieve the same effect.
18392 @end ifclear
18393
18394 The command to run @code{GDB} is
18395
18396 @smallexample
18397 $ ^gdb program^GDB PROGRAM^
18398 @end smallexample
18399
18400 @noindent
18401 where @code{^program^PROGRAM^} is the name of the executable file. This
18402 activates the debugger and results in a prompt for debugger commands.
18403 The simplest command is simply @code{run}, which causes the program to run
18404 exactly as if the debugger were not present. The following section
18405 describes some of the additional commands that can be given to @code{GDB}.
18406
18407 @c *******************************
18408 @node Introduction to GDB Commands
18409 @section Introduction to GDB Commands
18410
18411 @noindent
18412 @code{GDB} contains a large repertoire of commands.  @xref{Top,,
18413 Debugging with GDB, gdb, Debugging with GDB},
18414 @ifset vms
18415 located in the GNU:[DOCS] directory,
18416 @end ifset
18417 for extensive documentation on the use
18418 of these commands, together with examples of their use. Furthermore,
18419 the command @command{help} invoked from within GDB activates a simple help
18420 facility which summarizes the available commands and their options.
18421 In this section we summarize a few of the most commonly
18422 used commands to give an idea of what @code{GDB} is about. You should create
18423 a simple program with debugging information and experiment with the use of
18424 these @code{GDB} commands on the program as you read through the
18425 following section.
18426
18427 @table @code
18428 @item set args @var{arguments}
18429 The @var{arguments} list above is a list of arguments to be passed to
18430 the program on a subsequent run command, just as though the arguments
18431 had been entered on a normal invocation of the program. The @code{set args}
18432 command is not needed if the program does not require arguments.
18433
18434 @item run
18435 The @code{run} command causes execution of the program to start from
18436 the beginning. If the program is already running, that is to say if
18437 you are currently positioned at a breakpoint, then a prompt will ask
18438 for confirmation that you want to abandon the current execution and
18439 restart.
18440
18441 @item breakpoint @var{location}
18442 The breakpoint command sets a breakpoint, that is to say a point at which
18443 execution will halt and @code{GDB} will await further
18444 commands. @var{location} is
18445 either a line number within a file, given in the format @code{file:linenumber},
18446 or it is the name of a subprogram. If you request that a breakpoint be set on
18447 a subprogram that is overloaded, a prompt will ask you to specify on which of
18448 those subprograms you want to breakpoint. You can also
18449 specify that all of them should be breakpointed. If the program is run
18450 and execution encounters the breakpoint, then the program
18451 stops and @code{GDB} signals that the breakpoint was encountered by
18452 printing the line of code before which the program is halted.
18453
18454 @item catch exception @var{name}
18455 This command causes the program execution to stop whenever exception
18456 @var{name} is raised.  If @var{name} is omitted, then the execution is
18457 suspended when any exception is raised.
18458
18459 @item print @var{expression}
18460 This will print the value of the given expression. Most simple
18461 Ada expression formats are properly handled by @code{GDB}, so the expression
18462 can contain function calls, variables, operators, and attribute references.
18463
18464 @item continue
18465 Continues execution following a breakpoint, until the next breakpoint or the
18466 termination of the program.
18467
18468 @item step
18469 Executes a single line after a breakpoint. If the next statement
18470 is a subprogram call, execution continues into (the first statement of)
18471 the called subprogram.
18472
18473 @item next
18474 Executes a single line. If this line is a subprogram call, executes and
18475 returns from the call.
18476
18477 @item list
18478 Lists a few lines around the current source location. In practice, it
18479 is usually more convenient to have a separate edit window open with the
18480 relevant source file displayed. Successive applications of this command
18481 print subsequent lines. The command can be given an argument which is a
18482 line number, in which case it displays a few lines around the specified one.
18483
18484 @item backtrace
18485 Displays a backtrace of the call chain. This command is typically
18486 used after a breakpoint has occurred, to examine the sequence of calls that
18487 leads to the current breakpoint. The display includes one line for each
18488 activation record (frame) corresponding to an active subprogram.
18489
18490 @item up
18491 At a breakpoint, @code{GDB} can display the values of variables local
18492 to the current frame. The command @code{up} can be used to
18493 examine the contents of other active frames, by moving the focus up
18494 the stack, that is to say from callee to caller, one frame at a time.
18495
18496 @item down
18497 Moves the focus of @code{GDB} down from the frame currently being
18498 examined to the frame of its callee (the reverse of the previous command),
18499
18500 @item frame @var{n}
18501 Inspect the frame with the given number. The value 0 denotes the frame
18502 of the current breakpoint, that is to say the top of the call stack.
18503
18504 @end table
18505
18506 @noindent
18507 The above list is a very short introduction to the commands that
18508 @code{GDB} provides. Important additional capabilities, including conditional
18509 breakpoints, the ability to execute command sequences on a breakpoint,
18510 the ability to debug at the machine instruction level and many other
18511 features are described in detail in @ref{Top,, Debugging with GDB, gdb,
18512 Debugging with GDB}.  Note that most commands can be abbreviated
18513 (for example, c for continue, bt for backtrace).
18514
18515 @node Using Ada Expressions
18516 @section Using Ada Expressions
18517 @cindex Ada expressions
18518
18519 @noindent
18520 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
18521 extensions. The philosophy behind the design of this subset is
18522
18523 @itemize @bullet
18524 @item
18525 That @code{GDB} should provide basic literals and access to operations for
18526 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
18527 leaving more sophisticated computations to subprograms written into the
18528 program (which therefore may be called from @code{GDB}).
18529
18530 @item
18531 That type safety and strict adherence to Ada language restrictions
18532 are not particularly important to the @code{GDB} user.
18533
18534 @item
18535 That brevity is important to the @code{GDB} user.
18536 @end itemize
18537
18538 @noindent
18539 Thus, for brevity, the debugger acts as if there were
18540 implicit @code{with} and @code{use} clauses in effect for all user-written
18541 packages, thus making it unnecessary to fully qualify most names with
18542 their packages, regardless of context. Where this causes ambiguity,
18543 @code{GDB} asks the user's intent.
18544
18545 For details on the supported Ada syntax, see @ref{Top,, Debugging with
18546 GDB, gdb, Debugging with GDB}.
18547
18548 @node Calling User-Defined Subprograms
18549 @section Calling User-Defined Subprograms
18550
18551 @noindent
18552 An important capability of @code{GDB} is the ability to call user-defined
18553 subprograms while debugging. This is achieved simply by entering
18554 a subprogram call statement in the form:
18555
18556 @smallexample
18557 call subprogram-name (parameters)
18558 @end smallexample
18559
18560 @noindent
18561 The keyword @code{call} can be omitted in the normal case where the
18562 @code{subprogram-name} does not coincide with any of the predefined
18563 @code{GDB} commands.
18564
18565 The effect is to invoke the given subprogram, passing it the
18566 list of parameters that is supplied. The parameters can be expressions and
18567 can include variables from the program being debugged. The
18568 subprogram must be defined
18569 at the library level within your program, and @code{GDB} will call the
18570 subprogram within the environment of your program execution (which
18571 means that the subprogram is free to access or even modify variables
18572 within your program).
18573
18574 The most important use of this facility is in allowing the inclusion of
18575 debugging routines that are tailored to particular data structures
18576 in your program. Such debugging routines can be written to provide a suitably
18577 high-level description of an abstract type, rather than a low-level dump
18578 of its physical layout. After all, the standard
18579 @code{GDB print} command only knows the physical layout of your
18580 types, not their abstract meaning. Debugging routines can provide information
18581 at the desired semantic level and are thus enormously useful.
18582
18583 For example, when debugging GNAT itself, it is crucial to have access to
18584 the contents of the tree nodes used to represent the program internally.
18585 But tree nodes are represented simply by an integer value (which in turn
18586 is an index into a table of nodes).
18587 Using the @code{print} command on a tree node would simply print this integer
18588 value, which is not very useful. But the PN routine (defined in file
18589 treepr.adb in the GNAT sources) takes a tree node as input, and displays
18590 a useful high level representation of the tree node, which includes the
18591 syntactic category of the node, its position in the source, the integers
18592 that denote descendant nodes and parent node, as well as varied
18593 semantic information. To study this example in more detail, you might want to
18594 look at the body of the PN procedure in the stated file.
18595
18596 @node Using the Next Command in a Function
18597 @section Using the Next Command in a Function
18598
18599 @noindent
18600 When you use the @code{next} command in a function, the current source
18601 location will advance to the next statement as usual. A special case
18602 arises in the case of a @code{return} statement.
18603
18604 Part of the code for a return statement is the ``epilog'' of the function.
18605 This is the code that returns to the caller. There is only one copy of
18606 this epilog code, and it is typically associated with the last return
18607 statement in the function if there is more than one return. In some
18608 implementations, this epilog is associated with the first statement
18609 of the function.
18610
18611 The result is that if you use the @code{next} command from a return
18612 statement that is not the last return statement of the function you
18613 may see a strange apparent jump to the last return statement or to
18614 the start of the function. You should simply ignore this odd jump.
18615 The value returned is always that from the first return statement
18616 that was stepped through.
18617
18618 @node Ada Exceptions
18619 @section Stopping when Ada Exceptions are Raised
18620 @cindex Exceptions
18621
18622 @noindent
18623 You can set catchpoints that stop the program execution when your program
18624 raises selected exceptions.
18625
18626 @table @code
18627 @item catch exception
18628 Set a catchpoint that stops execution whenever (any task in the) program
18629 raises any exception.
18630
18631 @item catch exception @var{name}
18632 Set a catchpoint that stops execution whenever (any task in the) program
18633 raises the exception @var{name}.
18634
18635 @item catch exception unhandled
18636 Set a catchpoint that stops executino whenever (any task in the) program
18637 raises an exception for which there is no handler.
18638
18639 @item info exceptions
18640 @itemx info exceptions @var{regexp}
18641 The @code{info exceptions} command permits the user to examine all defined
18642 exceptions within Ada programs. With a regular expression, @var{regexp}, as
18643 argument, prints out only those exceptions whose name matches @var{regexp}.
18644 @end table
18645
18646 @node Ada Tasks
18647 @section Ada Tasks
18648 @cindex Tasks
18649
18650 @noindent
18651 @code{GDB} allows the following task-related commands:
18652
18653 @table @code
18654 @item info tasks
18655 This command shows a list of current Ada tasks, as in the following example:
18656
18657 @smallexample
18658 @iftex
18659 @leftskip=0cm
18660 @end iftex
18661 (gdb) info tasks
18662   ID       TID P-ID   Thread Pri State                 Name
18663    1   8088000   0   807e000  15 Child Activation Wait main_task
18664    2   80a4000   1   80ae000  15 Accept/Select Wait    b
18665    3   809a800   1   80a4800  15 Child Activation Wait a
18666 *  4   80ae800   3   80b8000  15 Running               c
18667 @end smallexample
18668
18669 @noindent
18670 In this listing, the asterisk before the first task indicates it to be the
18671 currently running task. The first column lists the task ID that is used
18672 to refer to tasks in the following commands.
18673
18674 @item break @var{linespec} task @var{taskid}
18675 @itemx break @var{linespec} task @var{taskid} if @dots{}
18676 @cindex Breakpoints and tasks
18677 These commands are like the @code{break @dots{} thread @dots{}}.
18678 @var{linespec} specifies source lines.
18679
18680 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
18681 to specify that you only want @code{GDB} to stop the program when a
18682 particular Ada task reaches this breakpoint. @var{taskid} is one of the
18683 numeric task identifiers assigned by @code{GDB}, shown in the first
18684 column of the @samp{info tasks} display.
18685
18686 If you do not specify @samp{task @var{taskid}} when you set a
18687 breakpoint, the breakpoint applies to @emph{all} tasks of your
18688 program.
18689
18690 You can use the @code{task} qualifier on conditional breakpoints as
18691 well; in this case, place @samp{task @var{taskid}} before the
18692 breakpoint condition (before the @code{if}).
18693
18694 @item task @var{taskno}
18695 @cindex Task switching
18696
18697 This command allows to switch to the task referred by @var{taskno}. In
18698 particular, This allows to browse the backtrace of the specified
18699 task. It is advised to switch back to the original task before
18700 continuing execution otherwise the scheduling of the program may be
18701 perturbed.
18702 @end table
18703
18704 @noindent
18705 For more detailed information on the tasking support,
18706 see @ref{Top,, Debugging with GDB, gdb, Debugging with GDB}.
18707
18708 @node Debugging Generic Units
18709 @section Debugging Generic Units
18710 @cindex Debugging Generic Units
18711 @cindex Generics
18712
18713 @noindent
18714 GNAT always uses code expansion for generic instantiation. This means that
18715 each time an instantiation occurs, a complete copy of the original code is
18716 made, with appropriate substitutions of formals by actuals.
18717
18718 It is not possible to refer to the original generic entities in
18719 @code{GDB}, but it is always possible to debug a particular instance of
18720 a generic, by using the appropriate expanded names. For example, if we have
18721
18722 @smallexample @c ada
18723 @group
18724 @cartouche
18725 procedure g is
18726
18727    generic package k is
18728       procedure kp (v1 : in out integer);
18729    end k;
18730
18731    package body k is
18732       procedure kp (v1 : in out integer) is
18733       begin
18734          v1 := v1 + 1;
18735       end kp;
18736    end k;
18737
18738    package k1 is new k;
18739    package k2 is new k;
18740
18741    var : integer := 1;
18742
18743 begin
18744    k1.kp (var);
18745    k2.kp (var);
18746    k1.kp (var);
18747    k2.kp (var);
18748 end;
18749 @end cartouche
18750 @end group
18751 @end smallexample
18752
18753 @noindent
18754 Then to break on a call to procedure kp in the k2 instance, simply
18755 use the command:
18756
18757 @smallexample
18758 (gdb) break g.k2.kp
18759 @end smallexample
18760
18761 @noindent
18762 When the breakpoint occurs, you can step through the code of the
18763 instance in the normal manner and examine the values of local variables, as for
18764 other units.
18765
18766 @node Remote Debugging using gdbserver
18767 @section Remote Debugging using gdbserver
18768 @cindex Remote Debugging using gdbserver
18769
18770 @noindent
18771 On platforms where gdbserver is supported, it is possible to use this tool
18772 to debug your application remotely.  This can be useful in situations
18773 where the program needs to be run on a target host that is different
18774 from the host used for development, particularly when the target has
18775 a limited amount of resources (either CPU and/or memory).
18776
18777 To do so, start your program using gdbserver on the target machine.
18778 gdbserver then automatically suspends the execution of your program
18779 at its entry point, waiting for a debugger to connect to it.  The
18780 following commands starts an application and tells gdbserver to
18781 wait for a connection with the debugger on localhost port 4444.
18782
18783 @smallexample
18784 $ gdbserver localhost:4444 program
18785 Process program created; pid = 5685
18786 Listening on port 4444
18787 @end smallexample
18788
18789 Once gdbserver has started listening, we can tell the debugger to establish
18790 a connection with this gdbserver, and then start the same debugging session
18791 as if the program was being debugged on the same host, directly under
18792 the control of GDB.
18793
18794 @smallexample
18795 $ gdb program
18796 (gdb) target remote targethost:4444
18797 Remote debugging using targethost:4444
18798 0x00007f29936d0af0 in ?? () from /lib64/ld-linux-x86-64.so.
18799 (gdb) b foo.adb:3
18800 Breakpoint 1 at 0x401f0c: file foo.adb, line 3.
18801 (gdb) continue
18802 Continuing.
18803
18804 Breakpoint 1, foo () at foo.adb:4
18805 4       end foo;
18806 @end smallexample
18807
18808 It is also possible to use gdbserver to attach to an already running
18809 program, in which case the execution of that program is simply suspended
18810 until the connection between the debugger and gdbserver is established.
18811
18812 For more information on how to use gdbserver, @ref{Top, Server, Using
18813 the gdbserver Program, gdb, Debugging with GDB}.  GNAT Pro provides support
18814 for gdbserver on x86-linux, x86-windows and x86_64-linux.
18815
18816 @node GNAT Abnormal Termination or Failure to Terminate
18817 @section GNAT Abnormal Termination or Failure to Terminate
18818 @cindex GNAT Abnormal Termination or Failure to Terminate
18819
18820 @noindent
18821 When presented with programs that contain serious errors in syntax
18822 or semantics,
18823 GNAT may on rare occasions  experience problems in operation, such
18824 as aborting with a
18825 segmentation fault or illegal memory access, raising an internal
18826 exception, terminating abnormally, or failing to terminate at all.
18827 In such cases, you can activate
18828 various features of GNAT that can help you pinpoint the construct in your
18829 program that is the likely source of the problem.
18830
18831 The following strategies are presented in increasing order of
18832 difficulty, corresponding to your experience in using GNAT and your
18833 familiarity with compiler internals.
18834
18835 @enumerate
18836 @item
18837 Run @command{gcc} with the @option{-gnatf}. This first
18838 switch causes all errors on a given line to be reported. In its absence,
18839 only the first error on a line is displayed.
18840
18841 The @option{-gnatdO} switch causes errors to be displayed as soon as they
18842 are encountered, rather than after compilation is terminated. If GNAT
18843 terminates prematurely or goes into an infinite loop, the last error
18844 message displayed may help to pinpoint the culprit.
18845
18846 @item
18847 Run @command{gcc} with the @option{^-v (verbose)^/VERBOSE^} switch. In this
18848 mode, @command{gcc} produces ongoing information about the progress of the
18849 compilation and provides the name of each procedure as code is
18850 generated. This switch allows you to find which Ada procedure was being
18851 compiled when it encountered a code generation problem.
18852
18853 @item
18854 @cindex @option{-gnatdc} switch
18855 Run @command{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
18856 switch that does for the front-end what @option{^-v^VERBOSE^} does
18857 for the back end. The system prints the name of each unit,
18858 either a compilation unit or nested unit, as it is being analyzed.
18859 @item
18860 Finally, you can start
18861 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
18862 front-end of GNAT, and can be run independently (normally it is just
18863 called from @command{gcc}). You can use @code{gdb} on @code{gnat1} as you
18864 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
18865 @code{where} command is the first line of attack; the variable
18866 @code{lineno} (seen by @code{print lineno}), used by the second phase of
18867 @code{gnat1} and by the @command{gcc} backend, indicates the source line at
18868 which the execution stopped, and @code{input_file name} indicates the name of
18869 the source file.
18870 @end enumerate
18871
18872 @node Naming Conventions for GNAT Source Files
18873 @section Naming Conventions for GNAT Source Files
18874
18875 @noindent
18876 In order to examine the workings of the GNAT system, the following
18877 brief description of its organization may be helpful:
18878
18879 @itemize @bullet
18880 @item
18881 Files with prefix @file{^sc^SC^} contain the lexical scanner.
18882
18883 @item
18884 All files prefixed with @file{^par^PAR^} are components of the parser. The
18885 numbers correspond to chapters of the Ada Reference Manual. For example,
18886 parsing of select statements can be found in @file{par-ch9.adb}.
18887
18888 @item
18889 All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
18890 numbers correspond to chapters of the Ada standard. For example, all
18891 issues involving context clauses can be found in @file{sem_ch10.adb}. In
18892 addition, some features of the language require sufficient special processing
18893 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
18894 dynamic dispatching, etc.
18895
18896 @item
18897 All files prefixed with @file{^exp^EXP^} perform normalization and
18898 expansion of the intermediate representation (abstract syntax tree, or AST).
18899 these files use the same numbering scheme as the parser and semantics files.
18900 For example, the construction of record initialization procedures is done in
18901 @file{exp_ch3.adb}.
18902
18903 @item
18904 The files prefixed with @file{^bind^BIND^} implement the binder, which
18905 verifies the consistency of the compilation, determines an order of
18906 elaboration, and generates the bind file.
18907
18908 @item
18909 The files @file{atree.ads} and @file{atree.adb} detail the low-level
18910 data structures used by the front-end.
18911
18912 @item
18913 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
18914 the abstract syntax tree as produced by the parser.
18915
18916 @item
18917 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
18918 all entities, computed during semantic analysis.
18919
18920 @item
18921 Library management issues are dealt with in files with prefix
18922 @file{^lib^LIB^}.
18923
18924 @item
18925 @findex Ada
18926 @cindex Annex A
18927 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
18928 defined in Annex A.
18929
18930 @item
18931 @findex Interfaces
18932 @cindex Annex B
18933 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
18934 defined in Annex B.
18935
18936 @item
18937 @findex System
18938 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
18939 both language-defined children and GNAT run-time routines.
18940
18941 @item
18942 @findex GNAT
18943 Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
18944 general-purpose packages, fully documented in their specs. All
18945 the other @file{.c} files are modifications of common @command{gcc} files.
18946 @end itemize
18947
18948 @node Getting Internal Debugging Information
18949 @section Getting Internal Debugging Information
18950
18951 @noindent
18952 Most compilers have internal debugging switches and modes. GNAT
18953 does also, except GNAT internal debugging switches and modes are not
18954 secret. A summary and full description of all the compiler and binder
18955 debug flags are in the file @file{debug.adb}. You must obtain the
18956 sources of the compiler to see the full detailed effects of these flags.
18957
18958 The switches that print the source of the program (reconstructed from
18959 the internal tree) are of general interest for user programs, as are the
18960 options to print
18961 the full internal tree, and the entity table (the symbol table
18962 information). The reconstructed source provides a readable version of the
18963 program after the front-end has completed analysis and  expansion,
18964 and is useful when studying the performance of specific constructs.
18965 For example, constraint checks are indicated, complex aggregates
18966 are replaced with loops and assignments, and tasking primitives
18967 are replaced with run-time calls.
18968
18969 @node Stack Traceback
18970 @section Stack Traceback
18971 @cindex traceback
18972 @cindex stack traceback
18973 @cindex stack unwinding
18974
18975 @noindent
18976 Traceback is a mechanism to display the sequence of subprogram calls that
18977 leads to a specified execution point in a program. Often (but not always)
18978 the execution point is an instruction at which an exception has been raised.
18979 This mechanism is also known as @i{stack unwinding} because it obtains
18980 its information by scanning the run-time stack and recovering the activation
18981 records of all active subprograms. Stack unwinding is one of the most
18982 important tools for program debugging.
18983
18984 The first entry stored in traceback corresponds to the deepest calling level,
18985 that is to say the subprogram currently executing the instruction
18986 from which we want to obtain the traceback.
18987
18988 Note that there is no runtime performance penalty when stack traceback
18989 is enabled, and no exception is raised during program execution.
18990
18991 @menu
18992 * Non-Symbolic Traceback::
18993 * Symbolic Traceback::
18994 @end menu
18995
18996 @node Non-Symbolic Traceback
18997 @subsection Non-Symbolic Traceback
18998 @cindex traceback, non-symbolic
18999
19000 @noindent
19001 Note: this feature is not supported on all platforms. See
19002 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
19003 platforms.
19004
19005 @menu
19006 * Tracebacks From an Unhandled Exception::
19007 * Tracebacks From Exception Occurrences (non-symbolic)::
19008 * Tracebacks From Anywhere in a Program (non-symbolic)::
19009 @end menu
19010
19011 @node Tracebacks From an Unhandled Exception
19012 @subsubsection Tracebacks From an Unhandled Exception
19013
19014 @noindent
19015 A runtime non-symbolic traceback is a list of addresses of call instructions.
19016 To enable this feature you must use the @option{-E}
19017 @code{gnatbind}'s option. With this option a stack traceback is stored as part
19018 of exception information. You can retrieve this information using the
19019 @code{addr2line} tool.
19020
19021 Here is a simple example:
19022
19023 @smallexample @c ada
19024 @cartouche
19025 procedure STB is
19026
19027    procedure P1 is
19028    begin
19029       raise Constraint_Error;
19030    end P1;
19031
19032    procedure P2 is
19033    begin
19034       P1;
19035    end P2;
19036
19037 begin
19038    P2;
19039 end STB;
19040 @end cartouche
19041 @end smallexample
19042
19043 @smallexample
19044 $ gnatmake stb -bargs -E
19045 $ stb
19046
19047 Execution terminated by unhandled exception
19048 Exception name: CONSTRAINT_ERROR
19049 Message: stb.adb:5
19050 Call stack traceback locations:
19051 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
19052 @end smallexample
19053
19054 @noindent
19055 As we see the traceback lists a sequence of addresses for the unhandled
19056 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
19057 guess that this exception come from procedure P1. To translate these
19058 addresses into the source lines where the calls appear, the
19059 @code{addr2line} tool, described below, is invaluable. The use of this tool
19060 requires the program to be compiled with debug information.
19061
19062 @smallexample
19063 $ gnatmake -g stb -bargs -E
19064 $ stb
19065
19066 Execution terminated by unhandled exception
19067 Exception name: CONSTRAINT_ERROR
19068 Message: stb.adb:5
19069 Call stack traceback locations:
19070 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
19071
19072 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
19073    0x4011f1 0x77e892a4
19074
19075 00401373 at d:/stb/stb.adb:5
19076 0040138B at d:/stb/stb.adb:10
19077 0040139C at d:/stb/stb.adb:14
19078 00401335 at d:/stb/b~stb.adb:104
19079 004011C4 at /build/@dots{}/crt1.c:200
19080 004011F1 at /build/@dots{}/crt1.c:222
19081 77E892A4 in ?? at ??:0
19082 @end smallexample
19083
19084 @noindent
19085 The @code{addr2line} tool has several other useful options:
19086
19087 @table @code
19088 @item --functions
19089 to get the function name corresponding to any location
19090
19091 @item --demangle=gnat
19092 to use the gnat decoding mode for the function names. Note that
19093 for binutils version 2.9.x the option is simply @option{--demangle}.
19094 @end table
19095
19096 @smallexample
19097 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
19098    0x40139c 0x401335 0x4011c4 0x4011f1
19099
19100 00401373 in stb.p1 at d:/stb/stb.adb:5
19101 0040138B in stb.p2 at d:/stb/stb.adb:10
19102 0040139C in stb at d:/stb/stb.adb:14
19103 00401335 in main at d:/stb/b~stb.adb:104
19104 004011C4 in <__mingw_CRTStartup> at /build/@dots{}/crt1.c:200
19105 004011F1 in <mainCRTStartup> at /build/@dots{}/crt1.c:222
19106 @end smallexample
19107
19108 @noindent
19109 From this traceback we can see that the exception was raised in
19110 @file{stb.adb} at line 5, which was reached from a procedure call in
19111 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
19112 which contains the call to the main program.
19113 @xref{Running gnatbind}. The remaining entries are assorted runtime routines,
19114 and the output will vary from platform to platform.
19115
19116 It is also possible to use @code{GDB} with these traceback addresses to debug
19117 the program. For example, we can break at a given code location, as reported
19118 in the stack traceback:
19119
19120 @smallexample
19121 $ gdb -nw stb
19122 @ifclear vms
19123 @noindent
19124 Furthermore, this feature is not implemented inside Windows DLL. Only
19125 the non-symbolic traceback is reported in this case.
19126 @end ifclear
19127
19128 (gdb) break *0x401373
19129 Breakpoint 1 at 0x401373: file stb.adb, line 5.
19130 @end smallexample
19131
19132 @noindent
19133 It is important to note that the stack traceback addresses
19134 do not change when debug information is included. This is particularly useful
19135 because it makes it possible to release software without debug information (to
19136 minimize object size), get a field report that includes a stack traceback
19137 whenever an internal bug occurs, and then be able to retrieve the sequence
19138 of calls with the same program compiled with debug information.
19139
19140 @node Tracebacks From Exception Occurrences (non-symbolic)
19141 @subsubsection Tracebacks From Exception Occurrences
19142
19143 @noindent
19144 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
19145 The stack traceback is attached to the exception information string, and can
19146 be retrieved in an exception handler within the Ada program, by means of the
19147 Ada facilities defined in @code{Ada.Exceptions}. Here is a simple example:
19148
19149 @smallexample @c ada
19150 with Ada.Text_IO;
19151 with Ada.Exceptions;
19152
19153 procedure STB is
19154
19155    use Ada;
19156    use Ada.Exceptions;
19157
19158    procedure P1 is
19159       K : Positive := 1;
19160    begin
19161       K := K - 1;
19162    exception
19163       when E : others =>
19164          Text_IO.Put_Line (Exception_Information (E));
19165    end P1;
19166
19167    procedure P2 is
19168    begin
19169       P1;
19170    end P2;
19171
19172 begin
19173    P2;
19174 end STB;
19175 @end smallexample
19176
19177 @noindent
19178 This program will output:
19179
19180 @smallexample
19181 $ stb
19182
19183 Exception name: CONSTRAINT_ERROR
19184 Message: stb.adb:12
19185 Call stack traceback locations:
19186 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
19187 @end smallexample
19188
19189 @node Tracebacks From Anywhere in a Program (non-symbolic)
19190 @subsubsection Tracebacks From Anywhere in a Program
19191
19192 @noindent
19193 It is also possible to retrieve a stack traceback from anywhere in a
19194 program. For this you need to
19195 use the @code{GNAT.Traceback} API. This package includes a procedure called
19196 @code{Call_Chain} that computes a complete stack traceback, as well as useful
19197 display procedures described below. It is not necessary to use the
19198 @option{-E gnatbind} option in this case, because the stack traceback mechanism
19199 is invoked explicitly.
19200
19201 @noindent
19202 In the following example we compute a traceback at a specific location in
19203 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
19204 convert addresses to strings:
19205
19206 @smallexample @c ada
19207 with Ada.Text_IO;
19208 with GNAT.Traceback;
19209 with GNAT.Debug_Utilities;
19210
19211 procedure STB is
19212
19213    use Ada;
19214    use GNAT;
19215    use GNAT.Traceback;
19216
19217    procedure P1 is
19218       TB  : Tracebacks_Array (1 .. 10);
19219       --  We are asking for a maximum of 10 stack frames.
19220       Len : Natural;
19221       --  Len will receive the actual number of stack frames returned.
19222    begin
19223       Call_Chain (TB, Len);
19224
19225       Text_IO.Put ("In STB.P1 : ");
19226
19227       for K in 1 .. Len loop
19228          Text_IO.Put (Debug_Utilities.Image (TB (K)));
19229          Text_IO.Put (' ');
19230       end loop;
19231
19232       Text_IO.New_Line;
19233    end P1;
19234
19235    procedure P2 is
19236    begin
19237       P1;
19238    end P2;
19239
19240 begin
19241    P2;
19242 end STB;
19243 @end smallexample
19244
19245 @smallexample
19246 $ gnatmake -g stb
19247 $ stb
19248
19249 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
19250 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
19251 @end smallexample
19252
19253 @noindent
19254 You can then get further information by invoking the @code{addr2line}
19255 tool as described earlier (note that the hexadecimal addresses
19256 need to be specified in C format, with a leading ``0x'').
19257
19258 @node Symbolic Traceback
19259 @subsection Symbolic Traceback
19260 @cindex traceback, symbolic
19261
19262 @noindent
19263 A symbolic traceback is a stack traceback in which procedure names are
19264 associated with each code location.
19265
19266 @noindent
19267 Note that this feature is not supported on all platforms. See
19268 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
19269 list of currently supported platforms.
19270
19271 @noindent
19272 Note that the symbolic traceback requires that the program be compiled
19273 with debug information. If it is not compiled with debug information
19274 only the non-symbolic information will be valid.
19275
19276 @menu
19277 * Tracebacks From Exception Occurrences (symbolic)::
19278 * Tracebacks From Anywhere in a Program (symbolic)::
19279 @end menu
19280
19281 @node Tracebacks From Exception Occurrences (symbolic)
19282 @subsubsection Tracebacks From Exception Occurrences
19283
19284 @smallexample @c ada
19285 with Ada.Text_IO;
19286 with GNAT.Traceback.Symbolic;
19287
19288 procedure STB is
19289
19290    procedure P1 is
19291    begin
19292       raise Constraint_Error;
19293    end P1;
19294
19295    procedure P2 is
19296    begin
19297       P1;
19298    end P2;
19299
19300    procedure P3 is
19301    begin
19302       P2;
19303    end P3;
19304
19305 begin
19306    P3;
19307 exception
19308    when E : others =>
19309       Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
19310 end STB;
19311 @end smallexample
19312
19313 @smallexample
19314 $ gnatmake -g .\stb -bargs -E -largs -lgnat -laddr2line -lintl
19315 $ stb
19316
19317 0040149F in stb.p1 at stb.adb:8
19318 004014B7 in stb.p2 at stb.adb:13
19319 004014CF in stb.p3 at stb.adb:18
19320 004015DD in ada.stb at stb.adb:22
19321 00401461 in main at b~stb.adb:168
19322 004011C4 in __mingw_CRTStartup at crt1.c:200
19323 004011F1 in mainCRTStartup at crt1.c:222
19324 77E892A4 in ?? at ??:0
19325 @end smallexample
19326
19327 @noindent
19328 In the above example the ``.\'' syntax in the @command{gnatmake} command
19329 is currently required by @command{addr2line} for files that are in
19330 the current working directory.
19331 Moreover, the exact sequence of linker options may vary from platform
19332 to platform.
19333 The above @option{-largs} section is for Windows platforms. By contrast,
19334 under Unix there is no need for the @option{-largs} section.
19335 Differences across platforms are due to details of linker implementation.
19336
19337 @node Tracebacks From Anywhere in a Program (symbolic)
19338 @subsubsection Tracebacks From Anywhere in a Program
19339
19340 @noindent
19341 It is possible to get a symbolic stack traceback
19342 from anywhere in a program, just as for non-symbolic tracebacks.
19343 The first step is to obtain a non-symbolic
19344 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
19345 information. Here is an example:
19346
19347 @smallexample @c ada
19348 with Ada.Text_IO;
19349 with GNAT.Traceback;
19350 with GNAT.Traceback.Symbolic;
19351
19352 procedure STB is
19353
19354    use Ada;
19355    use GNAT.Traceback;
19356    use GNAT.Traceback.Symbolic;
19357
19358    procedure P1 is
19359       TB  : Tracebacks_Array (1 .. 10);
19360       --  We are asking for a maximum of 10 stack frames.
19361       Len : Natural;
19362       --  Len will receive the actual number of stack frames returned.
19363    begin
19364       Call_Chain (TB, Len);
19365       Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
19366    end P1;
19367
19368    procedure P2 is
19369    begin
19370       P1;
19371    end P2;
19372
19373 begin
19374    P2;
19375 end STB;
19376 @end smallexample
19377
19378 @c ******************************
19379 @ifset vms
19380 @node Compatibility with HP Ada
19381 @chapter Compatibility with HP Ada
19382 @cindex Compatibility
19383
19384 @noindent
19385 @cindex DEC Ada
19386 @cindex HP Ada
19387 @cindex Compatibility between GNAT and HP Ada
19388 This chapter compares HP Ada (formerly known as ``DEC Ada'')
19389 for OpenVMS Alpha and GNAT for OpenVMS for Alpha and for I64.
19390 GNAT is highly compatible
19391 with HP Ada, and it should generally be straightforward to port code
19392 from the HP Ada environment to GNAT. However, there are a few language
19393 and implementation differences of which the user must be aware. These
19394 differences are discussed in this chapter. In
19395 addition, the operating environment and command structure for the
19396 compiler are different, and these differences are also discussed.
19397
19398 For further details on these and other compatibility issues,
19399 see Appendix E of the HP publication
19400 @cite{HP Ada, Technical Overview and Comparison on HP Platforms}.
19401
19402 Except where otherwise indicated, the description of GNAT for OpenVMS
19403 applies to both the Alpha and I64 platforms.
19404
19405 For information on porting Ada code from GNAT on Alpha OpenVMS to GNAT on
19406 I64 OpenVMS, see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
19407
19408 The discussion in this chapter addresses specifically the implementation
19409 of Ada 83 for HP OpenVMS Alpha Systems. In cases where the implementation
19410 of HP Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems,
19411 GNAT always follows the Alpha implementation.
19412
19413 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
19414 attributes are recognized, although only a subset of them can sensibly
19415 be implemented.  The description of pragmas in
19416 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
19417 indicates whether or not they are applicable to non-VMS systems.
19418
19419 @menu
19420 * Ada Language Compatibility::
19421 * Differences in the Definition of Package System::
19422 * Language-Related Features::
19423 * The Package STANDARD::
19424 * The Package SYSTEM::
19425 * Tasking and Task-Related Features::
19426 * Pragmas and Pragma-Related Features::
19427 * Library of Predefined Units::
19428 * Bindings::
19429 * Main Program Definition::
19430 * Implementation-Defined Attributes::
19431 * Compiler and Run-Time Interfacing::
19432 * Program Compilation and Library Management::
19433 * Input-Output::
19434 * Implementation Limits::
19435 * Tools and Utilities::
19436 @end menu
19437
19438 @node Ada Language Compatibility
19439 @section Ada Language Compatibility
19440
19441 @noindent
19442 GNAT handles Ada 95 and Ada 2005 as well as Ada 83, whereas HP Ada is only
19443 for Ada 83. Ada 95 and Ada 2005 are almost completely upwards compatible
19444 with Ada 83, and therefore Ada 83 programs will compile
19445 and run under GNAT with
19446 no changes or only minor changes. The @cite{Annotated Ada Reference Manual}
19447 provides details on specific incompatibilities.
19448
19449 GNAT provides the switch @option{/83} on the @command{GNAT COMPILE} command,
19450 as well as the pragma @code{ADA_83}, to force the compiler to
19451 operate in Ada 83 mode. This mode does not guarantee complete
19452 conformance to Ada 83, but in practice is sufficient to
19453 eliminate most sources of incompatibilities.
19454 In particular, it eliminates the recognition of the
19455 additional Ada 95 and Ada 2005 keywords, so that their use as identifiers
19456 in Ada 83 programs is legal, and handles the cases of packages
19457 with optional bodies, and generics that instantiate unconstrained
19458 types without the use of @code{(<>)}.
19459
19460 @node Differences in the Definition of Package System
19461 @section Differences in the Definition of Package @code{System}
19462
19463 @noindent
19464 An Ada compiler is allowed to add
19465 implementation-dependent declarations to package @code{System}.
19466 In normal mode,
19467 GNAT does not take advantage of this permission, and the version of
19468 @code{System} provided by GNAT exactly matches that defined in the Ada
19469 Reference Manual.
19470
19471 However, HP Ada adds an extensive set of declarations to package
19472 @code{System},
19473 as fully documented in the HP Ada manuals. To minimize changes required
19474 for programs that make use of these extensions, GNAT provides the pragma
19475 @code{Extend_System} for extending the definition of package System. By using:
19476 @cindex pragma @code{Extend_System}
19477 @cindex @code{Extend_System} pragma
19478
19479 @smallexample @c ada
19480 @group
19481 @cartouche
19482 pragma Extend_System (Aux_DEC);
19483 @end cartouche
19484 @end group
19485 @end smallexample
19486
19487 @noindent
19488 the set of definitions in @code{System} is extended to include those in
19489 package @code{System.Aux_DEC}.
19490 @cindex @code{System.Aux_DEC} package
19491 @cindex @code{Aux_DEC} package (child of @code{System})
19492 These definitions are incorporated directly into package @code{System},
19493 as though they had been declared there. For a
19494 list of the declarations added, see the spec of this package,
19495 which can be found in the file @file{s-auxdec.ads} in the GNAT library.
19496 @cindex @file{s-auxdec.ads} file
19497 The pragma @code{Extend_System} is a configuration pragma, which means that
19498 it can be placed in the file @file{gnat.adc}, so that it will automatically
19499 apply to all subsequent compilations. See @ref{Configuration Pragmas},
19500 for further details.
19501
19502 An alternative approach that avoids the use of the non-standard
19503 @code{Extend_System} pragma is to add a context clause to the unit that
19504 references these facilities:
19505
19506 @smallexample @c ada
19507 @cartouche
19508 with System.Aux_DEC;
19509 use  System.Aux_DEC;
19510 @end cartouche
19511 @end smallexample
19512
19513 @noindent
19514 The effect is not quite semantically identical to incorporating
19515 the declarations directly into package @code{System},
19516 but most programs will not notice a difference
19517 unless they use prefix notation (e.g.@: @code{System.Integer_8})
19518 to reference the entities directly in package @code{System}.
19519 For units containing such references,
19520 the prefixes must either be removed, or the pragma @code{Extend_System}
19521 must be used.
19522
19523 @node Language-Related Features
19524 @section Language-Related Features
19525
19526 @noindent
19527 The following sections highlight differences in types,
19528 representations of types, operations, alignment, and
19529 related topics.
19530
19531 @menu
19532 * Integer Types and Representations::
19533 * Floating-Point Types and Representations::
19534 * Pragmas Float_Representation and Long_Float::
19535 * Fixed-Point Types and Representations::
19536 * Record and Array Component Alignment::
19537 * Address Clauses::
19538 * Other Representation Clauses::
19539 @end menu
19540
19541 @node Integer Types and Representations
19542 @subsection Integer Types and Representations
19543
19544 @noindent
19545 The set of predefined integer types is identical in HP Ada and GNAT.
19546 Furthermore the representation of these integer types is also identical,
19547 including the capability of size clauses forcing biased representation.
19548
19549 In addition,
19550 HP Ada for OpenVMS Alpha systems has defined the
19551 following additional integer types in package @code{System}:
19552
19553 @itemize @bullet
19554
19555 @item
19556 @code{INTEGER_8}
19557
19558 @item
19559 @code{INTEGER_16}
19560
19561 @item
19562 @code{INTEGER_32}
19563
19564 @item
19565 @code{INTEGER_64}
19566
19567 @item
19568 @code{LARGEST_INTEGER}
19569 @end itemize
19570
19571 @noindent
19572 In GNAT, the first four of these types may be obtained from the
19573 standard Ada package @code{Interfaces}.
19574 Alternatively, by use of the pragma @code{Extend_System}, identical
19575 declarations can be referenced directly in package @code{System}.
19576 On both GNAT and HP Ada, the maximum integer size is 64 bits.
19577
19578 @node Floating-Point Types and Representations
19579 @subsection Floating-Point Types and Representations
19580 @cindex Floating-Point types
19581
19582 @noindent
19583 The set of predefined floating-point types is identical in HP Ada and GNAT.
19584 Furthermore the representation of these floating-point
19585 types is also identical. One important difference is that the default
19586 representation for HP Ada is @code{VAX_Float}, but the default representation
19587 for GNAT is IEEE.
19588
19589 Specific types may be declared to be @code{VAX_Float} or IEEE, using the
19590 pragma @code{Float_Representation} as described in the HP Ada
19591 documentation.
19592 For example, the declarations:
19593
19594 @smallexample @c ada
19595 @cartouche
19596 type F_Float is digits 6;
19597 pragma Float_Representation (VAX_Float, F_Float);
19598 @end cartouche
19599 @end smallexample
19600
19601 @noindent
19602 declares a type @code{F_Float} that will be represented in @code{VAX_Float}
19603 format.
19604 This set of declarations actually appears in @code{System.Aux_DEC},
19605 which contains
19606 the full set of additional floating-point declarations provided in
19607 the HP Ada version of package @code{System}.
19608 This and similar declarations may be accessed in a user program
19609 by using pragma @code{Extend_System}. The use of this
19610 pragma, and the related pragma @code{Long_Float} is described in further
19611 detail in the following section.
19612
19613 @node Pragmas Float_Representation and Long_Float
19614 @subsection Pragmas @code{Float_Representation} and @code{Long_Float}
19615
19616 @noindent
19617 HP Ada provides the pragma @code{Float_Representation}, which
19618 acts as a program library switch to allow control over
19619 the internal representation chosen for the predefined
19620 floating-point types declared in the package @code{Standard}.
19621 The format of this pragma is as follows:
19622
19623 @smallexample @c ada
19624 @cartouche
19625 pragma Float_Representation(VAX_Float | IEEE_Float);
19626 @end cartouche
19627 @end smallexample
19628
19629 @noindent
19630 This pragma controls the representation of floating-point
19631 types as follows:
19632
19633 @itemize @bullet
19634 @item
19635 @code{VAX_Float} specifies that floating-point
19636 types are represented by default with the VAX system hardware types
19637 @code{F-floating}, @code{D-floating}, @code{G-floating}.
19638 Note that the @code{H-floating}
19639 type was available only on VAX systems, and is not available
19640 in either HP Ada or GNAT.
19641
19642 @item
19643 @code{IEEE_Float} specifies that floating-point
19644 types are represented by default with the IEEE single and
19645 double floating-point types.
19646 @end itemize
19647
19648 @noindent
19649 GNAT provides an identical implementation of the pragma
19650 @code{Float_Representation}, except that it functions as a
19651 configuration pragma. Note that the
19652 notion of configuration pragma corresponds closely to the
19653 HP Ada notion of a program library switch.
19654
19655 When no pragma is used in GNAT, the default is @code{IEEE_Float},
19656 which is different
19657 from HP Ada 83, where the default is @code{VAX_Float}. In addition, the
19658 predefined libraries in GNAT are built using @code{IEEE_Float}, so it is not
19659 advisable to change the format of numbers passed to standard library
19660 routines, and if necessary explicit type conversions may be needed.
19661
19662 The use of @code{IEEE_Float} is recommended in GNAT since it is more
19663 efficient, and (given that it conforms to an international standard)
19664 potentially more portable.
19665 The situation in which @code{VAX_Float} may be useful is in interfacing
19666 to existing code and data that expect the use of @code{VAX_Float}.
19667 In such a situation use the predefined @code{VAX_Float}
19668 types in package @code{System}, as extended by
19669 @code{Extend_System}. For example, use @code{System.F_Float}
19670 to specify the 32-bit @code{F-Float} format.
19671
19672 @noindent
19673 On OpenVMS systems, HP Ada provides the pragma @code{Long_Float}
19674 to allow control over the internal representation chosen
19675 for the predefined type @code{Long_Float} and for floating-point
19676 type declarations with digits specified in the range 7 .. 15.
19677 The format of this pragma is as follows:
19678
19679 @smallexample @c ada
19680 @cartouche
19681 pragma Long_Float (D_FLOAT | G_FLOAT);
19682 @end cartouche
19683 @end smallexample
19684
19685 @node Fixed-Point Types and Representations
19686 @subsection Fixed-Point Types and Representations
19687
19688 @noindent
19689 On HP Ada for OpenVMS Alpha systems, rounding is
19690 away from zero for both positive and negative numbers.
19691 Therefore, @code{+0.5} rounds to @code{1},
19692 and @code{-0.5} rounds to @code{-1}.
19693
19694 On GNAT the results of operations
19695 on fixed-point types are in accordance with the Ada
19696 rules. In particular, results of operations on decimal
19697 fixed-point types are truncated.
19698
19699 @node Record and Array Component Alignment
19700 @subsection Record and Array Component Alignment
19701
19702 @noindent
19703 On HP Ada for OpenVMS Alpha, all non-composite components
19704 are aligned on natural boundaries. For example, 1-byte
19705 components are aligned on byte boundaries, 2-byte
19706 components on 2-byte boundaries, 4-byte components on 4-byte
19707 byte boundaries, and so on. The OpenVMS Alpha hardware
19708 runs more efficiently with naturally aligned data.
19709
19710 On GNAT, alignment rules are compatible
19711 with HP Ada for OpenVMS Alpha.
19712
19713 @node Address Clauses
19714 @subsection Address Clauses
19715
19716 @noindent
19717 In HP Ada and GNAT, address clauses are supported for
19718 objects and imported subprograms.
19719 The predefined type @code{System.Address} is a private type
19720 in both compilers on Alpha OpenVMS, with the same representation
19721 (it is simply a machine pointer). Addition, subtraction, and comparison
19722 operations are available in the standard Ada package
19723 @code{System.Storage_Elements}, or in package @code{System}
19724 if it is extended to include @code{System.Aux_DEC} using a
19725 pragma @code{Extend_System} as previously described.
19726
19727 Note that code that @code{with}'s both this extended package @code{System}
19728 and the package @code{System.Storage_Elements} should not @code{use}
19729 both packages, or ambiguities will result. In general it is better
19730 not to mix these two sets of facilities. The Ada package was
19731 designed specifically to provide the kind of features that HP Ada
19732 adds directly to package @code{System}.
19733
19734 The type @code{System.Address} is a 64-bit integer type in GNAT for
19735 I64 OpenVMS.  For more information,
19736 see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
19737
19738 GNAT is compatible with HP Ada in its handling of address
19739 clauses, except for some limitations in
19740 the form of address clauses for composite objects with
19741 initialization. Such address clauses are easily replaced
19742 by the use of an explicitly-defined constant as described
19743 in the Ada Reference Manual (13.1(22)). For example, the sequence
19744 of declarations:
19745
19746 @smallexample @c ada
19747 @cartouche
19748 X, Y : Integer := Init_Func;
19749 Q : String (X .. Y) := "abc";
19750 @dots{}
19751 for Q'Address use Compute_Address;
19752 @end cartouche
19753 @end smallexample
19754
19755 @noindent
19756 will be rejected by GNAT, since the address cannot be computed at the time
19757 that @code{Q} is declared. To achieve the intended effect, write instead:
19758
19759 @smallexample @c ada
19760 @group
19761 @cartouche
19762 X, Y : Integer := Init_Func;
19763 Q_Address : constant Address := Compute_Address;
19764 Q : String (X .. Y) := "abc";
19765 @dots{}
19766 for Q'Address use Q_Address;
19767 @end cartouche
19768 @end group
19769 @end smallexample
19770
19771 @noindent
19772 which will be accepted by GNAT (and other Ada compilers), and is also
19773 compatible with Ada 83. A fuller description of the restrictions
19774 on address specifications is found in @ref{Top, GNAT Reference Manual,
19775 About This Guide, gnat_rm, GNAT Reference Manual}.
19776
19777 @node Other Representation Clauses
19778 @subsection Other Representation Clauses
19779
19780 @noindent
19781 GNAT implements in a compatible manner all the representation
19782 clauses supported by HP Ada. In addition, GNAT
19783 implements the representation clause forms that were introduced in Ada 95,
19784 including @code{COMPONENT_SIZE} and @code{SIZE} clauses for objects.
19785
19786 @node The Package STANDARD
19787 @section The Package @code{STANDARD}
19788
19789 @noindent
19790 The package @code{STANDARD}, as implemented by HP Ada, is fully
19791 described in the @cite{Ada Reference Manual} and in the
19792 @cite{HP Ada Language Reference Manual}. As implemented by GNAT, the
19793 package @code{STANDARD} is described in the @cite{Ada Reference Manual}.
19794
19795 In addition, HP Ada supports the Latin-1 character set in
19796 the type @code{CHARACTER}. GNAT supports the Latin-1 character set
19797 in the type @code{CHARACTER} and also Unicode (ISO 10646 BMP) in
19798 the type @code{WIDE_CHARACTER}.
19799
19800 The floating-point types supported by GNAT are those
19801 supported by HP Ada, but the defaults are different, and are controlled by
19802 pragmas. See @ref{Floating-Point Types and Representations}, for details.
19803
19804 @node The Package SYSTEM
19805 @section The Package @code{SYSTEM}
19806
19807 @noindent
19808 HP Ada provides a specific version of the package
19809 @code{SYSTEM} for each platform on which the language is implemented.
19810 For the complete spec of the package @code{SYSTEM}, see
19811 Appendix F of the @cite{HP Ada Language Reference Manual}.
19812
19813 On HP Ada, the package @code{SYSTEM} includes the following conversion
19814 functions:
19815 @itemize @bullet
19816 @item @code{TO_ADDRESS(INTEGER)}
19817
19818 @item @code{TO_ADDRESS(UNSIGNED_LONGWORD)}
19819
19820 @item @code{TO_ADDRESS(}@i{universal_integer}@code{)}
19821
19822 @item @code{TO_INTEGER(ADDRESS)}
19823
19824 @item @code{TO_UNSIGNED_LONGWORD(ADDRESS)}
19825
19826 @item Function @code{IMPORT_VALUE return UNSIGNED_LONGWORD} and the
19827 functions @code{IMPORT_ADDRESS} and @code{IMPORT_LARGEST_VALUE}
19828 @end itemize
19829
19830 @noindent
19831 By default, GNAT supplies a version of @code{SYSTEM} that matches
19832 the definition given in the @cite{Ada Reference Manual}.
19833 This
19834 is a subset of the HP system definitions, which is as
19835 close as possible to the original definitions. The only difference
19836 is that the definition of @code{SYSTEM_NAME} is different:
19837
19838 @smallexample @c ada
19839 @cartouche
19840 type Name is (SYSTEM_NAME_GNAT);
19841 System_Name : constant Name := SYSTEM_NAME_GNAT;
19842 @end cartouche
19843 @end smallexample
19844
19845 @noindent
19846 Also, GNAT adds the Ada declarations for
19847 @code{BIT_ORDER} and @code{DEFAULT_BIT_ORDER}.
19848
19849 However, the use of the following pragma causes GNAT
19850 to extend the definition of package @code{SYSTEM} so that it
19851 encompasses the full set of HP-specific extensions,
19852 including the functions listed above:
19853
19854 @smallexample @c ada
19855 @cartouche
19856 pragma Extend_System (Aux_DEC);
19857 @end cartouche
19858 @end smallexample
19859
19860 @noindent
19861 The pragma @code{Extend_System} is a configuration pragma that
19862 is most conveniently placed in the @file{gnat.adc} file. @xref{Pragma
19863 Extend_System,,, gnat_rm, GNAT Reference Manual}, for further details.
19864
19865 HP Ada does not allow the recompilation of the package
19866 @code{SYSTEM}. Instead HP Ada provides several pragmas
19867 (@code{SYSTEM_NAME}, @code{STORAGE_UNIT}, and @code{MEMORY_SIZE})
19868 to modify values in the package @code{SYSTEM}.
19869 On OpenVMS Alpha systems, the pragma
19870 @code{SYSTEM_NAME} takes the enumeration literal @code{OPENVMS_AXP} as
19871 its single argument.
19872
19873 GNAT does permit the recompilation of package @code{SYSTEM} using
19874 the special switch @option{-gnatg}, and this switch can be used if
19875 it is necessary to modify the definitions in @code{SYSTEM}. GNAT does
19876 not permit the specification of @code{SYSTEM_NAME}, @code{STORAGE_UNIT}
19877 or @code{MEMORY_SIZE} by any other means.
19878
19879 On GNAT systems, the pragma @code{SYSTEM_NAME} takes the
19880 enumeration literal @code{SYSTEM_NAME_GNAT}.
19881
19882 The definitions provided by the use of
19883
19884 @smallexample @c ada
19885 pragma Extend_System (AUX_Dec);
19886 @end smallexample
19887
19888 @noindent
19889 are virtually identical to those provided by the HP Ada 83 package
19890 @code{SYSTEM}. One important difference is that the name of the
19891 @code{TO_ADDRESS}
19892 function for type @code{UNSIGNED_LONGWORD} is changed to
19893 @code{TO_ADDRESS_LONG}.
19894 @xref{Address Clauses,,, gnat_rm, GNAT Reference Manual}, for a
19895 discussion of why this change was necessary.
19896
19897 @noindent
19898 The version of @code{TO_ADDRESS} taking a @i{universal_integer} argument
19899 is in fact
19900 an extension to Ada 83 not strictly compatible with the reference manual.
19901 GNAT, in order to be exactly compatible with the standard,
19902 does not provide this capability. In HP Ada 83, the
19903 point of this definition is to deal with a call like:
19904
19905 @smallexample @c ada
19906 TO_ADDRESS (16#12777#);
19907 @end smallexample
19908
19909 @noindent
19910 Normally, according to Ada 83 semantics, one would expect this to be
19911 ambiguous, since it matches both the @code{INTEGER} and
19912 @code{UNSIGNED_LONGWORD} forms of @code{TO_ADDRESS}.
19913 However, in HP Ada 83, there is no ambiguity, since the
19914 definition using @i{universal_integer} takes precedence.
19915
19916 In GNAT, since the version with @i{universal_integer} cannot be supplied,
19917 it is
19918 not possible to be 100% compatible. Since there are many programs using
19919 numeric constants for the argument to @code{TO_ADDRESS}, the decision in
19920 GNAT was
19921 to change the name of the function in the @code{UNSIGNED_LONGWORD} case,
19922 so the declarations provided in the GNAT version of @code{AUX_Dec} are:
19923
19924 @smallexample @c ada
19925 function To_Address (X : Integer) return Address;
19926 pragma Pure_Function (To_Address);
19927
19928 function To_Address_Long (X : Unsigned_Longword) return Address;
19929 pragma Pure_Function (To_Address_Long);
19930 @end smallexample
19931
19932 @noindent
19933 This means that programs using @code{TO_ADDRESS} for
19934 @code{UNSIGNED_LONGWORD} must change the name to @code{TO_ADDRESS_LONG}.
19935
19936 @node Tasking and Task-Related Features
19937 @section Tasking and Task-Related Features
19938
19939 @noindent
19940 This section compares the treatment of tasking in GNAT
19941 and in HP Ada for OpenVMS Alpha.
19942 The GNAT description applies to both Alpha and I64 OpenVMS.
19943 For detailed information on tasking in
19944 HP Ada, see the @cite{HP Ada Language Reference Manual} and the
19945 relevant run-time reference manual.
19946
19947 @menu
19948 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
19949 * Assigning Task IDs::
19950 * Task IDs and Delays::
19951 * Task-Related Pragmas::
19952 * Scheduling and Task Priority::
19953 * The Task Stack::
19954 * External Interrupts::
19955 @end menu
19956
19957 @node Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
19958 @subsection Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
19959
19960 @noindent
19961 On OpenVMS Alpha systems, each Ada task (except a passive
19962 task) is implemented as a single stream of execution
19963 that is created and managed by the kernel. On these
19964 systems, HP Ada tasking support is based on DECthreads,
19965 an implementation of the POSIX standard for threads.
19966
19967 Also, on OpenVMS Alpha systems, HP Ada tasks and foreign
19968 code that calls DECthreads routines can be used together.
19969 The interaction between Ada tasks and DECthreads routines
19970 can have some benefits. For example when on OpenVMS Alpha,
19971 HP Ada can call C code that is already threaded.
19972
19973 GNAT uses the facilities of DECthreads,
19974 and Ada tasks are mapped to threads.
19975
19976 @node Assigning Task IDs
19977 @subsection Assigning Task IDs
19978
19979 @noindent
19980 The HP Ada Run-Time Library always assigns @code{%TASK 1} to
19981 the environment task that executes the main program. On
19982 OpenVMS Alpha systems, @code{%TASK 0} is often used for tasks
19983 that have been created but are not yet activated.
19984
19985 On OpenVMS Alpha systems, task IDs are assigned at
19986 activation. On GNAT systems, task IDs are also assigned at
19987 task creation but do not have the same form or values as
19988 task ID values in HP Ada. There is no null task, and the
19989 environment task does not have a specific task ID value.
19990
19991 @node Task IDs and Delays
19992 @subsection Task IDs and Delays
19993
19994 @noindent
19995 On OpenVMS Alpha systems, tasking delays are implemented
19996 using Timer System Services. The Task ID is used for the
19997 identification of the timer request (the @code{REQIDT} parameter).
19998 If Timers are used in the application take care not to use
19999 @code{0} for the identification, because cancelling such a timer
20000 will cancel all timers and may lead to unpredictable results.
20001
20002 @node Task-Related Pragmas
20003 @subsection Task-Related Pragmas
20004
20005 @noindent
20006 Ada supplies the pragma @code{TASK_STORAGE}, which allows
20007 specification of the size of the guard area for a task
20008 stack. (The guard area forms an area of memory that has no
20009 read or write access and thus helps in the detection of
20010 stack overflow.) On OpenVMS Alpha systems, if the pragma
20011 @code{TASK_STORAGE} specifies a value of zero, a minimal guard
20012 area is created. In the absence of a pragma @code{TASK_STORAGE},
20013 a default guard area is created.
20014
20015 GNAT supplies the following task-related pragmas:
20016
20017 @itemize @bullet
20018 @item  @code{TASK_INFO}
20019
20020 This pragma appears within a task definition and
20021 applies to the task in which it appears. The argument
20022 must be of type @code{SYSTEM.TASK_INFO.TASK_INFO_TYPE}.
20023
20024 @item  @code{TASK_STORAGE}
20025
20026 GNAT implements pragma @code{TASK_STORAGE} in the same way as HP Ada.
20027 Both HP Ada and GNAT supply the pragmas @code{PASSIVE},
20028 @code{SUPPRESS}, and @code{VOLATILE}.
20029 @end itemize
20030 @node Scheduling and Task Priority
20031 @subsection Scheduling and Task Priority
20032
20033 @noindent
20034 HP Ada implements the Ada language requirement that
20035 when two tasks are eligible for execution and they have
20036 different priorities, the lower priority task does not
20037 execute while the higher priority task is waiting. The HP
20038 Ada Run-Time Library keeps a task running until either the
20039 task is suspended or a higher priority task becomes ready.
20040
20041 On OpenVMS Alpha systems, the default strategy is round-
20042 robin with preemption. Tasks of equal priority take turns
20043 at the processor. A task is run for a certain period of
20044 time and then placed at the tail of the ready queue for
20045 its priority level.
20046
20047 HP Ada provides the implementation-defined pragma @code{TIME_SLICE},
20048 which can be used to enable or disable round-robin
20049 scheduling of tasks with the same priority.
20050 See the relevant HP Ada run-time reference manual for
20051 information on using the pragmas to control HP Ada task
20052 scheduling.
20053
20054 GNAT follows the scheduling rules of Annex D (Real-Time
20055 Annex) of the @cite{Ada Reference Manual}. In general, this
20056 scheduling strategy is fully compatible with HP Ada
20057 although it provides some additional constraints (as
20058 fully documented in Annex D).
20059 GNAT implements time slicing control in a manner compatible with
20060 HP Ada 83, by means of the pragma @code{Time_Slice}, whose semantics
20061 are identical to the HP Ada 83 pragma of the same name.
20062 Note that it is not possible to mix GNAT tasking and
20063 HP Ada 83 tasking in the same program, since the two run-time
20064 libraries are not compatible.
20065
20066 @node The Task Stack
20067 @subsection The Task Stack
20068
20069 @noindent
20070 In HP Ada, a task stack is allocated each time a
20071 non-passive task is activated. As soon as the task is
20072 terminated, the storage for the task stack is deallocated.
20073 If you specify a size of zero (bytes) with @code{T'STORAGE_SIZE},
20074 a default stack size is used. Also, regardless of the size
20075 specified, some additional space is allocated for task
20076 management purposes. On OpenVMS Alpha systems, at least
20077 one page is allocated.
20078
20079 GNAT handles task stacks in a similar manner. In accordance with
20080 the Ada rules, it provides the pragma @code{STORAGE_SIZE} as
20081 an alternative method for controlling the task stack size.
20082 The specification of the attribute @code{T'STORAGE_SIZE} is also
20083 supported in a manner compatible with HP Ada.
20084
20085 @node External Interrupts
20086 @subsection External Interrupts
20087
20088 @noindent
20089 On HP Ada, external interrupts can be associated with task entries.
20090 GNAT is compatible with HP Ada in its handling of external interrupts.
20091
20092 @node Pragmas and Pragma-Related Features
20093 @section Pragmas and Pragma-Related Features
20094
20095 @noindent
20096 Both HP Ada and GNAT supply all language-defined pragmas
20097 as specified by the Ada 83 standard. GNAT also supplies all
20098 language-defined pragmas introduced by Ada 95 and Ada 2005.
20099 In addition, GNAT implements the implementation-defined pragmas
20100 from HP Ada 83.
20101
20102 @itemize @bullet
20103 @item  @code{AST_ENTRY}
20104
20105 @item  @code{COMMON_OBJECT}
20106
20107 @item  @code{COMPONENT_ALIGNMENT}
20108
20109 @item  @code{EXPORT_EXCEPTION}
20110
20111 @item  @code{EXPORT_FUNCTION}
20112
20113 @item  @code{EXPORT_OBJECT}
20114
20115 @item  @code{EXPORT_PROCEDURE}
20116
20117 @item  @code{EXPORT_VALUED_PROCEDURE}
20118
20119 @item  @code{FLOAT_REPRESENTATION}
20120
20121 @item  @code{IDENT}
20122
20123 @item  @code{IMPORT_EXCEPTION}
20124
20125 @item  @code{IMPORT_FUNCTION}
20126
20127 @item  @code{IMPORT_OBJECT}
20128
20129 @item  @code{IMPORT_PROCEDURE}
20130
20131 @item  @code{IMPORT_VALUED_PROCEDURE}
20132
20133 @item  @code{INLINE_GENERIC}
20134
20135 @item  @code{INTERFACE_NAME}
20136
20137 @item  @code{LONG_FLOAT}
20138
20139 @item  @code{MAIN_STORAGE}
20140
20141 @item  @code{PASSIVE}
20142
20143 @item  @code{PSECT_OBJECT}
20144
20145 @item  @code{SHARE_GENERIC}
20146
20147 @item  @code{SUPPRESS_ALL}
20148
20149 @item  @code{TASK_STORAGE}
20150
20151 @item  @code{TIME_SLICE}
20152
20153 @item  @code{TITLE}
20154 @end itemize
20155
20156 @noindent
20157 These pragmas are all fully implemented, with the exception of @code{TITLE},
20158 @code{PASSIVE}, and @code{SHARE_GENERIC}, which are
20159 recognized, but which have no
20160 effect in GNAT. The effect of @code{PASSIVE} may be obtained by the
20161 use of Ada protected objects. In GNAT, all generics are inlined.
20162
20163 Unlike HP Ada, the GNAT ``@code{EXPORT_}@i{subprogram}'' pragmas require
20164 a separate subprogram specification which must appear before the
20165 subprogram body.
20166
20167 GNAT also supplies a number of implementation-defined pragmas including the
20168 following:
20169
20170 @itemize @bullet
20171 @item  @code{ABORT_DEFER}
20172
20173 @item  @code{ADA_83}
20174
20175 @item  @code{ADA_95}
20176
20177 @item  @code{ADA_05}
20178
20179 @item  @code{Ada_2005}
20180
20181 @item  @code{Ada_12}
20182
20183 @item  @code{Ada_2012}
20184
20185 @item  @code{ANNOTATE}
20186
20187 @item  @code{ASSERT}
20188
20189 @item  @code{C_PASS_BY_COPY}
20190
20191 @item  @code{CPP_CLASS}
20192
20193 @item  @code{CPP_CONSTRUCTOR}
20194
20195 @item  @code{CPP_DESTRUCTOR}
20196
20197 @item  @code{DEBUG}
20198
20199 @item  @code{EXTEND_SYSTEM}
20200
20201 @item  @code{LINKER_ALIAS}
20202
20203 @item  @code{LINKER_SECTION}
20204
20205 @item  @code{MACHINE_ATTRIBUTE}
20206
20207 @item  @code{NO_RETURN}
20208
20209 @item  @code{PURE_FUNCTION}
20210
20211 @item  @code{SOURCE_FILE_NAME}
20212
20213 @item  @code{SOURCE_REFERENCE}
20214
20215 @item  @code{TASK_INFO}
20216
20217 @item  @code{UNCHECKED_UNION}
20218
20219 @item  @code{UNIMPLEMENTED_UNIT}
20220
20221 @item  @code{UNIVERSAL_DATA}
20222
20223 @item  @code{UNSUPPRESS}
20224
20225 @item  @code{WARNINGS}
20226
20227 @item  @code{WEAK_EXTERNAL}
20228 @end itemize
20229
20230 @noindent
20231 For full details on these and other GNAT implementation-defined pragmas,
20232 see @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference
20233 Manual}.
20234
20235 @menu
20236 * Restrictions on the Pragma INLINE::
20237 * Restrictions on the Pragma INTERFACE::
20238 * Restrictions on the Pragma SYSTEM_NAME::
20239 @end menu
20240
20241 @node Restrictions on the Pragma INLINE
20242 @subsection Restrictions on Pragma @code{INLINE}
20243
20244 @noindent
20245 HP Ada enforces the following restrictions on the pragma @code{INLINE}:
20246 @itemize @bullet
20247 @item  Parameters cannot have a task type.
20248
20249 @item  Function results cannot be task types, unconstrained
20250 array types, or unconstrained types with discriminants.
20251
20252 @item  Bodies cannot declare the following:
20253 @itemize @bullet
20254 @item  Subprogram body or stub (imported subprogram is allowed)
20255
20256 @item  Tasks
20257
20258 @item  Generic declarations
20259
20260 @item  Instantiations
20261
20262 @item  Exceptions
20263
20264 @item  Access types (types derived from access types allowed)
20265
20266 @item  Array or record types
20267
20268 @item  Dependent tasks
20269
20270 @item  Direct recursive calls of subprogram or containing
20271 subprogram, directly or via a renaming
20272
20273 @end itemize
20274 @end itemize
20275
20276 @noindent
20277 In GNAT, the only restriction on pragma @code{INLINE} is that the
20278 body must occur before the call if both are in the same
20279 unit, and the size must be appropriately small. There are
20280 no other specific restrictions which cause subprograms to
20281 be incapable of being inlined.
20282
20283 @node  Restrictions on the Pragma INTERFACE
20284 @subsection  Restrictions on Pragma @code{INTERFACE}
20285
20286 @noindent
20287 The following restrictions on pragma @code{INTERFACE}
20288 are enforced by both HP Ada and GNAT:
20289 @itemize @bullet
20290 @item  Languages accepted: Ada, Bliss, C, Fortran, Default.
20291 Default is the default on OpenVMS Alpha systems.
20292
20293 @item  Parameter passing: Language specifies default
20294 mechanisms but can be overridden with an @code{EXPORT} pragma.
20295
20296 @itemize @bullet
20297 @item  Ada: Use internal Ada rules.
20298
20299 @item  Bliss, C: Parameters must be mode @code{in}; cannot be
20300 record or task type. Result cannot be a string, an
20301 array, or a record.
20302
20303 @item  Fortran: Parameters cannot have a task type. Result cannot
20304 be a string, an array, or a record.
20305 @end itemize
20306 @end itemize
20307
20308 @noindent
20309 GNAT is entirely upwards compatible with HP Ada, and in addition allows
20310 record parameters for all languages.
20311
20312 @node  Restrictions on the Pragma SYSTEM_NAME
20313 @subsection  Restrictions on Pragma @code{SYSTEM_NAME}
20314
20315 @noindent
20316 For HP Ada for OpenVMS Alpha, the enumeration literal
20317 for the type @code{NAME} is @code{OPENVMS_AXP}.
20318 In GNAT, the enumeration
20319 literal for the type @code{NAME} is @code{SYSTEM_NAME_GNAT}.
20320
20321 @node  Library of Predefined Units
20322 @section  Library of Predefined Units
20323
20324 @noindent
20325 A library of predefined units is provided as part of the
20326 HP Ada and GNAT implementations. HP Ada does not provide
20327 the package @code{MACHINE_CODE} but instead recommends importing
20328 assembler code.
20329
20330 The GNAT versions of the HP Ada Run-Time Library (@code{ADA$PREDEFINED:})
20331 units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
20332 version.
20333 The HP Ada Predefined Library units are modified to remove post-Ada 83
20334 incompatibilities and to make them interoperable with GNAT
20335 (@pxref{Changes to DECLIB}, for details).
20336 The units are located in the @file{DECLIB} directory.
20337
20338 The GNAT RTL is contained in
20339 the @file{ADALIB} directory, and
20340 the default search path is set up to find @code{DECLIB} units in preference
20341 to @code{ADALIB} units with the same name (@code{TEXT_IO},
20342 @code{SEQUENTIAL_IO}, and @code{DIRECT_IO}, for example).
20343
20344 @menu
20345 * Changes to DECLIB::
20346 @end menu
20347
20348 @node Changes to DECLIB
20349 @subsection Changes to @code{DECLIB}
20350
20351 @noindent
20352 The changes made to the HP Ada predefined library for GNAT and post-Ada 83
20353 compatibility are minor and include the following:
20354
20355 @itemize @bullet
20356 @item  Adjusting the location of pragmas and record representation
20357 clauses to obey Ada 95 (and thus Ada 2005) rules
20358
20359 @item  Adding the proper notation to generic formal parameters
20360 that take unconstrained types in instantiation
20361
20362 @item  Adding pragma @code{ELABORATE_BODY} to package specs
20363 that have package bodies not otherwise allowed
20364
20365 @item  Replacing occurrences of the identifier ``@code{PROTECTED}'' by
20366 ``@code{PROTECTD}''.
20367 Currently these are found only in the @code{STARLET} package spec.
20368
20369 @item Changing @code{SYSTEM.ADDRESS} to @code{SYSTEM.SHORT_ADDRESS}
20370 where the address size is constrained to 32 bits.
20371 @end itemize
20372
20373 @noindent
20374 None of the above changes is visible to users.
20375
20376 @node Bindings
20377 @section Bindings
20378
20379 @noindent
20380 On OpenVMS Alpha, HP Ada provides the following strongly-typed bindings:
20381 @itemize @bullet
20382
20383 @item  Command Language Interpreter (CLI interface)
20384
20385 @item  DECtalk Run-Time Library (DTK interface)
20386
20387 @item  Librarian utility routines (LBR interface)
20388
20389 @item  General Purpose Run-Time Library (LIB interface)
20390
20391 @item  Math Run-Time Library (MTH interface)
20392
20393 @item  National Character Set Run-Time Library (NCS interface)
20394
20395 @item  Compiled Code Support Run-Time Library (OTS interface)
20396
20397 @item  Parallel Processing Run-Time Library (PPL interface)
20398
20399 @item  Screen Management Run-Time Library (SMG interface)
20400
20401 @item  Sort Run-Time Library (SOR interface)
20402
20403 @item  String Run-Time Library (STR interface)
20404
20405 @item STARLET System Library
20406 @findex Starlet
20407
20408 @item  X Window System Version 11R4 and 11R5 (X, XLIB interface)
20409
20410 @item  X Windows Toolkit (XT interface)
20411
20412 @item  X/Motif Version 1.1.3 and 1.2 (XM interface)
20413 @end itemize
20414
20415 @noindent
20416 GNAT provides implementations of these HP bindings in the @code{DECLIB}
20417 directory, on both the Alpha and I64 OpenVMS platforms.
20418
20419 The X/Motif bindings used to build @code{DECLIB} are whatever versions are
20420 in the
20421 HP Ada @file{ADA$PREDEFINED} directory with extension @file{.ADC}.
20422 A pragma @code{Linker_Options} has been added to packages @code{Xm},
20423 @code{Xt}, and @code{X_Lib}
20424 causing the default X/Motif sharable image libraries to be linked in. This
20425 is done via options files named @file{xm.opt}, @file{xt.opt}, and
20426 @file{x_lib.opt} (also located in the @file{DECLIB} directory).
20427
20428 It may be necessary to edit these options files to update or correct the
20429 library names if, for example, the newer X/Motif bindings from
20430 @file{ADA$EXAMPLES}
20431 had been (previous to installing GNAT) copied and renamed to supersede the
20432 default @file{ADA$PREDEFINED} versions.
20433
20434 @menu
20435 * Shared Libraries and Options Files::
20436 * Interfaces to C::
20437 @end menu
20438
20439 @node Shared Libraries and Options Files
20440 @subsection Shared Libraries and Options Files
20441
20442 @noindent
20443 When using the HP Ada
20444 predefined X and Motif bindings, the linking with their sharable images is
20445 done automatically by @command{GNAT LINK}.
20446 When using other X and Motif bindings, you need
20447 to add the corresponding sharable images to the command line for
20448 @code{GNAT LINK}. When linking with shared libraries, or with
20449 @file{.OPT} files, you must
20450 also add them to the command line for @command{GNAT LINK}.
20451
20452 A shared library to be used with GNAT is built in the same way as other
20453 libraries under VMS. The VMS Link command can be used in standard fashion.
20454
20455 @node Interfaces to C
20456 @subsection Interfaces to C
20457
20458 @noindent
20459 HP Ada
20460 provides the following Ada types and operations:
20461
20462 @itemize @bullet
20463 @item C types package (@code{C_TYPES})
20464
20465 @item C strings (@code{C_TYPES.NULL_TERMINATED})
20466
20467 @item Other_types (@code{SHORT_INT})
20468 @end itemize
20469
20470 @noindent
20471 Interfacing to C with GNAT, you can use the above approach
20472 described for HP Ada or the facilities of Annex B of
20473 the @cite{Ada Reference Manual} (packages @code{INTERFACES.C},
20474 @code{INTERFACES.C.STRINGS} and @code{INTERFACES.C.POINTERS}). For more
20475 information, see @ref{Interfacing to C,,, gnat_rm, GNAT Reference Manual}.
20476
20477 The @option{-gnatF} qualifier forces default and explicit
20478 @code{External_Name} parameters in pragmas @code{Import} and @code{Export}
20479 to be uppercased for compatibility with the default behavior
20480 of HP C. The qualifier has no effect on @code{Link_Name} parameters.
20481
20482 @node Main Program Definition
20483 @section Main Program Definition
20484
20485 @noindent
20486 The following section discusses differences in the
20487 definition of main programs on HP Ada and GNAT.
20488 On HP Ada, main programs are defined to meet the
20489 following conditions:
20490 @itemize @bullet
20491 @item  Procedure with no formal parameters (returns @code{0} upon
20492 normal completion)
20493
20494 @item  Procedure with no formal parameters (returns @code{42} when
20495 an unhandled exception is raised)
20496
20497 @item  Function with no formal parameters whose returned value
20498 is of a discrete type
20499
20500 @item  Procedure with one @code{out} formal of a discrete type for
20501 which a specification of pragma @code{EXPORT_VALUED_PROCEDURE} is given.
20502
20503 @end itemize
20504
20505 @noindent
20506 When declared with the pragma @code{EXPORT_VALUED_PROCEDURE},
20507 a main function or main procedure returns a discrete
20508 value whose size is less than 64 bits (32 on VAX systems),
20509 the value is zero- or sign-extended as appropriate.
20510 On GNAT, main programs are defined as follows:
20511 @itemize @bullet
20512 @item  Must be a non-generic, parameterless subprogram that
20513 is either a procedure or function returning an Ada
20514 @code{STANDARD.INTEGER} (the predefined type)
20515
20516 @item  Cannot be a generic subprogram or an instantiation of a
20517 generic subprogram
20518 @end itemize
20519
20520 @node Implementation-Defined Attributes
20521 @section Implementation-Defined Attributes
20522
20523 @noindent
20524 GNAT provides all HP Ada implementation-defined
20525 attributes.
20526
20527 @node Compiler and Run-Time Interfacing
20528 @section Compiler and Run-Time Interfacing
20529
20530 @noindent
20531 HP Ada provides the following qualifiers to pass options to the linker
20532 (ACS LINK):
20533 @itemize @bullet
20534 @item  @option{/WAIT} and @option{/SUBMIT}
20535
20536 @item  @option{/COMMAND}
20537
20538 @item  @option{/@r{[}NO@r{]}MAP}
20539
20540 @item  @option{/OUTPUT=@var{file-spec}}
20541
20542 @item  @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
20543 @end itemize
20544
20545 @noindent
20546 To pass options to the linker, GNAT provides the following
20547 switches:
20548
20549 @itemize @bullet
20550 @item   @option{/EXECUTABLE=@var{exec-name}}
20551
20552 @item   @option{/VERBOSE}
20553
20554 @item   @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
20555 @end itemize
20556
20557 @noindent
20558 For more information on these switches, see
20559 @ref{Switches for gnatlink}.
20560 In HP Ada, the command-line switch @option{/OPTIMIZE} is available
20561 to control optimization. HP Ada also supplies the
20562 following pragmas:
20563 @itemize @bullet
20564 @item  @code{OPTIMIZE}
20565
20566 @item  @code{INLINE}
20567
20568 @item  @code{INLINE_GENERIC}
20569
20570 @item  @code{SUPPRESS_ALL}
20571
20572 @item  @code{PASSIVE}
20573 @end itemize
20574
20575 @noindent
20576 In GNAT, optimization is controlled strictly by command
20577 line parameters, as described in the corresponding section of this guide.
20578 The HP pragmas for control of optimization are
20579 recognized but ignored.
20580
20581 Note that in GNAT, the default is optimization off, whereas in HP Ada
20582 the default is that optimization is turned on.
20583
20584 @node Program Compilation and Library Management
20585 @section Program Compilation and Library Management
20586
20587 @noindent
20588 HP Ada and GNAT provide a comparable set of commands to
20589 build programs. HP Ada also provides a program library,
20590 which is a concept that does not exist on GNAT. Instead,
20591 GNAT provides directories of sources that are compiled as
20592 needed.
20593
20594 The following table summarizes
20595 the HP Ada commands and provides
20596 equivalent GNAT commands. In this table, some GNAT
20597 equivalents reflect the fact that GNAT does not use the
20598 concept of a program library. Instead, it uses a model
20599 in which collections of source and object files are used
20600 in a manner consistent with other languages like C and
20601 Fortran. Therefore, standard system file commands are used
20602 to manipulate these elements. Those GNAT commands are marked with
20603 an asterisk.
20604 Note that, unlike HP Ada, none of the GNAT commands accepts wild cards.
20605
20606 @need 1500
20607 @multitable @columnfractions .35 .65
20608
20609 @item @emph{HP Ada Command}
20610 @tab @emph{GNAT Equivalent / Description}
20611
20612 @item @command{ADA}
20613 @tab @command{GNAT COMPILE}@*
20614 Invokes the compiler to compile one or more Ada source files.
20615
20616 @item @command{ACS ATTACH}@*
20617 @tab [No equivalent]@*
20618 Switches control of terminal from current process running the program
20619 library manager.
20620
20621 @item @command{ACS CHECK}
20622 @tab @command{GNAT MAKE /DEPENDENCY_LIST}@*
20623 Forms the execution closure of one
20624 or more compiled units and checks completeness and currency.
20625
20626 @item @command{ACS COMPILE}
20627 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
20628 Forms the execution closure of one or
20629 more specified units, checks completeness and currency,
20630 identifies units that have revised source files, compiles same,
20631 and recompiles units that are or will become obsolete.
20632 Also completes incomplete generic instantiations.
20633
20634 @item @command{ACS COPY FOREIGN}
20635 @tab Copy (*)@*
20636 Copies a foreign object file into the program library as a
20637 library unit body.
20638
20639 @item @command{ACS COPY UNIT}
20640 @tab Copy (*)@*
20641 Copies a compiled unit from one program library to another.
20642
20643 @item @command{ACS CREATE LIBRARY}
20644 @tab Create /directory (*)@*
20645 Creates a program library.
20646
20647 @item @command{ACS CREATE SUBLIBRARY}
20648 @tab Create /directory (*)@*
20649 Creates a program sublibrary.
20650
20651 @item @command{ACS DELETE LIBRARY}
20652 @tab @*
20653 Deletes a program library and its contents.
20654
20655 @item @command{ACS DELETE SUBLIBRARY}
20656 @tab @*
20657 Deletes a program sublibrary and its contents.
20658
20659 @item @command{ACS DELETE UNIT}
20660 @tab Delete file (*)@*
20661 On OpenVMS systems, deletes one or more compiled units from
20662 the current program library.
20663
20664 @item @command{ACS DIRECTORY}
20665 @tab Directory (*)@*
20666 On OpenVMS systems, lists units contained in the current
20667 program library.
20668
20669 @item @command{ACS ENTER FOREIGN}
20670 @tab Copy (*)@*
20671 Allows the import of a foreign body as an Ada library
20672 spec and enters a reference to a pointer.
20673
20674 @item @command{ACS ENTER UNIT}
20675 @tab Copy (*)@*
20676 Enters a reference (pointer) from the current program library to
20677 a unit compiled into another program library.
20678
20679 @item @command{ACS EXIT}
20680 @tab [No equivalent]@*
20681 Exits from the program library manager.
20682
20683 @item @command{ACS EXPORT}
20684 @tab Copy (*)@*
20685 Creates an object file that contains system-specific object code
20686 for one or more units. With GNAT, object files can simply be copied
20687 into the desired directory.
20688
20689 @item @command{ACS EXTRACT SOURCE}
20690 @tab Copy (*)@*
20691 Allows access to the copied source file for each Ada compilation unit
20692
20693 @item @command{ACS HELP}
20694 @tab @command{HELP GNAT}@*
20695 Provides online help.
20696
20697 @item @command{ACS LINK}
20698 @tab @command{GNAT LINK}@*
20699 Links an object file containing Ada units into an executable file.
20700
20701 @item @command{ACS LOAD}
20702 @tab Copy (*)@*
20703 Loads (partially compiles) Ada units into the program library.
20704 Allows loading a program from a collection of files into a library
20705 without knowing the relationship among units.
20706
20707 @item @command{ACS MERGE}
20708 @tab Copy (*)@*
20709 Merges into the current program library, one or more units from
20710 another library where they were modified.
20711
20712 @item @command{ACS RECOMPILE}
20713 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
20714 Recompiles from   external or copied source files any obsolete
20715 unit in the closure. Also, completes any incomplete generic
20716 instantiations.
20717
20718 @item @command{ACS REENTER}
20719 @tab @command{GNAT MAKE}@*
20720 Reenters current references to units compiled after last entered
20721 with the @command{ACS ENTER UNIT} command.
20722
20723 @item @command{ACS SET LIBRARY}
20724 @tab Set default (*)@*
20725 Defines a program library to be the compilation context as well
20726 as the target library for compiler output and commands in general.
20727
20728 @item @command{ACS SET PRAGMA}
20729 @tab Edit @file{gnat.adc} (*)@*
20730 Redefines specified  values of the library characteristics
20731 @code{LONG_ FLOAT}, @code{MEMORY_SIZE}, @code{SYSTEM_NAME},
20732 and @code{Float_Representation}.
20733
20734 @item @command{ACS SET SOURCE}
20735 @tab Define @code{ADA_INCLUDE_PATH} path (*)@*
20736 Defines the source file search list for the @command{ACS COMPILE} command.
20737
20738 @item @command{ACS SHOW LIBRARY}
20739 @tab Directory (*)@*
20740 Lists information about one or more program libraries.
20741
20742 @item @command{ACS SHOW PROGRAM}
20743 @tab [No equivalent]@*
20744 Lists information about the execution closure of one or
20745 more units in the program library.
20746
20747 @item @command{ACS SHOW SOURCE}
20748 @tab Show logical @code{ADA_INCLUDE_PATH}@*
20749 Shows the source file search used when compiling units.
20750
20751 @item @command{ACS SHOW VERSION}
20752 @tab Compile with @option{VERBOSE} option
20753 Displays the version number of the compiler and program library
20754 manager used.
20755
20756 @item @command{ACS SPAWN}
20757 @tab [No equivalent]@*
20758 Creates a subprocess of the current process (same as @command{DCL SPAWN}
20759 command).
20760
20761 @item @command{ACS VERIFY}
20762 @tab [No equivalent]@*
20763 Performs a series of consistency checks on a program library to
20764 determine whether the library structure and library files are in
20765 valid form.
20766 @end multitable
20767
20768 @noindent
20769
20770 @node Input-Output
20771 @section Input-Output
20772
20773 @noindent
20774 On OpenVMS Alpha systems, HP Ada uses OpenVMS Record
20775 Management Services (RMS) to perform operations on
20776 external files.
20777
20778 @noindent
20779 HP Ada and GNAT predefine an identical set of input-
20780 output packages. To make the use of the
20781 generic @code{TEXT_IO} operations more convenient, HP Ada
20782 provides predefined library packages that instantiate the
20783 integer and floating-point operations for the predefined
20784 integer and floating-point types as shown in the following table.
20785
20786 @multitable @columnfractions .45 .55
20787 @item @emph{Package Name} @tab Instantiation
20788
20789 @item @code{INTEGER_TEXT_IO}
20790 @tab @code{INTEGER_IO(INTEGER)}
20791
20792 @item @code{SHORT_INTEGER_TEXT_IO}
20793 @tab @code{INTEGER_IO(SHORT_INTEGER)}
20794
20795 @item @code{SHORT_SHORT_INTEGER_TEXT_IO}
20796 @tab @code{INTEGER_IO(SHORT_SHORT_INTEGER)}
20797
20798 @item @code{FLOAT_TEXT_IO}
20799 @tab @code{FLOAT_IO(FLOAT)}
20800
20801 @item @code{LONG_FLOAT_TEXT_IO}
20802 @tab @code{FLOAT_IO(LONG_FLOAT)}
20803 @end multitable
20804
20805 @noindent
20806 The HP Ada predefined packages and their operations
20807 are implemented using OpenVMS Alpha files and input-output
20808 facilities. HP Ada supports asynchronous input-output on OpenVMS Alpha.
20809 Familiarity with the following is recommended:
20810 @itemize @bullet
20811 @item  RMS file organizations and access methods
20812
20813 @item  OpenVMS file specifications and directories
20814
20815 @item  OpenVMS File Definition Language (FDL)
20816 @end itemize
20817
20818 @noindent
20819 GNAT provides I/O facilities that are completely
20820 compatible with HP Ada. The distribution includes the
20821 standard HP Ada versions of all I/O packages, operating
20822 in a manner compatible with HP Ada. In particular, the
20823 following packages are by default the HP Ada (Ada 83)
20824 versions of these packages rather than the renamings
20825 suggested in Annex J of the Ada Reference Manual:
20826 @itemize @bullet
20827 @item  @code{TEXT_IO}
20828
20829 @item  @code{SEQUENTIAL_IO}
20830
20831 @item  @code{DIRECT_IO}
20832 @end itemize
20833
20834 @noindent
20835 The use of the standard child package syntax (for
20836 example, @code{ADA.TEXT_IO}) retrieves the post-Ada 83 versions of these
20837 packages.
20838 GNAT provides HP-compatible predefined instantiations
20839 of the @code{TEXT_IO} packages, and also
20840 provides the standard predefined instantiations required
20841 by the @cite{Ada Reference Manual}.
20842
20843 For further information on how GNAT interfaces to the file
20844 system or how I/O is implemented in programs written in
20845 mixed languages, see @ref{Implementation of the Standard I/O,,,
20846 gnat_rm, GNAT Reference Manual}.
20847 This chapter covers the following:
20848 @itemize @bullet
20849 @item  Standard I/O packages
20850
20851 @item  @code{FORM} strings
20852
20853 @item  @code{ADA.DIRECT_IO}
20854
20855 @item  @code{ADA.SEQUENTIAL_IO}
20856
20857 @item  @code{ADA.TEXT_IO}
20858
20859 @item  Stream pointer positioning
20860
20861 @item  Reading and writing non-regular files
20862
20863 @item  @code{GET_IMMEDIATE}
20864
20865 @item  Treating @code{TEXT_IO} files as streams
20866
20867 @item  Shared files
20868
20869 @item  Open modes
20870 @end itemize
20871
20872 @node Implementation Limits
20873 @section Implementation Limits
20874
20875 @noindent
20876 The following table lists implementation limits for HP Ada
20877 and GNAT systems.
20878 @multitable @columnfractions .60 .20 .20
20879 @sp 1
20880 @item  @emph{Compilation Parameter}
20881 @tab   @emph{HP Ada}
20882 @tab   @emph{GNAT}
20883 @sp 1
20884
20885 @item  In a subprogram or entry  declaration, maximum number of
20886 formal parameters that are of an unconstrained record type
20887 @tab   32
20888 @tab   No set limit
20889 @sp 1
20890
20891 @item  Maximum identifier length (number of characters)
20892 @tab   255
20893 @tab   32766
20894 @sp 1
20895
20896 @item  Maximum number of characters in a source line
20897 @tab   255
20898 @tab   32766
20899 @sp 1
20900
20901 @item  Maximum collection size   (number of bytes)
20902 @tab   2**31-1
20903 @tab   2**31-1
20904 @sp 1
20905
20906 @item  Maximum number of discriminants for a record type
20907 @tab   245
20908 @tab   No set limit
20909 @sp 1
20910
20911 @item  Maximum number of formal parameters in an entry or
20912 subprogram declaration
20913 @tab   246
20914 @tab    No set limit
20915 @sp 1
20916
20917 @item  Maximum number of dimensions in an array type
20918 @tab   255
20919 @tab   No set limit
20920 @sp 1
20921
20922 @item  Maximum number of library  units and subunits in a compilation.
20923 @tab   4095
20924 @tab   No set limit
20925 @sp 1
20926
20927 @item  Maximum number of library units and subunits in an execution.
20928 @tab   16383
20929 @tab   No set limit
20930 @sp 1
20931
20932 @item  Maximum number of objects declared with the pragma @code{COMMON_OBJECT}
20933 or @code{PSECT_OBJECT}
20934 @tab   32757
20935 @tab   No set limit
20936 @sp 1
20937
20938 @item  Maximum number of enumeration literals in an enumeration type
20939 definition
20940 @tab   65535
20941 @tab   No set limit
20942 @sp 1
20943
20944 @item  Maximum number of lines in a source file
20945 @tab   65534
20946 @tab   No set limit
20947 @sp 1
20948
20949 @item  Maximum number of bits in any object
20950 @tab   2**31-1
20951 @tab   2**31-1
20952 @sp 1
20953
20954 @item  Maximum size of the static portion of a stack frame (approximate)
20955 @tab   2**31-1
20956 @tab   2**31-1
20957 @end multitable
20958
20959 @node Tools and Utilities
20960 @section Tools and Utilities
20961
20962 @noindent
20963 The following table lists some of the OpenVMS development tools
20964 available for HP Ada, and the corresponding tools for
20965 use with @value{EDITION} on Alpha and I64 platforms.
20966 Aside from the debugger, all the OpenVMS tools identified are part
20967 of the DECset package.
20968
20969 @iftex
20970 @c Specify table in TeX since Texinfo does a poor job
20971 @tex
20972 \smallskip
20973 \smallskip
20974 \settabs\+Language-Sensitive Editor\quad
20975    &Product with HP Ada\quad
20976    &\cr
20977 \+\it Tool
20978    &\it Product with HP Ada
20979    & \it Product with GNAT Pro\cr
20980 \smallskip
20981 \+Code Management System
20982    &HP CMS
20983    & HP CMS\cr
20984 \smallskip
20985 \+Language-Sensitive Editor
20986    &HP LSE
20987    & emacs or HP LSE (Alpha)\cr
20988 \+
20989    &
20990    & HP LSE (I64)\cr
20991 \smallskip
20992 \+Debugger
20993    &OpenVMS Debug
20994    & gdb (Alpha),\cr
20995 \+
20996    &
20997    & OpenVMS Debug (I64)\cr
20998 \smallskip
20999 \+Source Code Analyzer /
21000    &HP SCA
21001    & GNAT XREF\cr
21002 \+Cross Referencer
21003    &
21004    &\cr
21005 \smallskip
21006 \+Test Manager
21007    &HP Digital Test
21008    & HP DTM\cr
21009 \+
21010    &Manager (DTM)
21011    &\cr
21012 \smallskip
21013 \+Performance and
21014    & HP PCA
21015    & HP PCA\cr
21016 \+Coverage Analyzer
21017    &
21018    &\cr
21019 \smallskip
21020 \+Module Management
21021    & HP MMS
21022    & Not applicable\cr
21023 \+ System
21024    &
21025    &\cr
21026 \smallskip
21027 \smallskip
21028 @end tex
21029 @end iftex
21030
21031 @ifnottex
21032 @c This is the Texinfo version of the table.  It renders poorly in pdf, hence
21033 @c the TeX version above for the printed version
21034 @flushleft
21035 @c @multitable @columnfractions .3 .4 .4
21036 @multitable {Source Code Analyzer /}{Tool with HP Ada}{Tool with GNAT Pro}
21037 @item @i{Tool}
21038 @tab @i{Tool with HP Ada}
21039 @tab @i{Tool with @value{EDITION}}
21040 @item Code Management@*System
21041 @tab HP CMS
21042 @tab HP CMS
21043 @item Language-Sensitive@*Editor
21044 @tab HP LSE
21045 @tab emacs or HP LSE (Alpha)
21046 @item
21047 @tab
21048 @tab HP LSE (I64)
21049 @item Debugger
21050 @tab OpenVMS Debug
21051 @tab gdb (Alpha),
21052 @item
21053 @tab
21054 @tab OpenVMS Debug (I64)
21055 @item Source Code Analyzer /@*Cross Referencer
21056 @tab HP SCA
21057 @tab GNAT XREF
21058 @item Test Manager
21059 @tab HP Digital Test@*Manager (DTM)
21060 @tab HP DTM
21061 @item Performance and@*Coverage Analyzer
21062 @tab HP PCA
21063 @tab HP PCA
21064 @item Module Management@*System
21065 @tab HP MMS
21066 @tab Not applicable
21067 @end multitable
21068 @end flushleft
21069 @end ifnottex
21070
21071 @end ifset
21072
21073 @c **************************************
21074 @node Platform-Specific Information for the Run-Time Libraries
21075 @appendix Platform-Specific Information for the Run-Time Libraries
21076 @cindex Tasking and threads libraries
21077 @cindex Threads libraries and tasking
21078 @cindex Run-time libraries (platform-specific information)
21079
21080 @noindent
21081 The GNAT run-time implementation may vary with respect to both the
21082 underlying threads library and the exception handling scheme.
21083 For threads support, one or more of the following are supplied:
21084 @itemize @bullet
21085 @item @b{native threads library}, a binding to the thread package from
21086 the underlying operating system
21087
21088 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
21089 POSIX thread package
21090 @end itemize
21091
21092 @noindent
21093 For exception handling, either or both of two models are supplied:
21094 @itemize @bullet
21095 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
21096 Most programs should experience a substantial speed improvement by
21097 being compiled with a ZCX run-time.
21098 This is especially true for
21099 tasking applications or applications with many exception handlers.}
21100 @cindex Zero-Cost Exceptions
21101 @cindex ZCX (Zero-Cost Exceptions)
21102 which uses binder-generated tables that
21103 are interrogated at run time to locate a handler
21104
21105 @item @b{setjmp / longjmp} (``SJLJ''),
21106 @cindex setjmp/longjmp Exception Model
21107 @cindex SJLJ (setjmp/longjmp Exception Model)
21108 which uses dynamically-set data to establish
21109 the set of handlers
21110 @end itemize
21111
21112 @noindent
21113 This appendix summarizes which combinations of threads and exception support
21114 are supplied on various GNAT platforms.
21115 It then shows how to select a particular library either
21116 permanently or temporarily,
21117 explains the properties of (and tradeoffs among) the various threads
21118 libraries, and provides some additional
21119 information about several specific platforms.
21120
21121 @menu
21122 * Summary of Run-Time Configurations::
21123 * Specifying a Run-Time Library::
21124 * Choosing the Scheduling Policy::
21125 * Solaris-Specific Considerations::
21126 * Linux-Specific Considerations::
21127 * AIX-Specific Considerations::
21128 * Irix-Specific Considerations::
21129 * RTX-Specific Considerations::
21130 * HP-UX-Specific Considerations::
21131 @end menu
21132
21133 @node Summary of Run-Time Configurations
21134 @section Summary of Run-Time Configurations
21135
21136 @multitable @columnfractions .30 .70
21137 @item @b{alpha-openvms}
21138 @item @code{@ @ }@i{rts-native (default)}
21139 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
21140 @item @code{@ @ @ @ }Exceptions @tab ZCX
21141 @*
21142 @item @b{alpha-tru64}
21143 @item @code{@ @ }@i{rts-native (default)}
21144 @item @code{@ @ @ @ }Tasking    @tab native TRU64 threads
21145 @item @code{@ @ @ @ }Exceptions @tab ZCX
21146 @*
21147 @item @code{@ @ }@i{rts-sjlj}
21148 @item @code{@ @ @ @ }Tasking    @tab native TRU64 threads
21149 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21150 @*
21151 @item @b{ia64-hp_linux}
21152 @item @code{@ @ }@i{rts-native (default)}
21153 @item @code{@ @ @ @ }Tasking    @tab pthread library
21154 @item @code{@ @ @ @ }Exceptions @tab ZCX
21155 @*
21156 @item @b{ia64-hpux}
21157 @item @code{@ @ }@i{rts-native (default)}
21158 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
21159 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21160 @*
21161 @item @b{ia64-openvms}
21162 @item @code{@ @ }@i{rts-native (default)}
21163 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
21164 @item @code{@ @ @ @ }Exceptions @tab ZCX
21165 @*
21166 @item @b{ia64-sgi_linux}
21167 @item @code{@ @ }@i{rts-native (default)}
21168 @item @code{@ @ @ @ }Tasking    @tab pthread library
21169 @item @code{@ @ @ @ }Exceptions @tab ZCX
21170 @*
21171 @item @b{mips-irix}
21172 @item @code{@ @ }@i{rts-native (default)}
21173 @item @code{@ @ @ @ }Tasking    @tab native IRIX threads
21174 @item @code{@ @ @ @ }Exceptions @tab ZCX
21175 @*
21176 @item @b{pa-hpux}
21177 @item @code{@ @ }@i{rts-native (default)}
21178 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
21179 @item @code{@ @ @ @ }Exceptions @tab ZCX
21180 @*
21181 @item @code{@ @ }@i{rts-sjlj}
21182 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
21183 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21184 @*
21185 @item @b{ppc-aix}
21186 @item @code{@ @ }@i{rts-native (default)}
21187 @item @code{@ @ @ @ }Tasking    @tab native AIX threads
21188 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21189 @*
21190 @item @b{ppc-darwin}
21191 @item @code{@ @ }@i{rts-native (default)}
21192 @item @code{@ @ @ @ }Tasking    @tab native MacOS threads
21193 @item @code{@ @ @ @ }Exceptions @tab ZCX
21194 @*
21195 @item @b{sparc-solaris}  @tab
21196 @item @code{@ @ }@i{rts-native (default)}
21197 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
21198 @item @code{@ @ @ @ }Exceptions @tab ZCX
21199 @*
21200 @item @code{@ @ }@i{rts-pthread}
21201 @item @code{@ @ @ @ }Tasking    @tab pthread library
21202 @item @code{@ @ @ @ }Exceptions @tab ZCX
21203 @*
21204 @item @code{@ @ }@i{rts-sjlj}
21205 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
21206 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21207 @*
21208 @item @b{sparc64-solaris}  @tab
21209 @item @code{@ @ }@i{rts-native (default)}
21210 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
21211 @item @code{@ @ @ @ }Exceptions @tab ZCX
21212 @*
21213 @item @b{x86-linux}
21214 @item @code{@ @ }@i{rts-native (default)}
21215 @item @code{@ @ @ @ }Tasking    @tab pthread library
21216 @item @code{@ @ @ @ }Exceptions @tab ZCX
21217 @*
21218 @item @code{@ @ }@i{rts-sjlj}
21219 @item @code{@ @ @ @ }Tasking    @tab pthread library
21220 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21221 @*
21222 @item @b{x86-lynx}
21223 @item @code{@ @ }@i{rts-native (default)}
21224 @item @code{@ @ @ @ }Tasking    @tab native LynxOS threads
21225 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21226 @*
21227 @item @b{x86-solaris}
21228 @item @code{@ @ }@i{rts-native (default)}
21229 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads
21230 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21231 @*
21232 @item @b{x86-windows}
21233 @item @code{@ @ }@i{rts-native (default)}
21234 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
21235 @item @code{@ @ @ @ }Exceptions @tab ZCX
21236 @*
21237 @item @code{@ @ }@i{rts-sjlj (default)}
21238 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
21239 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21240 @*
21241 @item @b{x86-windows-rtx}
21242 @item @code{@ @ }@i{rts-rtx-rtss (default)}
21243 @item @code{@ @ @ @ }Tasking    @tab RTX real-time subsystem RTSS threads (kernel mode)
21244 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21245 @*
21246 @item @code{@ @ }@i{rts-rtx-w32}
21247 @item @code{@ @ @ @ }Tasking    @tab RTX Win32 threads (user mode)
21248 @item @code{@ @ @ @ }Exceptions @tab ZCX
21249 @*
21250 @item @b{x86_64-linux}
21251 @item @code{@ @ }@i{rts-native (default)}
21252 @item @code{@ @ @ @ }Tasking    @tab pthread library
21253 @item @code{@ @ @ @ }Exceptions @tab ZCX
21254 @*
21255 @item @code{@ @ }@i{rts-sjlj}
21256 @item @code{@ @ @ @ }Tasking    @tab pthread library
21257 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21258 @*
21259 @end multitable
21260
21261 @node Specifying a Run-Time Library
21262 @section Specifying a Run-Time Library
21263
21264 @noindent
21265 The @file{adainclude} subdirectory containing the sources of the GNAT
21266 run-time library, and the @file{adalib} subdirectory containing the
21267 @file{ALI} files and the static and/or shared GNAT library, are located
21268 in the gcc target-dependent area:
21269
21270 @smallexample
21271 target=$prefix/lib/gcc/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
21272 @end smallexample
21273
21274 @noindent
21275 As indicated above, on some platforms several run-time libraries are supplied.
21276 These libraries are installed in the target dependent area and
21277 contain a complete source and binary subdirectory. The detailed description
21278 below explains the differences between the different libraries in terms of
21279 their thread support.
21280
21281 The default run-time library (when GNAT is installed) is @emph{rts-native}.
21282 This default run time is selected by the means of soft links.
21283 For example on x86-linux:
21284
21285 @smallexample
21286 @group
21287  $(target-dir)
21288      |
21289      +--- adainclude----------+
21290      |                        |
21291      +--- adalib-----------+  |
21292      |                     |  |
21293      +--- rts-native       |  |
21294      |    |                |  |
21295      |    +--- adainclude <---+
21296      |    |                |
21297      |    +--- adalib <----+
21298      |
21299      +--- rts-sjlj
21300           |
21301           +--- adainclude
21302           |
21303           +--- adalib
21304 @end group
21305 @end smallexample
21306
21307 @noindent
21308 If the @i{rts-sjlj} library is to be selected on a permanent basis,
21309 these soft links can be modified with the following commands:
21310
21311 @smallexample
21312 $ cd $target
21313 $ rm -f adainclude adalib
21314 $ ln -s rts-sjlj/adainclude adainclude
21315 $ ln -s rts-sjlj/adalib adalib
21316 @end smallexample
21317
21318 @noindent
21319 Alternatively, you can specify @file{rts-sjlj/adainclude} in the file
21320 @file{$target/ada_source_path} and @file{rts-sjlj/adalib} in
21321 @file{$target/ada_object_path}.
21322
21323 Selecting another run-time library temporarily can be
21324 achieved by using the @option{--RTS} switch, e.g., @option{--RTS=sjlj}
21325 @cindex @option{--RTS} option
21326
21327 @node Choosing the Scheduling Policy
21328 @section Choosing the Scheduling Policy
21329
21330 @noindent
21331 When using a POSIX threads implementation, you have a choice of several
21332 scheduling policies: @code{SCHED_FIFO},
21333 @cindex @code{SCHED_FIFO} scheduling policy
21334 @code{SCHED_RR}
21335 @cindex @code{SCHED_RR} scheduling policy
21336 and @code{SCHED_OTHER}.
21337 @cindex @code{SCHED_OTHER} scheduling policy
21338 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
21339 or @code{SCHED_RR} requires special (e.g., root) privileges.
21340
21341 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
21342 @code{SCHED_FIFO},
21343 @cindex @code{SCHED_FIFO} scheduling policy
21344 you can use one of the following:
21345
21346 @itemize @bullet
21347 @item
21348 @code{pragma Time_Slice (0.0)}
21349 @cindex pragma Time_Slice
21350 @item
21351 the corresponding binder option @option{-T0}
21352 @cindex @option{-T0} option
21353 @item
21354 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
21355 @cindex pragma Task_Dispatching_Policy
21356 @end itemize
21357
21358 @noindent
21359 To specify @code{SCHED_RR},
21360 @cindex @code{SCHED_RR} scheduling policy
21361 you should use @code{pragma Time_Slice} with a
21362 value greater than @code{0.0}, or else use the corresponding @option{-T}
21363 binder option.
21364
21365 @node Solaris-Specific Considerations
21366 @section Solaris-Specific Considerations
21367 @cindex Solaris Sparc threads libraries
21368
21369 @noindent
21370 This section addresses some topics related to the various threads libraries
21371 on Sparc Solaris.
21372
21373 @menu
21374 * Solaris Threads Issues::
21375 @end menu
21376
21377 @node Solaris Threads Issues
21378 @subsection Solaris Threads Issues
21379
21380 @noindent
21381 GNAT under Solaris/Sparc 32 bits comes with an alternate tasking run-time
21382 library based on POSIX threads --- @emph{rts-pthread}.
21383 @cindex rts-pthread threads library
21384 This run-time library has the advantage of being mostly shared across all
21385 POSIX-compliant thread implementations, and it also provides under
21386 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
21387 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
21388 and @code{PTHREAD_PRIO_PROTECT}
21389 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
21390 semantics that can be selected using the predefined pragma
21391 @code{Locking_Policy}
21392 @cindex pragma Locking_Policy (under rts-pthread)
21393 with respectively
21394 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
21395 @cindex @code{Inheritance_Locking} (under rts-pthread)
21396 @cindex @code{Ceiling_Locking} (under rts-pthread)
21397
21398 As explained above, the native run-time library is based on the Solaris thread
21399 library (@code{libthread}) and is the default library.
21400
21401 When the Solaris threads library is used (this is the default), programs
21402 compiled with GNAT can automatically take advantage of
21403 and can thus execute on multiple processors.
21404 The user can alternatively specify a processor on which the program should run
21405 to emulate a single-processor system. The multiprocessor / uniprocessor choice
21406 is made by
21407 setting the environment variable @env{GNAT_PROCESSOR}
21408 @cindex @env{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
21409 to one of the following:
21410
21411 @table @code
21412 @item -2
21413 Use the default configuration (run the program on all
21414 available processors) - this is the same as having @code{GNAT_PROCESSOR}
21415 unset
21416
21417 @item -1
21418 Let the run-time implementation choose one processor and run the program on
21419 that processor
21420
21421 @item 0 .. Last_Proc
21422 Run the program on the specified processor.
21423 @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
21424 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
21425 @end table
21426
21427 @node Linux-Specific Considerations
21428 @section Linux-Specific Considerations
21429 @cindex Linux threads libraries
21430
21431 @noindent
21432 On GNU/Linux without NPTL support (usually system with GNU C Library
21433 older than 2.3), the signal model is not POSIX compliant, which means
21434 that to send a signal to the process, you need to send the signal to all
21435 threads, e.g.@: by using @code{killpg()}.
21436
21437 @node AIX-Specific Considerations
21438 @section AIX-Specific Considerations
21439 @cindex AIX resolver library
21440
21441 @noindent
21442 On AIX, the resolver library initializes some internal structure on
21443 the first call to @code{get*by*} functions, which are used to implement
21444 @code{GNAT.Sockets.Get_Host_By_Name} and
21445 @code{GNAT.Sockets.Get_Host_By_Address}.
21446 If such initialization occurs within an Ada task, and the stack size for
21447 the task is the default size, a stack overflow may occur.
21448
21449 To avoid this overflow, the user should either ensure that the first call
21450 to @code{GNAT.Sockets.Get_Host_By_Name} or
21451 @code{GNAT.Sockets.Get_Host_By_Addrss}
21452 occurs in the environment task, or use @code{pragma Storage_Size} to
21453 specify a sufficiently large size for the stack of the task that contains
21454 this call.
21455
21456 @node Irix-Specific Considerations
21457 @section Irix-Specific Considerations
21458 @cindex Irix libraries
21459
21460 @noindent
21461 The GCC support libraries coming with the Irix compiler have moved to
21462 their canonical place with respect to the general Irix ABI related
21463 conventions. Running applications built with the default shared GNAT
21464 run-time now requires the LD_LIBRARY_PATH environment variable to
21465 include this location. A possible way to achieve this is to issue the
21466 following command line on a bash prompt:
21467
21468 @smallexample
21469 @group
21470 $  LD_LIBRARY_PATH=$LD_LIBRARY_PATH:`dirname \`gcc --print-file-name=libgcc_s.so\``
21471 @end group
21472 @end smallexample
21473
21474 @node RTX-Specific Considerations
21475 @section RTX-Specific Considerations
21476 @cindex RTX libraries
21477
21478 @noindent
21479 The Real-time Extension (RTX) to Windows is based on the Windows Win32
21480 API. Applications can be built to work in two different modes:
21481
21482 @itemize @bullet
21483 @item
21484 Windows executables that run in Ring 3 to utilize memory protection
21485 (@emph{rts-rtx-w32}).
21486
21487 @item
21488 Real-time subsystem (RTSS) executables that run in Ring 0, where
21489 performance can be optimized with RTSS applications taking precedent
21490 over all Windows applications (@emph{rts-rtx-rtss}). This mode requires
21491 the Microsoft linker to handle RTSS libraries.
21492
21493 @end itemize
21494
21495 @node HP-UX-Specific Considerations
21496 @section HP-UX-Specific Considerations
21497 @cindex HP-UX Scheduling
21498
21499 @noindent
21500 On HP-UX, appropriate privileges are required to change the scheduling
21501 parameters of a task. The calling process must have appropriate
21502 privileges or be a member of a group having @code{PRIV_RTSCHED} access to
21503 successfully change the scheduling parameters.
21504
21505 By default, GNAT uses the @code{SCHED_HPUX} policy. To have access to the
21506 priority range 0-31 either the @code{FIFO_Within_Priorities} or the
21507 @code{Round_Robin_Within_Priorities} scheduling policies need to be set.
21508
21509 To specify the @code{FIFO_Within_Priorities} scheduling policy you can use
21510 one of the following:
21511
21512 @itemize @bullet
21513 @item
21514 @code{pragma Time_Slice (0.0)}
21515 @cindex pragma Time_Slice
21516 @item
21517 the corresponding binder option @option{-T0}
21518 @cindex @option{-T0} option
21519 @item
21520 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
21521 @cindex pragma Task_Dispatching_Policy
21522 @end itemize
21523
21524 @noindent
21525 To specify the @code{Round_Robin_Within_Priorities}, scheduling policy
21526 you should use @code{pragma Time_Slice} with a
21527 value greater than @code{0.0}, or use the corresponding @option{-T}
21528 binder option, or set the @code{pragma Task_Dispatching_Policy
21529 (Round_Robin_Within_Priorities)}.
21530
21531 @c *******************************
21532 @node Example of Binder Output File
21533 @appendix Example of Binder Output File
21534
21535 @noindent
21536 This Appendix displays the source code for @command{gnatbind}'s output
21537 file generated for a simple ``Hello World'' program.
21538 Comments have been added for clarification purposes.
21539
21540 @smallexample @c adanocomment
21541 @iftex
21542 @leftskip=0cm
21543 @end iftex
21544 --  The package is called Ada_Main unless this name is actually used
21545 --  as a unit name in the partition, in which case some other unique
21546 --  name is used.
21547
21548 with System;
21549 package ada_main is
21550
21551    Elab_Final_Code : Integer;
21552    pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
21553
21554    --  The main program saves the parameters (argument count,
21555    --  argument values, environment pointer) in global variables
21556    --  for later access by other units including
21557    --  Ada.Command_Line.
21558
21559    gnat_argc : Integer;
21560    gnat_argv : System.Address;
21561    gnat_envp : System.Address;
21562
21563    --  The actual variables are stored in a library routine. This
21564    --  is useful for some shared library situations, where there
21565    --  are problems if variables are not in the library.
21566
21567    pragma Import (C, gnat_argc);
21568    pragma Import (C, gnat_argv);
21569    pragma Import (C, gnat_envp);
21570
21571    --  The exit status is similarly an external location
21572
21573    gnat_exit_status : Integer;
21574    pragma Import (C, gnat_exit_status);
21575
21576    GNAT_Version : constant String :=
21577                     "GNAT Version: 6.0.0w (20061115)";
21578    pragma Export (C, GNAT_Version, "__gnat_version");
21579
21580    --  This is the generated adafinal routine that performs
21581    --  finalization at the end of execution. In the case where
21582    --  Ada is the main program, this main program makes a call
21583    --  to adafinal at program termination.
21584
21585    procedure adafinal;
21586    pragma Export (C, adafinal, "adafinal");
21587
21588    --  This is the generated adainit routine that performs
21589    --  initialization at the start of execution. In the case
21590    --  where Ada is the main program, this main program makes
21591    --  a call to adainit at program startup.
21592
21593    procedure adainit;
21594    pragma Export (C, adainit, "adainit");
21595
21596    --  This routine is called at the start of execution. It is
21597    --  a dummy routine that is used by the debugger to breakpoint
21598    --  at the start of execution.
21599
21600    procedure Break_Start;
21601    pragma Import (C, Break_Start, "__gnat_break_start");
21602
21603    --  This is the actual generated main program (it would be
21604    --  suppressed if the no main program switch were used). As
21605    --  required by standard system conventions, this program has
21606    --  the external name main.
21607
21608    function main
21609      (argc : Integer;
21610       argv : System.Address;
21611       envp : System.Address)
21612       return Integer;
21613    pragma Export (C, main, "main");
21614
21615    --  The following set of constants give the version
21616    --  identification values for every unit in the bound
21617    --  partition. This identification is computed from all
21618    --  dependent semantic units, and corresponds to the
21619    --  string that would be returned by use of the
21620    --  Body_Version or Version attributes.
21621
21622    type Version_32 is mod 2 ** 32;
21623    u00001 : constant Version_32 := 16#7880BEB3#;
21624    u00002 : constant Version_32 := 16#0D24CBD0#;
21625    u00003 : constant Version_32 := 16#3283DBEB#;
21626    u00004 : constant Version_32 := 16#2359F9ED#;
21627    u00005 : constant Version_32 := 16#664FB847#;
21628    u00006 : constant Version_32 := 16#68E803DF#;
21629    u00007 : constant Version_32 := 16#5572E604#;
21630    u00008 : constant Version_32 := 16#46B173D8#;
21631    u00009 : constant Version_32 := 16#156A40CF#;
21632    u00010 : constant Version_32 := 16#033DABE0#;
21633    u00011 : constant Version_32 := 16#6AB38FEA#;
21634    u00012 : constant Version_32 := 16#22B6217D#;
21635    u00013 : constant Version_32 := 16#68A22947#;
21636    u00014 : constant Version_32 := 16#18CC4A56#;
21637    u00015 : constant Version_32 := 16#08258E1B#;
21638    u00016 : constant Version_32 := 16#367D5222#;
21639    u00017 : constant Version_32 := 16#20C9ECA4#;
21640    u00018 : constant Version_32 := 16#50D32CB6#;
21641    u00019 : constant Version_32 := 16#39A8BB77#;
21642    u00020 : constant Version_32 := 16#5CF8FA2B#;
21643    u00021 : constant Version_32 := 16#2F1EB794#;
21644    u00022 : constant Version_32 := 16#31AB6444#;
21645    u00023 : constant Version_32 := 16#1574B6E9#;
21646    u00024 : constant Version_32 := 16#5109C189#;
21647    u00025 : constant Version_32 := 16#56D770CD#;
21648    u00026 : constant Version_32 := 16#02F9DE3D#;
21649    u00027 : constant Version_32 := 16#08AB6B2C#;
21650    u00028 : constant Version_32 := 16#3FA37670#;
21651    u00029 : constant Version_32 := 16#476457A0#;
21652    u00030 : constant Version_32 := 16#731E1B6E#;
21653    u00031 : constant Version_32 := 16#23C2E789#;
21654    u00032 : constant Version_32 := 16#0F1BD6A1#;
21655    u00033 : constant Version_32 := 16#7C25DE96#;
21656    u00034 : constant Version_32 := 16#39ADFFA2#;
21657    u00035 : constant Version_32 := 16#571DE3E7#;
21658    u00036 : constant Version_32 := 16#5EB646AB#;
21659    u00037 : constant Version_32 := 16#4249379B#;
21660    u00038 : constant Version_32 := 16#0357E00A#;
21661    u00039 : constant Version_32 := 16#3784FB72#;
21662    u00040 : constant Version_32 := 16#2E723019#;
21663    u00041 : constant Version_32 := 16#623358EA#;
21664    u00042 : constant Version_32 := 16#107F9465#;
21665    u00043 : constant Version_32 := 16#6843F68A#;
21666    u00044 : constant Version_32 := 16#63305874#;
21667    u00045 : constant Version_32 := 16#31E56CE1#;
21668    u00046 : constant Version_32 := 16#02917970#;
21669    u00047 : constant Version_32 := 16#6CCBA70E#;
21670    u00048 : constant Version_32 := 16#41CD4204#;
21671    u00049 : constant Version_32 := 16#572E3F58#;
21672    u00050 : constant Version_32 := 16#20729FF5#;
21673    u00051 : constant Version_32 := 16#1D4F93E8#;
21674    u00052 : constant Version_32 := 16#30B2EC3D#;
21675    u00053 : constant Version_32 := 16#34054F96#;
21676    u00054 : constant Version_32 := 16#5A199860#;
21677    u00055 : constant Version_32 := 16#0E7F912B#;
21678    u00056 : constant Version_32 := 16#5760634A#;
21679    u00057 : constant Version_32 := 16#5D851835#;
21680
21681    --  The following Export pragmas export the version numbers
21682    --  with symbolic names ending in B (for body) or S
21683    --  (for spec) so that they can be located in a link. The
21684    --  information provided here is sufficient to track down
21685    --  the exact versions of units used in a given build.
21686
21687    pragma Export (C, u00001, "helloB");
21688    pragma Export (C, u00002, "system__standard_libraryB");
21689    pragma Export (C, u00003, "system__standard_libraryS");
21690    pragma Export (C, u00004, "adaS");
21691    pragma Export (C, u00005, "ada__text_ioB");
21692    pragma Export (C, u00006, "ada__text_ioS");
21693    pragma Export (C, u00007, "ada__exceptionsB");
21694    pragma Export (C, u00008, "ada__exceptionsS");
21695    pragma Export (C, u00009, "gnatS");
21696    pragma Export (C, u00010, "gnat__heap_sort_aB");
21697    pragma Export (C, u00011, "gnat__heap_sort_aS");
21698    pragma Export (C, u00012, "systemS");
21699    pragma Export (C, u00013, "system__exception_tableB");
21700    pragma Export (C, u00014, "system__exception_tableS");
21701    pragma Export (C, u00015, "gnat__htableB");
21702    pragma Export (C, u00016, "gnat__htableS");
21703    pragma Export (C, u00017, "system__exceptionsS");
21704    pragma Export (C, u00018, "system__machine_state_operationsB");
21705    pragma Export (C, u00019, "system__machine_state_operationsS");
21706    pragma Export (C, u00020, "system__machine_codeS");
21707    pragma Export (C, u00021, "system__storage_elementsB");
21708    pragma Export (C, u00022, "system__storage_elementsS");
21709    pragma Export (C, u00023, "system__secondary_stackB");
21710    pragma Export (C, u00024, "system__secondary_stackS");
21711    pragma Export (C, u00025, "system__parametersB");
21712    pragma Export (C, u00026, "system__parametersS");
21713    pragma Export (C, u00027, "system__soft_linksB");
21714    pragma Export (C, u00028, "system__soft_linksS");
21715    pragma Export (C, u00029, "system__stack_checkingB");
21716    pragma Export (C, u00030, "system__stack_checkingS");
21717    pragma Export (C, u00031, "system__tracebackB");
21718    pragma Export (C, u00032, "system__tracebackS");
21719    pragma Export (C, u00033, "ada__streamsS");
21720    pragma Export (C, u00034, "ada__tagsB");
21721    pragma Export (C, u00035, "ada__tagsS");
21722    pragma Export (C, u00036, "system__string_opsB");
21723    pragma Export (C, u00037, "system__string_opsS");
21724    pragma Export (C, u00038, "interfacesS");
21725    pragma Export (C, u00039, "interfaces__c_streamsB");
21726    pragma Export (C, u00040, "interfaces__c_streamsS");
21727    pragma Export (C, u00041, "system__file_ioB");
21728    pragma Export (C, u00042, "system__file_ioS");
21729    pragma Export (C, u00043, "ada__finalizationB");
21730    pragma Export (C, u00044, "ada__finalizationS");
21731    pragma Export (C, u00045, "system__finalization_rootB");
21732    pragma Export (C, u00046, "system__finalization_rootS");
21733    pragma Export (C, u00047, "system__finalization_implementationB");
21734    pragma Export (C, u00048, "system__finalization_implementationS");
21735    pragma Export (C, u00049, "system__string_ops_concat_3B");
21736    pragma Export (C, u00050, "system__string_ops_concat_3S");
21737    pragma Export (C, u00051, "system__stream_attributesB");
21738    pragma Export (C, u00052, "system__stream_attributesS");
21739    pragma Export (C, u00053, "ada__io_exceptionsS");
21740    pragma Export (C, u00054, "system__unsigned_typesS");
21741    pragma Export (C, u00055, "system__file_control_blockS");
21742    pragma Export (C, u00056, "ada__finalization__list_controllerB");
21743    pragma Export (C, u00057, "ada__finalization__list_controllerS");
21744
21745    -- BEGIN ELABORATION ORDER
21746    -- ada (spec)
21747    -- gnat (spec)
21748    -- gnat.heap_sort_a (spec)
21749    -- gnat.heap_sort_a (body)
21750    -- gnat.htable (spec)
21751    -- gnat.htable (body)
21752    -- interfaces (spec)
21753    -- system (spec)
21754    -- system.machine_code (spec)
21755    -- system.parameters (spec)
21756    -- system.parameters (body)
21757    -- interfaces.c_streams (spec)
21758    -- interfaces.c_streams (body)
21759    -- system.standard_library (spec)
21760    -- ada.exceptions (spec)
21761    -- system.exception_table (spec)
21762    -- system.exception_table (body)
21763    -- ada.io_exceptions (spec)
21764    -- system.exceptions (spec)
21765    -- system.storage_elements (spec)
21766    -- system.storage_elements (body)
21767    -- system.machine_state_operations (spec)
21768    -- system.machine_state_operations (body)
21769    -- system.secondary_stack (spec)
21770    -- system.stack_checking (spec)
21771    -- system.soft_links (spec)
21772    -- system.soft_links (body)
21773    -- system.stack_checking (body)
21774    -- system.secondary_stack (body)
21775    -- system.standard_library (body)
21776    -- system.string_ops (spec)
21777    -- system.string_ops (body)
21778    -- ada.tags (spec)
21779    -- ada.tags (body)
21780    -- ada.streams (spec)
21781    -- system.finalization_root (spec)
21782    -- system.finalization_root (body)
21783    -- system.string_ops_concat_3 (spec)
21784    -- system.string_ops_concat_3 (body)
21785    -- system.traceback (spec)
21786    -- system.traceback (body)
21787    -- ada.exceptions (body)
21788    -- system.unsigned_types (spec)
21789    -- system.stream_attributes (spec)
21790    -- system.stream_attributes (body)
21791    -- system.finalization_implementation (spec)
21792    -- system.finalization_implementation (body)
21793    -- ada.finalization (spec)
21794    -- ada.finalization (body)
21795    -- ada.finalization.list_controller (spec)
21796    -- ada.finalization.list_controller (body)
21797    -- system.file_control_block (spec)
21798    -- system.file_io (spec)
21799    -- system.file_io (body)
21800    -- ada.text_io (spec)
21801    -- ada.text_io (body)
21802    -- hello (body)
21803    -- END ELABORATION ORDER
21804
21805 end ada_main;
21806
21807 --  The following source file name pragmas allow the generated file
21808 --  names to be unique for different main programs. They are needed
21809 --  since the package name will always be Ada_Main.
21810
21811 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
21812 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
21813
21814 --  Generated package body for Ada_Main starts here
21815
21816 package body ada_main is
21817
21818    --  The actual finalization is performed by calling the
21819    --  library routine in System.Standard_Library.Adafinal
21820
21821    procedure Do_Finalize;
21822    pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
21823
21824    -------------
21825    -- adainit --
21826    -------------
21827
21828 @findex adainit
21829    procedure adainit is
21830
21831       --  These booleans are set to True once the associated unit has
21832       --  been elaborated. It is also used to avoid elaborating the
21833       --  same unit twice.
21834
21835       E040 : Boolean;
21836       pragma Import (Ada, E040, "interfaces__c_streams_E");
21837
21838       E008 : Boolean;
21839       pragma Import (Ada, E008, "ada__exceptions_E");
21840
21841       E014 : Boolean;
21842       pragma Import (Ada, E014, "system__exception_table_E");
21843
21844       E053 : Boolean;
21845       pragma Import (Ada, E053, "ada__io_exceptions_E");
21846
21847       E017 : Boolean;
21848       pragma Import (Ada, E017, "system__exceptions_E");
21849
21850       E024 : Boolean;
21851       pragma Import (Ada, E024, "system__secondary_stack_E");
21852
21853       E030 : Boolean;
21854       pragma Import (Ada, E030, "system__stack_checking_E");
21855
21856       E028 : Boolean;
21857       pragma Import (Ada, E028, "system__soft_links_E");
21858
21859       E035 : Boolean;
21860       pragma Import (Ada, E035, "ada__tags_E");
21861
21862       E033 : Boolean;
21863       pragma Import (Ada, E033, "ada__streams_E");
21864
21865       E046 : Boolean;
21866       pragma Import (Ada, E046, "system__finalization_root_E");
21867
21868       E048 : Boolean;
21869       pragma Import (Ada, E048, "system__finalization_implementation_E");
21870
21871       E044 : Boolean;
21872       pragma Import (Ada, E044, "ada__finalization_E");
21873
21874       E057 : Boolean;
21875       pragma Import (Ada, E057, "ada__finalization__list_controller_E");
21876
21877       E055 : Boolean;
21878       pragma Import (Ada, E055, "system__file_control_block_E");
21879
21880       E042 : Boolean;
21881       pragma Import (Ada, E042, "system__file_io_E");
21882
21883       E006 : Boolean;
21884       pragma Import (Ada, E006, "ada__text_io_E");
21885
21886       --  Set_Globals is a library routine that stores away the
21887       --  value of the indicated set of global values in global
21888       --  variables within the library.
21889
21890       procedure Set_Globals
21891         (Main_Priority            : Integer;
21892          Time_Slice_Value         : Integer;
21893          WC_Encoding              : Character;
21894          Locking_Policy           : Character;
21895          Queuing_Policy           : Character;
21896          Task_Dispatching_Policy  : Character;
21897          Adafinal                 : System.Address;
21898          Unreserve_All_Interrupts : Integer;
21899          Exception_Tracebacks     : Integer);
21900 @findex __gnat_set_globals
21901       pragma Import (C, Set_Globals, "__gnat_set_globals");
21902
21903       --  SDP_Table_Build is a library routine used to build the
21904       --  exception tables. See unit Ada.Exceptions in files
21905       --  a-except.ads/adb for full details of how zero cost
21906       --  exception handling works. This procedure, the call to
21907       --  it, and the two following tables are all omitted if the
21908       --  build is in longjmp/setjmp exception mode.
21909
21910 @findex SDP_Table_Build
21911 @findex Zero Cost Exceptions
21912       procedure SDP_Table_Build
21913         (SDP_Addresses   : System.Address;
21914          SDP_Count       : Natural;
21915          Elab_Addresses  : System.Address;
21916          Elab_Addr_Count : Natural);
21917       pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
21918
21919       --  Table of Unit_Exception_Table addresses. Used for zero
21920       --  cost exception handling to build the top level table.
21921
21922       ST : aliased constant array (1 .. 23) of System.Address := (
21923         Hello'UET_Address,
21924         Ada.Text_Io'UET_Address,
21925         Ada.Exceptions'UET_Address,
21926         Gnat.Heap_Sort_A'UET_Address,
21927         System.Exception_Table'UET_Address,
21928         System.Machine_State_Operations'UET_Address,
21929         System.Secondary_Stack'UET_Address,
21930         System.Parameters'UET_Address,
21931         System.Soft_Links'UET_Address,
21932         System.Stack_Checking'UET_Address,
21933         System.Traceback'UET_Address,
21934         Ada.Streams'UET_Address,
21935         Ada.Tags'UET_Address,
21936         System.String_Ops'UET_Address,
21937         Interfaces.C_Streams'UET_Address,
21938         System.File_Io'UET_Address,
21939         Ada.Finalization'UET_Address,
21940         System.Finalization_Root'UET_Address,
21941         System.Finalization_Implementation'UET_Address,
21942         System.String_Ops_Concat_3'UET_Address,
21943         System.Stream_Attributes'UET_Address,
21944         System.File_Control_Block'UET_Address,
21945         Ada.Finalization.List_Controller'UET_Address);
21946
21947       --  Table of addresses of elaboration routines. Used for
21948       --  zero cost exception handling to make sure these
21949       --  addresses are included in the top level procedure
21950       --  address table.
21951
21952       EA : aliased constant array (1 .. 23) of System.Address := (
21953         adainit'Code_Address,
21954         Do_Finalize'Code_Address,
21955         Ada.Exceptions'Elab_Spec'Address,
21956         System.Exceptions'Elab_Spec'Address,
21957         Interfaces.C_Streams'Elab_Spec'Address,
21958         System.Exception_Table'Elab_Body'Address,
21959         Ada.Io_Exceptions'Elab_Spec'Address,
21960         System.Stack_Checking'Elab_Spec'Address,
21961         System.Soft_Links'Elab_Body'Address,
21962         System.Secondary_Stack'Elab_Body'Address,
21963         Ada.Tags'Elab_Spec'Address,
21964         Ada.Tags'Elab_Body'Address,
21965         Ada.Streams'Elab_Spec'Address,
21966         System.Finalization_Root'Elab_Spec'Address,
21967         Ada.Exceptions'Elab_Body'Address,
21968         System.Finalization_Implementation'Elab_Spec'Address,
21969         System.Finalization_Implementation'Elab_Body'Address,
21970         Ada.Finalization'Elab_Spec'Address,
21971         Ada.Finalization.List_Controller'Elab_Spec'Address,
21972         System.File_Control_Block'Elab_Spec'Address,
21973         System.File_Io'Elab_Body'Address,
21974         Ada.Text_Io'Elab_Spec'Address,
21975         Ada.Text_Io'Elab_Body'Address);
21976
21977    --  Start of processing for adainit
21978
21979    begin
21980
21981       --  Call SDP_Table_Build to build the top level procedure
21982       --  table for zero cost exception handling (omitted in
21983       --  longjmp/setjmp mode).
21984
21985       SDP_Table_Build (ST'Address, 23, EA'Address, 23);
21986
21987       --  Call Set_Globals to record various information for
21988       --  this partition.  The values are derived by the binder
21989       --  from information stored in the ali files by the compiler.
21990
21991 @findex __gnat_set_globals
21992       Set_Globals
21993         (Main_Priority            => -1,
21994          --  Priority of main program, -1 if no pragma Priority used
21995
21996          Time_Slice_Value         => -1,
21997          --  Time slice from Time_Slice pragma, -1 if none used
21998
21999          WC_Encoding              => 'b',
22000          --  Wide_Character encoding used, default is brackets
22001
22002          Locking_Policy           => ' ',
22003          --  Locking_Policy used, default of space means not
22004          --  specified, otherwise it is the first character of
22005          --  the policy name.
22006
22007          Queuing_Policy           => ' ',
22008          --  Queuing_Policy used, default of space means not
22009          --  specified, otherwise it is the first character of
22010          --  the policy name.
22011
22012          Task_Dispatching_Policy  => ' ',
22013          --  Task_Dispatching_Policy used, default of space means
22014          --  not specified, otherwise first character of the
22015          --  policy name.
22016
22017          Adafinal                 => System.Null_Address,
22018          --  Address of Adafinal routine, not used anymore
22019
22020          Unreserve_All_Interrupts => 0,
22021          --  Set true if pragma Unreserve_All_Interrupts was used
22022
22023          Exception_Tracebacks     => 0);
22024          --  Indicates if exception tracebacks are enabled
22025
22026       Elab_Final_Code := 1;
22027
22028       --  Now we have the elaboration calls for all units in the partition.
22029       --  The Elab_Spec and Elab_Body attributes generate references to the
22030       --  implicit elaboration procedures generated by the compiler for
22031       --  each unit that requires elaboration.
22032
22033       if not E040 then
22034          Interfaces.C_Streams'Elab_Spec;
22035       end if;
22036       E040 := True;
22037       if not E008 then
22038          Ada.Exceptions'Elab_Spec;
22039       end if;
22040       if not E014 then
22041          System.Exception_Table'Elab_Body;
22042          E014 := True;
22043       end if;
22044       if not E053 then
22045          Ada.Io_Exceptions'Elab_Spec;
22046          E053 := True;
22047       end if;
22048       if not E017 then
22049          System.Exceptions'Elab_Spec;
22050          E017 := True;
22051       end if;
22052       if not E030 then
22053          System.Stack_Checking'Elab_Spec;
22054       end if;
22055       if not E028 then
22056          System.Soft_Links'Elab_Body;
22057          E028 := True;
22058       end if;
22059       E030 := True;
22060       if not E024 then
22061          System.Secondary_Stack'Elab_Body;
22062          E024 := True;
22063       end if;
22064       if not E035 then
22065          Ada.Tags'Elab_Spec;
22066       end if;
22067       if not E035 then
22068          Ada.Tags'Elab_Body;
22069          E035 := True;
22070       end if;
22071       if not E033 then
22072          Ada.Streams'Elab_Spec;
22073          E033 := True;
22074       end if;
22075       if not E046 then
22076          System.Finalization_Root'Elab_Spec;
22077       end if;
22078       E046 := True;
22079       if not E008 then
22080          Ada.Exceptions'Elab_Body;
22081          E008 := True;
22082       end if;
22083       if not E048 then
22084          System.Finalization_Implementation'Elab_Spec;
22085       end if;
22086       if not E048 then
22087          System.Finalization_Implementation'Elab_Body;
22088          E048 := True;
22089       end if;
22090       if not E044 then
22091          Ada.Finalization'Elab_Spec;
22092       end if;
22093       E044 := True;
22094       if not E057 then
22095          Ada.Finalization.List_Controller'Elab_Spec;
22096       end if;
22097       E057 := True;
22098       if not E055 then
22099          System.File_Control_Block'Elab_Spec;
22100          E055 := True;
22101       end if;
22102       if not E042 then
22103          System.File_Io'Elab_Body;
22104          E042 := True;
22105       end if;
22106       if not E006 then
22107          Ada.Text_Io'Elab_Spec;
22108       end if;
22109       if not E006 then
22110          Ada.Text_Io'Elab_Body;
22111          E006 := True;
22112       end if;
22113
22114       Elab_Final_Code := 0;
22115    end adainit;
22116
22117    --------------
22118    -- adafinal --
22119    --------------
22120
22121 @findex adafinal
22122    procedure adafinal is
22123    begin
22124       Do_Finalize;
22125    end adafinal;
22126
22127    ----------
22128    -- main --
22129    ----------
22130
22131    --  main is actually a function, as in the ANSI C standard,
22132    --  defined to return the exit status. The three parameters
22133    --  are the argument count, argument values and environment
22134    --  pointer.
22135
22136 @findex Main Program
22137    function main
22138      (argc : Integer;
22139       argv : System.Address;
22140       envp : System.Address)
22141       return Integer
22142    is
22143       --  The initialize routine performs low level system
22144       --  initialization using a standard library routine which
22145       --  sets up signal handling and performs any other
22146       --  required setup. The routine can be found in file
22147       --  a-init.c.
22148
22149 @findex __gnat_initialize
22150       procedure initialize;
22151       pragma Import (C, initialize, "__gnat_initialize");
22152
22153       --  The finalize routine performs low level system
22154       --  finalization using a standard library routine. The
22155       --  routine is found in file a-final.c and in the standard
22156       --  distribution is a dummy routine that does nothing, so
22157       --  really this is a hook for special user finalization.
22158
22159 @findex __gnat_finalize
22160       procedure finalize;
22161       pragma Import (C, finalize, "__gnat_finalize");
22162
22163       --  We get to the main program of the partition by using
22164       --  pragma Import because if we try to with the unit and
22165       --  call it Ada style, then not only do we waste time
22166       --  recompiling it, but also, we don't really know the right
22167       --  switches (e.g.@: identifier character set) to be used
22168       --  to compile it.
22169
22170       procedure Ada_Main_Program;
22171       pragma Import (Ada, Ada_Main_Program, "_ada_hello");
22172
22173    --  Start of processing for main
22174
22175    begin
22176       --  Save global variables
22177
22178       gnat_argc := argc;
22179       gnat_argv := argv;
22180       gnat_envp := envp;
22181
22182       --  Call low level system initialization
22183
22184       Initialize;
22185
22186       --  Call our generated Ada initialization routine
22187
22188       adainit;
22189
22190       --  This is the point at which we want the debugger to get
22191       --  control
22192
22193       Break_Start;
22194
22195       --  Now we call the main program of the partition
22196
22197       Ada_Main_Program;
22198
22199       --  Perform Ada finalization
22200
22201       adafinal;
22202
22203       --  Perform low level system finalization
22204
22205       Finalize;
22206
22207       --  Return the proper exit status
22208       return (gnat_exit_status);
22209    end;
22210
22211 --  This section is entirely comments, so it has no effect on the
22212 --  compilation of the Ada_Main package. It provides the list of
22213 --  object files and linker options, as well as some standard
22214 --  libraries needed for the link. The gnatlink utility parses
22215 --  this b~hello.adb file to read these comment lines to generate
22216 --  the appropriate command line arguments for the call to the
22217 --  system linker. The BEGIN/END lines are used for sentinels for
22218 --  this parsing operation.
22219
22220 --  The exact file names will of course depend on the environment,
22221 --  host/target and location of files on the host system.
22222
22223 @findex Object file list
22224 -- BEGIN Object file/option list
22225    --   ./hello.o
22226    --   -L./
22227    --   -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
22228    --   /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
22229 -- END Object file/option list
22230
22231 end ada_main;
22232 @end smallexample
22233
22234 @noindent
22235 The Ada code in the above example is exactly what is generated by the
22236 binder. We have added comments to more clearly indicate the function
22237 of each part of the generated @code{Ada_Main} package.
22238
22239 The code is standard Ada in all respects, and can be processed by any
22240 tools that handle Ada. In particular, it is possible to use the debugger
22241 in Ada mode to debug the generated @code{Ada_Main} package. For example,
22242 suppose that for reasons that you do not understand, your program is crashing
22243 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
22244 you can place a breakpoint on the call:
22245
22246 @smallexample @c ada
22247 Ada.Text_Io'Elab_Body;
22248 @end smallexample
22249
22250 @noindent
22251 and trace the elaboration routine for this package to find out where
22252 the problem might be (more usually of course you would be debugging
22253 elaboration code in your own application).
22254
22255 @node Elaboration Order Handling in GNAT
22256 @appendix Elaboration Order Handling in GNAT
22257 @cindex Order of elaboration
22258 @cindex Elaboration control
22259
22260 @menu
22261 * Elaboration Code::
22262 * Checking the Elaboration Order::
22263 * Controlling the Elaboration Order::
22264 * Controlling Elaboration in GNAT - Internal Calls::
22265 * Controlling Elaboration in GNAT - External Calls::
22266 * Default Behavior in GNAT - Ensuring Safety::
22267 * Treatment of Pragma Elaborate::
22268 * Elaboration Issues for Library Tasks::
22269 * Mixing Elaboration Models::
22270 * What to Do If the Default Elaboration Behavior Fails::
22271 * Elaboration for Access-to-Subprogram Values::
22272 * Summary of Procedures for Elaboration Control::
22273 * Other Elaboration Order Considerations::
22274 @end menu
22275
22276 @noindent
22277 This chapter describes the handling of elaboration code in Ada and
22278 in GNAT, and discusses how the order of elaboration of program units can
22279 be controlled in GNAT, either automatically or with explicit programming
22280 features.
22281
22282 @node Elaboration Code
22283 @section Elaboration Code
22284
22285 @noindent
22286 Ada provides rather general mechanisms for executing code at elaboration
22287 time, that is to say before the main program starts executing. Such code arises
22288 in three contexts:
22289
22290 @table @asis
22291 @item Initializers for variables.
22292 Variables declared at the library level, in package specs or bodies, can
22293 require initialization that is performed at elaboration time, as in:
22294 @smallexample @c ada
22295 @cartouche
22296 Sqrt_Half : Float := Sqrt (0.5);
22297 @end cartouche
22298 @end smallexample
22299
22300 @item Package initialization code
22301 Code in a @code{BEGIN-END} section at the outer level of a package body is
22302 executed as part of the package body elaboration code.
22303
22304 @item Library level task allocators
22305 Tasks that are declared using task allocators at the library level
22306 start executing immediately and hence can execute at elaboration time.
22307 @end table
22308
22309 @noindent
22310 Subprogram calls are possible in any of these contexts, which means that
22311 any arbitrary part of the program may be executed as part of the elaboration
22312 code. It is even possible to write a program which does all its work at
22313 elaboration time, with a null main program, although stylistically this
22314 would usually be considered an inappropriate way to structure
22315 a program.
22316
22317 An important concern arises in the context of elaboration code:
22318 we have to be sure that it is executed in an appropriate order. What we
22319 have is a series of elaboration code sections, potentially one section
22320 for each unit in the program. It is important that these execute
22321 in the correct order. Correctness here means that, taking the above
22322 example of the declaration of @code{Sqrt_Half},
22323 if some other piece of
22324 elaboration code references @code{Sqrt_Half},
22325 then it must run after the
22326 section of elaboration code that contains the declaration of
22327 @code{Sqrt_Half}.
22328
22329 There would never be any order of elaboration problem if we made a rule
22330 that whenever you @code{with} a unit, you must elaborate both the spec and body
22331 of that unit before elaborating the unit doing the @code{with}'ing:
22332
22333 @smallexample @c ada
22334 @group
22335 @cartouche
22336 with Unit_1;
22337 package Unit_2 is @dots{}
22338 @end cartouche
22339 @end group
22340 @end smallexample
22341
22342 @noindent
22343 would require that both the body and spec of @code{Unit_1} be elaborated
22344 before the spec of @code{Unit_2}. However, a rule like that would be far too
22345 restrictive. In particular, it would make it impossible to have routines
22346 in separate packages that were mutually recursive.
22347
22348 You might think that a clever enough compiler could look at the actual
22349 elaboration code and determine an appropriate correct order of elaboration,
22350 but in the general case, this is not possible. Consider the following
22351 example.
22352
22353 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
22354 that references
22355 the variable @code{Sqrt_1}, which is declared in the elaboration code
22356 of the body of @code{Unit_1}:
22357
22358 @smallexample @c ada
22359 @cartouche
22360 Sqrt_1 : Float := Sqrt (0.1);
22361 @end cartouche
22362 @end smallexample
22363
22364 @noindent
22365 The elaboration code of the body of @code{Unit_1} also contains:
22366
22367 @smallexample @c ada
22368 @group
22369 @cartouche
22370 if expression_1 = 1 then
22371    Q := Unit_2.Func_2;
22372 end if;
22373 @end cartouche
22374 @end group
22375 @end smallexample
22376
22377 @noindent
22378 @code{Unit_2} is exactly parallel,
22379 it has a procedure @code{Func_2} that references
22380 the variable @code{Sqrt_2}, which is declared in the elaboration code of
22381 the body @code{Unit_2}:
22382
22383 @smallexample @c ada
22384 @cartouche
22385 Sqrt_2 : Float := Sqrt (0.1);
22386 @end cartouche
22387 @end smallexample
22388
22389 @noindent
22390 The elaboration code of the body of @code{Unit_2} also contains:
22391
22392 @smallexample @c ada
22393 @group
22394 @cartouche
22395 if expression_2 = 2 then
22396    Q := Unit_1.Func_1;
22397 end if;
22398 @end cartouche
22399 @end group
22400 @end smallexample
22401
22402 @noindent
22403 Now the question is, which of the following orders of elaboration is
22404 acceptable:
22405
22406 @smallexample
22407 @group
22408 Spec of Unit_1
22409 Spec of Unit_2
22410 Body of Unit_1
22411 Body of Unit_2
22412 @end group
22413 @end smallexample
22414
22415 @noindent
22416 or
22417
22418 @smallexample
22419 @group
22420 Spec of Unit_2
22421 Spec of Unit_1
22422 Body of Unit_2
22423 Body of Unit_1
22424 @end group
22425 @end smallexample
22426
22427 @noindent
22428 If you carefully analyze the flow here, you will see that you cannot tell
22429 at compile time the answer to this question.
22430 If @code{expression_1} is not equal to 1,
22431 and @code{expression_2} is not equal to 2,
22432 then either order is acceptable, because neither of the function calls is
22433 executed. If both tests evaluate to true, then neither order is acceptable
22434 and in fact there is no correct order.
22435
22436 If one of the two expressions is true, and the other is false, then one
22437 of the above orders is correct, and the other is incorrect. For example,
22438 if @code{expression_1} /= 1 and @code{expression_2} = 2,
22439 then the call to @code{Func_1}
22440 will occur, but not the call to @code{Func_2.}
22441 This means that it is essential
22442 to elaborate the body of @code{Unit_1} before
22443 the body of @code{Unit_2}, so the first
22444 order of elaboration is correct and the second is wrong.
22445
22446 By making @code{expression_1} and @code{expression_2}
22447 depend on input data, or perhaps
22448 the time of day, we can make it impossible for the compiler or binder
22449 to figure out which of these expressions will be true, and hence it
22450 is impossible to guarantee a safe order of elaboration at run time.
22451
22452 @node Checking the Elaboration Order
22453 @section Checking the Elaboration Order
22454
22455 @noindent
22456 In some languages that involve the same kind of elaboration problems,
22457 e.g.@: Java and C++, the programmer is expected to worry about these
22458 ordering problems himself, and it is common to
22459 write a program in which an incorrect elaboration order  gives
22460 surprising results, because it references variables before they
22461 are initialized.
22462 Ada is designed to be a safe language, and a programmer-beware approach is
22463 clearly not sufficient. Consequently, the language provides three lines
22464 of defense:
22465
22466 @table @asis
22467 @item Standard rules
22468 Some standard rules restrict the possible choice of elaboration
22469 order. In particular, if you @code{with} a unit, then its spec is always
22470 elaborated before the unit doing the @code{with}. Similarly, a parent
22471 spec is always elaborated before the child spec, and finally
22472 a spec is always elaborated before its corresponding body.
22473
22474 @item Dynamic elaboration checks
22475 @cindex Elaboration checks
22476 @cindex Checks, elaboration
22477 Dynamic checks are made at run time, so that if some entity is accessed
22478 before it is elaborated (typically  by means of a subprogram call)
22479 then the exception (@code{Program_Error}) is raised.
22480
22481 @item Elaboration control
22482 Facilities are provided for the programmer to specify the desired order
22483 of elaboration.
22484 @end table
22485
22486 Let's look at these facilities in more detail. First, the rules for
22487 dynamic checking. One possible rule would be simply to say that the
22488 exception is raised if you access a variable which has not yet been
22489 elaborated. The trouble with this approach is that it could require
22490 expensive checks on every variable reference. Instead Ada has two
22491 rules which are a little more restrictive, but easier to check, and
22492 easier to state:
22493
22494 @table @asis
22495 @item Restrictions on calls
22496 A subprogram can only be called at elaboration time if its body
22497 has been elaborated. The rules for elaboration given above guarantee
22498 that the spec of the subprogram has been elaborated before the
22499 call, but not the body. If this rule is violated, then the
22500 exception @code{Program_Error} is raised.
22501
22502 @item Restrictions on instantiations
22503 A generic unit can only be instantiated if the body of the generic
22504 unit has been elaborated. Again, the rules for elaboration given above
22505 guarantee that the spec of the generic unit has been elaborated
22506 before the instantiation, but not the body. If this rule is
22507 violated, then the exception @code{Program_Error} is raised.
22508 @end table
22509
22510 @noindent
22511 The idea is that if the body has been elaborated, then any variables
22512 it references must have been elaborated; by checking for the body being
22513 elaborated we guarantee that none of its references causes any
22514 trouble. As we noted above, this is a little too restrictive, because a
22515 subprogram that has no non-local references in its body may in fact be safe
22516 to call. However, it really would be unsafe to rely on this, because
22517 it would mean that the caller was aware of details of the implementation
22518 in the body. This goes against the basic tenets of Ada.
22519
22520 A plausible implementation can be described as follows.
22521 A Boolean variable is associated with each subprogram
22522 and each generic unit. This variable is initialized to False, and is set to
22523 True at the point body is elaborated. Every call or instantiation checks the
22524 variable, and raises @code{Program_Error} if the variable is False.
22525
22526 Note that one might think that it would be good enough to have one Boolean
22527 variable for each package, but that would not deal with cases of trying
22528 to call a body in the same package as the call
22529 that has not been elaborated yet.
22530 Of course a compiler may be able to do enough analysis to optimize away
22531 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
22532 does such optimizations, but still the easiest conceptual model is to
22533 think of there being one variable per subprogram.
22534
22535 @node Controlling the Elaboration Order
22536 @section Controlling the Elaboration Order
22537
22538 @noindent
22539 In the previous section we discussed the rules in Ada which ensure
22540 that @code{Program_Error} is raised if an incorrect elaboration order is
22541 chosen. This prevents erroneous executions, but we need mechanisms to
22542 specify a correct execution and avoid the exception altogether.
22543 To achieve this, Ada provides a number of features for controlling
22544 the order of elaboration. We discuss these features in this section.
22545
22546 First, there are several ways of indicating to the compiler that a given
22547 unit has no elaboration problems:
22548
22549 @table @asis
22550 @item packages that do not require a body
22551 A library package that does not require a body does not permit
22552 a body (this rule was introduced in Ada 95).
22553 Thus if we have a such a package, as in:
22554
22555 @smallexample @c ada
22556 @group
22557 @cartouche
22558 package Definitions is
22559    generic
22560       type m is new integer;
22561    package Subp is
22562       type a is array (1 .. 10) of m;
22563       type b is array (1 .. 20) of m;
22564    end Subp;
22565 end Definitions;
22566 @end cartouche
22567 @end group
22568 @end smallexample
22569
22570 @noindent
22571 A package that @code{with}'s @code{Definitions} may safely instantiate
22572 @code{Definitions.Subp} because the compiler can determine that there
22573 definitely is no package body to worry about in this case
22574
22575 @item pragma Pure
22576 @cindex pragma Pure
22577 @findex Pure
22578 Places sufficient restrictions on a unit to guarantee that
22579 no call to any subprogram in the unit can result in an
22580 elaboration problem. This means that the compiler does not need
22581 to worry about the point of elaboration of such units, and in
22582 particular, does not need to check any calls to any subprograms
22583 in this unit.
22584
22585 @item pragma Preelaborate
22586 @findex Preelaborate
22587 @cindex pragma Preelaborate
22588 This pragma places slightly less stringent restrictions on a unit than
22589 does pragma Pure,
22590 but these restrictions are still sufficient to ensure that there
22591 are no elaboration problems with any calls to the unit.
22592
22593 @item pragma Elaborate_Body
22594 @findex Elaborate_Body
22595 @cindex pragma Elaborate_Body
22596 This pragma requires that the body of a unit be elaborated immediately
22597 after its spec. Suppose a unit @code{A} has such a pragma,
22598 and unit @code{B} does
22599 a @code{with} of unit @code{A}. Recall that the standard rules require
22600 the spec of unit @code{A}
22601 to be elaborated before the @code{with}'ing unit; given the pragma in
22602 @code{A}, we also know that the body of @code{A}
22603 will be elaborated before @code{B}, so
22604 that calls to @code{A} are safe and do not need a check.
22605 @end table
22606
22607 @noindent
22608 Note that,
22609 unlike pragma @code{Pure} and pragma @code{Preelaborate},
22610 the use of
22611 @code{Elaborate_Body} does not guarantee that the program is
22612 free of elaboration problems, because it may not be possible
22613 to satisfy the requested elaboration order.
22614 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
22615 If a programmer
22616 marks @code{Unit_1} as @code{Elaborate_Body},
22617 and not @code{Unit_2,} then the order of
22618 elaboration will be:
22619
22620 @smallexample
22621 @group
22622 Spec of Unit_2
22623 Spec of Unit_1
22624 Body of Unit_1
22625 Body of Unit_2
22626 @end group
22627 @end smallexample
22628
22629 @noindent
22630 Now that means that the call to @code{Func_1} in @code{Unit_2}
22631 need not be checked,
22632 it must be safe. But the call to @code{Func_2} in
22633 @code{Unit_1} may still fail if
22634 @code{Expression_1} is equal to 1,
22635 and the programmer must still take
22636 responsibility for this not being the case.
22637
22638 If all units carry a pragma @code{Elaborate_Body}, then all problems are
22639 eliminated, except for calls entirely within a body, which are
22640 in any case fully under programmer control. However, using the pragma
22641 everywhere is not always possible.
22642 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
22643 we marked both of them as having pragma @code{Elaborate_Body}, then
22644 clearly there would be no possible elaboration order.
22645
22646 The above pragmas allow a server to guarantee safe use by clients, and
22647 clearly this is the preferable approach. Consequently a good rule
22648 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
22649 and if this is not possible,
22650 mark them as @code{Elaborate_Body} if possible.
22651 As we have seen, there are situations where neither of these
22652 three pragmas can be used.
22653 So we also provide methods for clients to control the
22654 order of elaboration of the servers on which they depend:
22655
22656 @table @asis
22657 @item pragma Elaborate (unit)
22658 @findex Elaborate
22659 @cindex pragma Elaborate
22660 This pragma is placed in the context clause, after a @code{with} clause,
22661 and it requires that the body of the named unit be elaborated before
22662 the unit in which the pragma occurs. The idea is to use this pragma
22663 if the current unit calls at elaboration time, directly or indirectly,
22664 some subprogram in the named unit.
22665
22666 @item pragma Elaborate_All (unit)
22667 @findex Elaborate_All
22668 @cindex pragma Elaborate_All
22669 This is a stronger version of the Elaborate pragma. Consider the
22670 following example:
22671
22672 @smallexample
22673 Unit A @code{with}'s unit B and calls B.Func in elab code
22674 Unit B @code{with}'s unit C, and B.Func calls C.Func
22675 @end smallexample
22676
22677 @noindent
22678 Now if we put a pragma @code{Elaborate (B)}
22679 in unit @code{A}, this ensures that the
22680 body of @code{B} is elaborated before the call, but not the
22681 body of @code{C}, so
22682 the call to @code{C.Func} could still cause @code{Program_Error} to
22683 be raised.
22684
22685 The effect of a pragma @code{Elaborate_All} is stronger, it requires
22686 not only that the body of the named unit be elaborated before the
22687 unit doing the @code{with}, but also the bodies of all units that the
22688 named unit uses, following @code{with} links transitively. For example,
22689 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
22690 then it requires
22691 not only that the body of @code{B} be elaborated before @code{A},
22692 but also the
22693 body of @code{C}, because @code{B} @code{with}'s @code{C}.
22694 @end table
22695
22696 @noindent
22697 We are now in a position to give a usage rule in Ada for avoiding
22698 elaboration problems, at least if dynamic dispatching and access to
22699 subprogram values are not used. We will handle these cases separately
22700 later.
22701
22702 The rule is simple. If a unit has elaboration code that can directly or
22703 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
22704 a generic package in a @code{with}'ed unit,
22705 then if the @code{with}'ed unit does not have
22706 pragma @code{Pure} or @code{Preelaborate}, then the client should have
22707 a pragma @code{Elaborate_All}
22708 for the @code{with}'ed unit. By following this rule a client is
22709 assured that calls can be made without risk of an exception.
22710
22711 For generic subprogram instantiations, the rule can be relaxed to
22712 require only a pragma @code{Elaborate} since elaborating the body
22713 of a subprogram cannot cause any transitive elaboration (we are
22714 not calling the subprogram in this case, just elaborating its
22715 declaration).
22716
22717 If this rule is not followed, then a program may be in one of four
22718 states:
22719
22720 @table @asis
22721 @item No order exists
22722 No order of elaboration exists which follows the rules, taking into
22723 account any @code{Elaborate}, @code{Elaborate_All},
22724 or @code{Elaborate_Body} pragmas. In
22725 this case, an Ada compiler must diagnose the situation at bind
22726 time, and refuse to build an executable program.
22727
22728 @item One or more orders exist, all incorrect
22729 One or more acceptable elaboration orders exist, and all of them
22730 generate an elaboration order problem. In this case, the binder
22731 can build an executable program, but @code{Program_Error} will be raised
22732 when the program is run.
22733
22734 @item Several orders exist, some right, some incorrect
22735 One or more acceptable elaboration orders exists, and some of them
22736 work, and some do not. The programmer has not controlled
22737 the order of elaboration, so the binder may or may not pick one of
22738 the correct orders, and the program may or may not raise an
22739 exception when it is run. This is the worst case, because it means
22740 that the program may fail when moved to another compiler, or even
22741 another version of the same compiler.
22742
22743 @item One or more orders exists, all correct
22744 One ore more acceptable elaboration orders exist, and all of them
22745 work. In this case the program runs successfully. This state of
22746 affairs can be guaranteed by following the rule we gave above, but
22747 may be true even if the rule is not followed.
22748 @end table
22749
22750 @noindent
22751 Note that one additional advantage of following our rules on the use
22752 of @code{Elaborate} and @code{Elaborate_All}
22753 is that the program continues to stay in the ideal (all orders OK) state
22754 even if maintenance
22755 changes some bodies of some units. Conversely, if a program that does
22756 not follow this rule happens to be safe at some point, this state of affairs
22757 may deteriorate silently as a result of maintenance changes.
22758
22759 You may have noticed that the above discussion did not mention
22760 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
22761 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
22762 code in the body makes calls to some other unit, so it is still necessary
22763 to use @code{Elaborate_All} on such units.
22764
22765 @node Controlling Elaboration in GNAT - Internal Calls
22766 @section Controlling Elaboration in GNAT - Internal Calls
22767
22768 @noindent
22769 In the case of internal calls, i.e., calls within a single package, the
22770 programmer has full control over the order of elaboration, and it is up
22771 to the programmer to elaborate declarations in an appropriate order. For
22772 example writing:
22773
22774 @smallexample @c ada
22775 @group
22776 @cartouche
22777 function One return Float;
22778
22779 Q : Float := One;
22780
22781 function One return Float is
22782 begin
22783      return 1.0;
22784 end One;
22785 @end cartouche
22786 @end group
22787 @end smallexample
22788
22789 @noindent
22790 will obviously raise @code{Program_Error} at run time, because function
22791 One will be called before its body is elaborated. In this case GNAT will
22792 generate a warning that the call will raise @code{Program_Error}:
22793
22794 @smallexample
22795 @group
22796 @cartouche
22797  1. procedure y is
22798  2.    function One return Float;
22799  3.
22800  4.    Q : Float := One;
22801                     |
22802     >>> warning: cannot call "One" before body is elaborated
22803     >>> warning: Program_Error will be raised at run time
22804
22805  5.
22806  6.    function One return Float is
22807  7.    begin
22808  8.         return 1.0;
22809  9.    end One;
22810 10.
22811 11. begin
22812 12.    null;
22813 13. end;
22814 @end cartouche
22815 @end group
22816 @end smallexample
22817
22818 @noindent
22819 Note that in this particular case, it is likely that the call is safe, because
22820 the function @code{One} does not access any global variables.
22821 Nevertheless in Ada, we do not want the validity of the check to depend on
22822 the contents of the body (think about the separate compilation case), so this
22823 is still wrong, as we discussed in the previous sections.
22824
22825 The error is easily corrected by rearranging the declarations so that the
22826 body of @code{One} appears before the declaration containing the call
22827 (note that in Ada 95 and Ada 2005,
22828 declarations can appear in any order, so there is no restriction that
22829 would prevent this reordering, and if we write:
22830
22831 @smallexample @c ada
22832 @group
22833 @cartouche
22834 function One return Float;
22835
22836 function One return Float is
22837 begin
22838      return 1.0;
22839 end One;
22840
22841 Q : Float := One;
22842 @end cartouche
22843 @end group
22844 @end smallexample
22845
22846 @noindent
22847 then all is well, no warning is generated, and no
22848 @code{Program_Error} exception
22849 will be raised.
22850 Things are more complicated when a chain of subprograms is executed:
22851
22852 @smallexample @c ada
22853 @group
22854 @cartouche
22855 function A return Integer;
22856 function B return Integer;
22857 function C return Integer;
22858
22859 function B return Integer is begin return A; end;
22860 function C return Integer is begin return B; end;
22861
22862 X : Integer := C;
22863
22864 function A return Integer is begin return 1; end;
22865 @end cartouche
22866 @end group
22867 @end smallexample
22868
22869 @noindent
22870 Now the call to @code{C}
22871 at elaboration time in the declaration of @code{X} is correct, because
22872 the body of @code{C} is already elaborated,
22873 and the call to @code{B} within the body of
22874 @code{C} is correct, but the call
22875 to @code{A} within the body of @code{B} is incorrect, because the body
22876 of @code{A} has not been elaborated, so @code{Program_Error}
22877 will be raised on the call to @code{A}.
22878 In this case GNAT will generate a
22879 warning that @code{Program_Error} may be
22880 raised at the point of the call. Let's look at the warning:
22881
22882 @smallexample
22883 @group
22884 @cartouche
22885  1. procedure x is
22886  2.    function A return Integer;
22887  3.    function B return Integer;
22888  4.    function C return Integer;
22889  5.
22890  6.    function B return Integer is begin return A; end;
22891                                                     |
22892     >>> warning: call to "A" before body is elaborated may
22893                  raise Program_Error
22894     >>> warning: "B" called at line 7
22895     >>> warning: "C" called at line 9
22896
22897  7.    function C return Integer is begin return B; end;
22898  8.
22899  9.    X : Integer := C;
22900 10.
22901 11.    function A return Integer is begin return 1; end;
22902 12.
22903 13. begin
22904 14.    null;
22905 15. end;
22906 @end cartouche
22907 @end group
22908 @end smallexample
22909
22910 @noindent
22911 Note that the message here says ``may raise'', instead of the direct case,
22912 where the message says ``will be raised''. That's because whether
22913 @code{A} is
22914 actually called depends in general on run-time flow of control.
22915 For example, if the body of @code{B} said
22916
22917 @smallexample @c ada
22918 @group
22919 @cartouche
22920 function B return Integer is
22921 begin
22922    if some-condition-depending-on-input-data then
22923       return A;
22924    else
22925       return 1;
22926    end if;
22927 end B;
22928 @end cartouche
22929 @end group
22930 @end smallexample
22931
22932 @noindent
22933 then we could not know until run time whether the incorrect call to A would
22934 actually occur, so @code{Program_Error} might
22935 or might not be raised. It is possible for a compiler to
22936 do a better job of analyzing bodies, to
22937 determine whether or not @code{Program_Error}
22938 might be raised, but it certainly
22939 couldn't do a perfect job (that would require solving the halting problem
22940 and is provably impossible), and because this is a warning anyway, it does
22941 not seem worth the effort to do the analysis. Cases in which it
22942 would be relevant are rare.
22943
22944 In practice, warnings of either of the forms given
22945 above will usually correspond to
22946 real errors, and should be examined carefully and eliminated.
22947 In the rare case where a warning is bogus, it can be suppressed by any of
22948 the following methods:
22949
22950 @itemize @bullet
22951 @item
22952 Compile with the @option{-gnatws} switch set
22953
22954 @item
22955 Suppress @code{Elaboration_Check} for the called subprogram
22956
22957 @item
22958 Use pragma @code{Warnings_Off} to turn warnings off for the call
22959 @end itemize
22960
22961 @noindent
22962 For the internal elaboration check case,
22963 GNAT by default generates the
22964 necessary run-time checks to ensure
22965 that @code{Program_Error} is raised if any
22966 call fails an elaboration check. Of course this can only happen if a
22967 warning has been issued as described above. The use of pragma
22968 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
22969 some of these checks, meaning that it may be possible (but is not
22970 guaranteed) for a program to be able to call a subprogram whose body
22971 is not yet elaborated, without raising a @code{Program_Error} exception.
22972
22973 @node Controlling Elaboration in GNAT - External Calls
22974 @section Controlling Elaboration in GNAT - External Calls
22975
22976 @noindent
22977 The previous section discussed the case in which the execution of a
22978 particular thread of elaboration code occurred entirely within a
22979 single unit. This is the easy case to handle, because a programmer
22980 has direct and total control over the order of elaboration, and
22981 furthermore, checks need only be generated in cases which are rare
22982 and which the compiler can easily detect.
22983 The situation is more complex when separate compilation is taken into account.
22984 Consider the following:
22985
22986 @smallexample @c ada
22987 @cartouche
22988 @group
22989 package Math is
22990    function Sqrt (Arg : Float) return Float;
22991 end Math;
22992
22993 package body Math is
22994    function Sqrt (Arg : Float) return Float is
22995    begin
22996          @dots{}
22997    end Sqrt;
22998 end Math;
22999 @end group
23000 @group
23001 with Math;
23002 package Stuff is
23003    X : Float := Math.Sqrt (0.5);
23004 end Stuff;
23005
23006 with Stuff;
23007 procedure Main is
23008 begin
23009    @dots{}
23010 end Main;
23011 @end group
23012 @end cartouche
23013 @end smallexample
23014
23015 @noindent
23016 where @code{Main} is the main program. When this program is executed, the
23017 elaboration code must first be executed, and one of the jobs of the
23018 binder is to determine the order in which the units of a program are
23019 to be elaborated. In this case we have four units: the spec and body
23020 of @code{Math},
23021 the spec of @code{Stuff} and the body of @code{Main}).
23022 In what order should the four separate sections of elaboration code
23023 be executed?
23024
23025 There are some restrictions in the order of elaboration that the binder
23026 can choose. In particular, if unit U has a @code{with}
23027 for a package @code{X}, then you
23028 are assured that the spec of @code{X}
23029 is elaborated before U , but you are
23030 not assured that the body of @code{X}
23031 is elaborated before U.
23032 This means that in the above case, the binder is allowed to choose the
23033 order:
23034
23035 @smallexample
23036 spec of Math
23037 spec of Stuff
23038 body of Math
23039 body of Main
23040 @end smallexample
23041
23042 @noindent
23043 but that's not good, because now the call to @code{Math.Sqrt}
23044 that happens during
23045 the elaboration of the @code{Stuff}
23046 spec happens before the body of @code{Math.Sqrt} is
23047 elaborated, and hence causes @code{Program_Error} exception to be raised.
23048 At first glance, one might say that the binder is misbehaving, because
23049 obviously you want to elaborate the body of something you @code{with}
23050 first, but
23051 that is not a general rule that can be followed in all cases. Consider
23052
23053 @smallexample @c ada
23054 @group
23055 @cartouche
23056 package X is @dots{}
23057
23058 package Y is @dots{}
23059
23060 with X;
23061 package body Y is @dots{}
23062
23063 with Y;
23064 package body X is @dots{}
23065 @end cartouche
23066 @end group
23067 @end smallexample
23068
23069 @noindent
23070 This is a common arrangement, and, apart from the order of elaboration
23071 problems that might arise in connection with elaboration code, this works fine.
23072 A rule that says that you must first elaborate the body of anything you
23073 @code{with} cannot work in this case:
23074 the body of @code{X} @code{with}'s @code{Y},
23075 which means you would have to
23076 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
23077 which means
23078 you have to elaborate the body of @code{X} first, but @dots{} and we have a
23079 loop that cannot be broken.
23080
23081 It is true that the binder can in many cases guess an order of elaboration
23082 that is unlikely to cause a @code{Program_Error}
23083 exception to be raised, and it tries to do so (in the
23084 above example of @code{Math/Stuff/Spec}, the GNAT binder will
23085 by default
23086 elaborate the body of @code{Math} right after its spec, so all will be well).
23087
23088 However, a program that blindly relies on the binder to be helpful can
23089 get into trouble, as we discussed in the previous sections, so
23090 GNAT
23091 provides a number of facilities for assisting the programmer in
23092 developing programs that are robust with respect to elaboration order.
23093
23094 @node Default Behavior in GNAT - Ensuring Safety
23095 @section Default Behavior in GNAT - Ensuring Safety
23096
23097 @noindent
23098 The default behavior in GNAT ensures elaboration safety. In its
23099 default mode GNAT implements the
23100 rule we previously described as the right approach. Let's restate it:
23101
23102 @itemize
23103 @item
23104 @emph{If a unit has elaboration code that can directly or indirectly make a
23105 call to a subprogram in a @code{with}'ed unit, or instantiate a generic
23106 package in a @code{with}'ed unit, then if the @code{with}'ed unit
23107 does not have pragma @code{Pure} or
23108 @code{Preelaborate}, then the client should have an
23109 @code{Elaborate_All} pragma for the @code{with}'ed unit.}
23110
23111 @emph{In the case of instantiating a generic subprogram, it is always
23112 sufficient to have only an @code{Elaborate} pragma for the
23113 @code{with}'ed unit.}
23114 @end itemize
23115
23116 @noindent
23117 By following this rule a client is assured that calls and instantiations
23118 can be made without risk of an exception.
23119
23120 In this mode GNAT traces all calls that are potentially made from
23121 elaboration code, and puts in any missing implicit @code{Elaborate}
23122 and @code{Elaborate_All} pragmas.
23123 The advantage of this approach is that no elaboration problems
23124 are possible if the binder can find an elaboration order that is
23125 consistent with these implicit @code{Elaborate} and
23126 @code{Elaborate_All} pragmas. The
23127 disadvantage of this approach is that no such order may exist.
23128
23129 If the binder does not generate any diagnostics, then it means that it has
23130 found an elaboration order that is guaranteed to be safe. However, the binder
23131 may still be relying on implicitly generated @code{Elaborate} and
23132 @code{Elaborate_All} pragmas so portability to other compilers than GNAT is not
23133 guaranteed.
23134
23135 If it is important to guarantee portability, then the compilations should
23136 use the
23137 @option{-gnatwl}
23138 (warn on elaboration problems) switch. This will cause warning messages
23139 to be generated indicating the missing @code{Elaborate} and
23140 @code{Elaborate_All} pragmas.
23141 Consider the following source program:
23142
23143 @smallexample @c ada
23144 @group
23145 @cartouche
23146 with k;
23147 package j is
23148   m : integer := k.r;
23149 end;
23150 @end cartouche
23151 @end group
23152 @end smallexample
23153
23154 @noindent
23155 where it is clear that there
23156 should be a pragma @code{Elaborate_All}
23157 for unit @code{k}. An implicit pragma will be generated, and it is
23158 likely that the binder will be able to honor it. However, if you want
23159 to port this program to some other Ada compiler than GNAT.
23160 it is safer to include the pragma explicitly in the source. If this
23161 unit is compiled with the
23162 @option{-gnatwl}
23163 switch, then the compiler outputs a warning:
23164
23165 @smallexample
23166 @group
23167 @cartouche
23168 1. with k;
23169 2. package j is
23170 3.   m : integer := k.r;
23171                      |
23172    >>> warning: call to "r" may raise Program_Error
23173    >>> warning: missing pragma Elaborate_All for "k"
23174
23175 4. end;
23176 @end cartouche
23177 @end group
23178 @end smallexample
23179
23180 @noindent
23181 and these warnings can be used as a guide for supplying manually
23182 the missing pragmas. It is usually a bad idea to use this warning
23183 option during development. That's because it will warn you when
23184 you need to put in a pragma, but cannot warn you when it is time
23185 to take it out. So the use of pragma @code{Elaborate_All} may lead to
23186 unnecessary dependencies and even false circularities.
23187
23188 This default mode is more restrictive than the Ada Reference
23189 Manual, and it is possible to construct programs which will compile
23190 using the dynamic model described there, but will run into a
23191 circularity using the safer static model we have described.
23192
23193 Of course any Ada compiler must be able to operate in a mode
23194 consistent with the requirements of the Ada Reference Manual,
23195 and in particular must have the capability of implementing the
23196 standard dynamic model of elaboration with run-time checks.
23197
23198 In GNAT, this standard mode can be achieved either by the use of
23199 the @option{-gnatE} switch on the compiler (@command{gcc} or
23200 @command{gnatmake}) command, or by the use of the configuration pragma:
23201
23202 @smallexample @c ada
23203 pragma Elaboration_Checks (DYNAMIC);
23204 @end smallexample
23205
23206 @noindent
23207 Either approach will cause the unit affected to be compiled using the
23208 standard dynamic run-time elaboration checks described in the Ada
23209 Reference Manual. The static model is generally preferable, since it
23210 is clearly safer to rely on compile and link time checks rather than
23211 run-time checks. However, in the case of legacy code, it may be
23212 difficult to meet the requirements of the static model. This
23213 issue is further discussed in
23214 @ref{What to Do If the Default Elaboration Behavior Fails}.
23215
23216 Note that the static model provides a strict subset of the allowed
23217 behavior and programs of the Ada Reference Manual, so if you do
23218 adhere to the static model and no circularities exist,
23219 then you are assured that your program will
23220 work using the dynamic model, providing that you remove any
23221 pragma Elaborate statements from the source.
23222
23223 @node Treatment of Pragma Elaborate
23224 @section Treatment of Pragma Elaborate
23225 @cindex Pragma Elaborate
23226
23227 @noindent
23228 The use of @code{pragma Elaborate}
23229 should generally be avoided in Ada 95 and Ada 2005 programs,
23230 since there is no guarantee that transitive calls
23231 will be properly handled. Indeed at one point, this pragma was placed
23232 in Annex J (Obsolescent Features), on the grounds that it is never useful.
23233
23234 Now that's a bit restrictive. In practice, the case in which
23235 @code{pragma Elaborate} is useful is when the caller knows that there
23236 are no transitive calls, or that the called unit contains all necessary
23237 transitive @code{pragma Elaborate} statements, and legacy code often
23238 contains such uses.
23239
23240 Strictly speaking the static mode in GNAT should ignore such pragmas,
23241 since there is no assurance at compile time that the necessary safety
23242 conditions are met. In practice, this would cause GNAT to be incompatible
23243 with correctly written Ada 83 code that had all necessary
23244 @code{pragma Elaborate} statements in place. Consequently, we made the
23245 decision that GNAT in its default mode will believe that if it encounters
23246 a @code{pragma Elaborate} then the programmer knows what they are doing,
23247 and it will trust that no elaboration errors can occur.
23248
23249 The result of this decision is two-fold. First to be safe using the
23250 static mode, you should remove all @code{pragma Elaborate} statements.
23251 Second, when fixing circularities in existing code, you can selectively
23252 use @code{pragma Elaborate} statements to convince the static mode of
23253 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
23254 statement.
23255
23256 When using the static mode with @option{-gnatwl}, any use of
23257 @code{pragma Elaborate} will generate a warning about possible
23258 problems.
23259
23260 @node Elaboration Issues for Library Tasks
23261 @section Elaboration Issues for Library Tasks
23262 @cindex Library tasks, elaboration issues
23263 @cindex Elaboration of library tasks
23264
23265 @noindent
23266 In this section we examine special elaboration issues that arise for
23267 programs that declare library level tasks.
23268
23269 Generally the model of execution of an Ada program is that all units are
23270 elaborated, and then execution of the program starts. However, the
23271 declaration of library tasks definitely does not fit this model. The
23272 reason for this is that library tasks start as soon as they are declared
23273 (more precisely, as soon as the statement part of the enclosing package
23274 body is reached), that is to say before elaboration
23275 of the program is complete. This means that if such a task calls a
23276 subprogram, or an entry in another task, the callee may or may not be
23277 elaborated yet, and in the standard
23278 Reference Manual model of dynamic elaboration checks, you can even
23279 get timing dependent Program_Error exceptions, since there can be
23280 a race between the elaboration code and the task code.
23281
23282 The static model of elaboration in GNAT seeks to avoid all such
23283 dynamic behavior, by being conservative, and the conservative
23284 approach in this particular case is to assume that all the code
23285 in a task body is potentially executed at elaboration time if
23286 a task is declared at the library level.
23287
23288 This can definitely result in unexpected circularities. Consider
23289 the following example
23290
23291 @smallexample @c ada
23292 package Decls is
23293   task Lib_Task is
23294      entry Start;
23295   end Lib_Task;
23296
23297   type My_Int is new Integer;
23298
23299   function Ident (M : My_Int) return My_Int;
23300 end Decls;
23301
23302 with Utils;
23303 package body Decls is
23304   task body Lib_Task is
23305   begin
23306      accept Start;
23307      Utils.Put_Val (2);
23308   end Lib_Task;
23309
23310   function Ident (M : My_Int) return My_Int is
23311   begin
23312      return M;
23313   end Ident;
23314 end Decls;
23315
23316 with Decls;
23317 package Utils is
23318   procedure Put_Val (Arg : Decls.My_Int);
23319 end Utils;
23320
23321 with Text_IO;
23322 package body Utils is
23323   procedure Put_Val (Arg : Decls.My_Int) is
23324   begin
23325      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
23326   end Put_Val;
23327 end Utils;
23328
23329 with Decls;
23330 procedure Main is
23331 begin
23332    Decls.Lib_Task.Start;
23333 end;
23334 @end smallexample
23335
23336 @noindent
23337 If the above example is compiled in the default static elaboration
23338 mode, then a circularity occurs. The circularity comes from the call
23339 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
23340 this call occurs in elaboration code, we need an implicit pragma
23341 @code{Elaborate_All} for @code{Utils}. This means that not only must
23342 the spec and body of @code{Utils} be elaborated before the body
23343 of @code{Decls}, but also the spec and body of any unit that is
23344 @code{with'ed} by the body of @code{Utils} must also be elaborated before
23345 the body of @code{Decls}. This is the transitive implication of
23346 pragma @code{Elaborate_All} and it makes sense, because in general
23347 the body of @code{Put_Val} might have a call to something in a
23348 @code{with'ed} unit.
23349
23350 In this case, the body of Utils (actually its spec) @code{with's}
23351 @code{Decls}. Unfortunately this means that the body of @code{Decls}
23352 must be elaborated before itself, in case there is a call from the
23353 body of @code{Utils}.
23354
23355 Here is the exact chain of events we are worrying about:
23356
23357 @enumerate
23358 @item
23359 In the body of @code{Decls} a call is made from within the body of a library
23360 task to a subprogram in the package @code{Utils}. Since this call may
23361 occur at elaboration time (given that the task is activated at elaboration
23362 time), we have to assume the worst, i.e., that the
23363 call does happen at elaboration time.
23364
23365 @item
23366 This means that the body and spec of @code{Util} must be elaborated before
23367 the body of @code{Decls} so that this call does not cause an access before
23368 elaboration.
23369
23370 @item
23371 Within the body of @code{Util}, specifically within the body of
23372 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
23373 by this package.
23374
23375 @item
23376 One such @code{with}'ed package is package @code{Decls}, so there
23377 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
23378 In fact there is such a call in this example, but we would have to
23379 assume that there was such a call even if it were not there, since
23380 we are not supposed to write the body of @code{Decls} knowing what
23381 is in the body of @code{Utils}; certainly in the case of the
23382 static elaboration model, the compiler does not know what is in
23383 other bodies and must assume the worst.
23384
23385 @item
23386 This means that the spec and body of @code{Decls} must also be
23387 elaborated before we elaborate the unit containing the call, but
23388 that unit is @code{Decls}! This means that the body of @code{Decls}
23389 must be elaborated before itself, and that's a circularity.
23390 @end enumerate
23391
23392 @noindent
23393 Indeed, if you add an explicit pragma @code{Elaborate_All} for @code{Utils} in
23394 the body of @code{Decls} you will get a true Ada Reference Manual
23395 circularity that makes the program illegal.
23396
23397 In practice, we have found that problems with the static model of
23398 elaboration in existing code often arise from library tasks, so
23399 we must address this particular situation.
23400
23401 Note that if we compile and run the program above, using the dynamic model of
23402 elaboration (that is to say use the @option{-gnatE} switch),
23403 then it compiles, binds,
23404 links, and runs, printing the expected result of 2. Therefore in some sense
23405 the circularity here is only apparent, and we need to capture
23406 the properties of this program that  distinguish it from other library-level
23407 tasks that have real elaboration problems.
23408
23409 We have four possible answers to this question:
23410
23411 @itemize @bullet
23412
23413 @item
23414 Use the dynamic model of elaboration.
23415
23416 If we use the @option{-gnatE} switch, then as noted above, the program works.
23417 Why is this? If we examine the task body, it is apparent that the task cannot
23418 proceed past the
23419 @code{accept} statement until after elaboration has been completed, because
23420 the corresponding entry call comes from the main program, not earlier.
23421 This is why the dynamic model works here. But that's really giving
23422 up on a precise analysis, and we prefer to take this approach only if we cannot
23423 solve the
23424 problem in any other manner. So let us examine two ways to reorganize
23425 the program to avoid the potential elaboration problem.
23426
23427 @item
23428 Split library tasks into separate packages.
23429
23430 Write separate packages, so that library tasks are isolated from
23431 other declarations as much as possible. Let us look at a variation on
23432 the above program.
23433
23434 @smallexample @c ada
23435 package Decls1 is
23436   task Lib_Task is
23437      entry Start;
23438   end Lib_Task;
23439 end Decls1;
23440
23441 with Utils;
23442 package body Decls1 is
23443   task body Lib_Task is
23444   begin
23445      accept Start;
23446      Utils.Put_Val (2);
23447   end Lib_Task;
23448 end Decls1;
23449
23450 package Decls2 is
23451   type My_Int is new Integer;
23452   function Ident (M : My_Int) return My_Int;
23453 end Decls2;
23454
23455 with Utils;
23456 package body Decls2 is
23457   function Ident (M : My_Int) return My_Int is
23458   begin
23459      return M;
23460   end Ident;
23461 end Decls2;
23462
23463 with Decls2;
23464 package Utils is
23465   procedure Put_Val (Arg : Decls2.My_Int);
23466 end Utils;
23467
23468 with Text_IO;
23469 package body Utils is
23470   procedure Put_Val (Arg : Decls2.My_Int) is
23471   begin
23472      Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
23473   end Put_Val;
23474 end Utils;
23475
23476 with Decls1;
23477 procedure Main is
23478 begin
23479    Decls1.Lib_Task.Start;
23480 end;
23481 @end smallexample
23482
23483 @noindent
23484 All we have done is to split @code{Decls} into two packages, one
23485 containing the library task, and one containing everything else. Now
23486 there is no cycle, and the program compiles, binds, links and executes
23487 using the default static model of elaboration.
23488
23489 @item
23490 Declare separate task types.
23491
23492 A significant part of the problem arises because of the use of the
23493 single task declaration form. This means that the elaboration of
23494 the task type, and the elaboration of the task itself (i.e.@: the
23495 creation of the task) happen at the same time. A good rule
23496 of style in Ada is to always create explicit task types. By
23497 following the additional step of placing task objects in separate
23498 packages from the task type declaration, many elaboration problems
23499 are avoided. Here is another modified example of the example program:
23500
23501 @smallexample @c ada
23502 package Decls is
23503   task type Lib_Task_Type is
23504      entry Start;
23505   end Lib_Task_Type;
23506
23507   type My_Int is new Integer;
23508
23509   function Ident (M : My_Int) return My_Int;
23510 end Decls;
23511
23512 with Utils;
23513 package body Decls is
23514   task body Lib_Task_Type is
23515   begin
23516      accept Start;
23517      Utils.Put_Val (2);
23518   end Lib_Task_Type;
23519
23520   function Ident (M : My_Int) return My_Int is
23521   begin
23522      return M;
23523   end Ident;
23524 end Decls;
23525
23526 with Decls;
23527 package Utils is
23528   procedure Put_Val (Arg : Decls.My_Int);
23529 end Utils;
23530
23531 with Text_IO;
23532 package body Utils is
23533   procedure Put_Val (Arg : Decls.My_Int) is
23534   begin
23535      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
23536   end Put_Val;
23537 end Utils;
23538
23539 with Decls;
23540 package Declst is
23541    Lib_Task : Decls.Lib_Task_Type;
23542 end Declst;
23543
23544 with Declst;
23545 procedure Main is
23546 begin
23547    Declst.Lib_Task.Start;
23548 end;
23549 @end smallexample
23550
23551 @noindent
23552 What we have done here is to replace the @code{task} declaration in
23553 package @code{Decls} with a @code{task type} declaration. Then we
23554 introduce a separate package @code{Declst} to contain the actual
23555 task object. This separates the elaboration issues for
23556 the @code{task type}
23557 declaration, which causes no trouble, from the elaboration issues
23558 of the task object, which is also unproblematic, since it is now independent
23559 of the elaboration of  @code{Utils}.
23560 This separation of concerns also corresponds to
23561 a generally sound engineering principle of separating declarations
23562 from instances. This version of the program also compiles, binds, links,
23563 and executes, generating the expected output.
23564
23565 @item
23566 Use No_Entry_Calls_In_Elaboration_Code restriction.
23567 @cindex No_Entry_Calls_In_Elaboration_Code
23568
23569 The previous two approaches described how a program can be restructured
23570 to avoid the special problems caused by library task bodies. in practice,
23571 however, such restructuring may be difficult to apply to existing legacy code,
23572 so we must consider solutions that do not require massive rewriting.
23573
23574 Let us consider more carefully why our original sample program works
23575 under the dynamic model of elaboration. The reason is that the code
23576 in the task body blocks immediately on the @code{accept}
23577 statement. Now of course there is nothing to prohibit elaboration
23578 code from making entry calls (for example from another library level task),
23579 so we cannot tell in isolation that
23580 the task will not execute the accept statement  during elaboration.
23581
23582 However, in practice it is very unusual to see elaboration code
23583 make any entry calls, and the pattern of tasks starting
23584 at elaboration time and then immediately blocking on @code{accept} or
23585 @code{select} statements is very common. What this means is that
23586 the compiler is being too pessimistic when it analyzes the
23587 whole package body as though it might be executed at elaboration
23588 time.
23589
23590 If we know that the elaboration code contains no entry calls, (a very safe
23591 assumption most of the time, that could almost be made the default
23592 behavior), then we can compile all units of the program under control
23593 of the following configuration pragma:
23594
23595 @smallexample
23596 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
23597 @end smallexample
23598
23599 @noindent
23600 This pragma can be placed in the @file{gnat.adc} file in the usual
23601 manner. If we take our original unmodified program and compile it
23602 in the presence of a @file{gnat.adc} containing the above pragma,
23603 then once again, we can compile, bind, link, and execute, obtaining
23604 the expected result. In the presence of this pragma, the compiler does
23605 not trace calls in a task body, that appear after the first @code{accept}
23606 or @code{select} statement, and therefore does not report a potential
23607 circularity in the original program.
23608
23609 The compiler will check to the extent it can that the above
23610 restriction is not violated, but it is not always possible to do a
23611 complete check at compile time, so it is important to use this
23612 pragma only if the stated restriction is in fact met, that is to say
23613 no task receives an entry call before elaboration of all units is completed.
23614
23615 @end itemize
23616
23617 @node Mixing Elaboration Models
23618 @section Mixing Elaboration Models
23619 @noindent
23620 So far, we have assumed that the entire program is either compiled
23621 using the dynamic model or static model, ensuring consistency. It
23622 is possible to mix the two models, but rules have to be followed
23623 if this mixing is done to ensure that elaboration checks are not
23624 omitted.
23625
23626 The basic rule is that @emph{a unit compiled with the static model cannot
23627 be @code{with'ed} by a unit compiled with the dynamic model}. The
23628 reason for this is that in the static model, a unit assumes that
23629 its clients guarantee to use (the equivalent of) pragma
23630 @code{Elaborate_All} so that no elaboration checks are required
23631 in inner subprograms, and this assumption is violated if the
23632 client is compiled with dynamic checks.
23633
23634 The precise rule is as follows. A unit that is compiled with dynamic
23635 checks can only @code{with} a unit that meets at least one of the
23636 following criteria:
23637
23638 @itemize @bullet
23639
23640 @item
23641 The @code{with'ed} unit is itself compiled with dynamic elaboration
23642 checks (that is with the @option{-gnatE} switch.
23643
23644 @item
23645 The @code{with'ed} unit is an internal GNAT implementation unit from
23646 the System, Interfaces, Ada, or GNAT hierarchies.
23647
23648 @item
23649 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
23650
23651 @item
23652 The @code{with'ing} unit (that is the client) has an explicit pragma
23653 @code{Elaborate_All} for the @code{with'ed} unit.
23654
23655 @end itemize
23656
23657 @noindent
23658 If this rule is violated, that is if a unit with dynamic elaboration
23659 checks @code{with's} a unit that does not meet one of the above four
23660 criteria, then the binder (@code{gnatbind}) will issue a warning
23661 similar to that in the following example:
23662
23663 @smallexample
23664 warning: "x.ads" has dynamic elaboration checks and with's
23665 warning:   "y.ads" which has static elaboration checks
23666 @end smallexample
23667
23668 @noindent
23669 These warnings indicate that the rule has been violated, and that as a result
23670 elaboration checks may be missed in the resulting executable file.
23671 This warning may be suppressed using the @option{-ws} binder switch
23672 in the usual manner.
23673
23674 One useful application of this mixing rule is in the case of a subsystem
23675 which does not itself @code{with} units from the remainder of the
23676 application. In this case, the entire subsystem can be compiled with
23677 dynamic checks to resolve a circularity in the subsystem, while
23678 allowing the main application that uses this subsystem to be compiled
23679 using the more reliable default static model.
23680
23681 @node What to Do If the Default Elaboration Behavior Fails
23682 @section What to Do If the Default Elaboration Behavior Fails
23683
23684 @noindent
23685 If the binder cannot find an acceptable order, it outputs detailed
23686 diagnostics. For example:
23687 @smallexample
23688 @group
23689 @iftex
23690 @leftskip=0cm
23691 @end iftex
23692 error: elaboration circularity detected
23693 info:   "proc (body)" must be elaborated before "pack (body)"
23694 info:     reason: Elaborate_All probably needed in unit "pack (body)"
23695 info:     recompile "pack (body)" with -gnatwl
23696 info:                             for full details
23697 info:       "proc (body)"
23698 info:         is needed by its spec:
23699 info:       "proc (spec)"
23700 info:         which is withed by:
23701 info:       "pack (body)"
23702 info:  "pack (body)" must be elaborated before "proc (body)"
23703 info:     reason: pragma Elaborate in unit "proc (body)"
23704 @end group
23705
23706 @end smallexample
23707
23708 @noindent
23709 In this case we have a cycle that the binder cannot break. On the one
23710 hand, there is an explicit pragma Elaborate in @code{proc} for
23711 @code{pack}. This means that the body of @code{pack} must be elaborated
23712 before the body of @code{proc}. On the other hand, there is elaboration
23713 code in @code{pack} that calls a subprogram in @code{proc}. This means
23714 that for maximum safety, there should really be a pragma
23715 Elaborate_All in @code{pack} for @code{proc} which would require that
23716 the body of @code{proc} be elaborated before the body of
23717 @code{pack}. Clearly both requirements cannot be satisfied.
23718 Faced with a circularity of this kind, you have three different options.
23719
23720 @table @asis
23721 @item Fix the program
23722 The most desirable option from the point of view of long-term maintenance
23723 is to rearrange the program so that the elaboration problems are avoided.
23724 One useful technique is to place the elaboration code into separate
23725 child packages. Another is to move some of the initialization code to
23726 explicitly called subprograms, where the program controls the order
23727 of initialization explicitly. Although this is the most desirable option,
23728 it may be impractical and involve too much modification, especially in
23729 the case of complex legacy code.
23730
23731 @item Perform dynamic checks
23732 If the compilations are done using the
23733 @option{-gnatE}
23734 (dynamic elaboration check) switch, then GNAT behaves in a quite different
23735 manner. Dynamic checks are generated for all calls that could possibly result
23736 in raising an exception. With this switch, the compiler does not generate
23737 implicit @code{Elaborate} or @code{Elaborate_All} pragmas. The behavior then is
23738 exactly as specified in the @cite{Ada Reference Manual}.
23739 The binder will generate
23740 an executable program that may or may not raise @code{Program_Error}, and then
23741 it is the programmer's job to ensure that it does not raise an exception. Note
23742 that it is important to compile all units with the switch, it cannot be used
23743 selectively.
23744
23745 @item Suppress checks
23746 The drawback of dynamic checks is that they generate a
23747 significant overhead at run time, both in space and time. If you
23748 are absolutely sure that your program cannot raise any elaboration
23749 exceptions, and you still want to use the dynamic elaboration model,
23750 then you can use the configuration pragma
23751 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
23752 example this pragma could be placed in the @file{gnat.adc} file.
23753
23754 @item Suppress checks selectively
23755 When you know that certain calls or instantiations in elaboration code cannot
23756 possibly lead to an elaboration error, and the binder nevertheless complains
23757 about implicit @code{Elaborate} and @code{Elaborate_All} pragmas that lead to
23758 elaboration circularities, it is possible to remove those warnings locally and
23759 obtain a program that will bind. Clearly this can be unsafe, and it is the
23760 responsibility of the programmer to make sure that the resulting program has no
23761 elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can be
23762 used with different granularity to suppress warnings and break elaboration
23763 circularities:
23764
23765 @itemize @bullet
23766 @item
23767 Place the pragma that names the called subprogram in the declarative part
23768 that contains the call.
23769
23770 @item
23771 Place the pragma in the declarative part, without naming an entity. This
23772 disables warnings on all calls in the corresponding  declarative region.
23773
23774 @item
23775 Place the pragma in the package spec that declares the called subprogram,
23776 and name the subprogram. This disables warnings on all elaboration calls to
23777 that subprogram.
23778
23779 @item
23780 Place the pragma in the package spec that declares the called subprogram,
23781 without naming any entity. This disables warnings on all elaboration calls to
23782 all subprograms declared in this spec.
23783
23784 @item Use Pragma Elaborate
23785 As previously described in section @xref{Treatment of Pragma Elaborate},
23786 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
23787 that no elaboration checks are required on calls to the designated unit.
23788 There may be cases in which the caller knows that no transitive calls
23789 can occur, so that a @code{pragma Elaborate} will be sufficient in a
23790 case where @code{pragma Elaborate_All} would cause a circularity.
23791 @end itemize
23792
23793 @noindent
23794 These five cases are listed in order of decreasing safety, and therefore
23795 require increasing programmer care in their application. Consider the
23796 following program:
23797
23798 @smallexample @c adanocomment
23799 package Pack1 is
23800   function F1 return Integer;
23801   X1 : Integer;
23802 end Pack1;
23803
23804 package Pack2 is
23805   function F2 return Integer;
23806   function Pure (x : integer) return integer;
23807   --  pragma Suppress (Elaboration_Check, On => Pure);  -- (3)
23808   --  pragma Suppress (Elaboration_Check);              -- (4)
23809 end Pack2;
23810
23811 with Pack2;
23812 package body Pack1 is
23813   function F1 return Integer is
23814   begin
23815     return 100;
23816   end F1;
23817   Val : integer := Pack2.Pure (11);    --  Elab. call (1)
23818 begin
23819   declare
23820     --  pragma Suppress(Elaboration_Check, Pack2.F2);   -- (1)
23821     --  pragma Suppress(Elaboration_Check);             -- (2)
23822   begin
23823     X1 := Pack2.F2 + 1;                --  Elab. call (2)
23824   end;
23825 end Pack1;
23826
23827 with Pack1;
23828 package body Pack2 is
23829   function F2 return Integer is
23830   begin
23831      return Pack1.F1;
23832   end F2;
23833   function Pure (x : integer) return integer is
23834   begin
23835      return x ** 3 - 3 * x;
23836   end;
23837 end Pack2;
23838
23839 with Pack1, Ada.Text_IO;
23840 procedure Proc3 is
23841 begin
23842   Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
23843 end Proc3;
23844 @end smallexample
23845 In the absence of any pragmas, an attempt to bind this program produces
23846 the following diagnostics:
23847 @smallexample
23848 @group
23849 @iftex
23850 @leftskip=.5cm
23851 @end iftex
23852 error: elaboration circularity detected
23853 info:    "pack1 (body)" must be elaborated before "pack1 (body)"
23854 info:       reason: Elaborate_All probably needed in unit "pack1 (body)"
23855 info:       recompile "pack1 (body)" with -gnatwl for full details
23856 info:          "pack1 (body)"
23857 info:             must be elaborated along with its spec:
23858 info:          "pack1 (spec)"
23859 info:             which is withed by:
23860 info:          "pack2 (body)"
23861 info:             which must be elaborated along with its spec:
23862 info:          "pack2 (spec)"
23863 info:             which is withed by:
23864 info:          "pack1 (body)"
23865 @end group
23866 @end smallexample
23867 The sources of the circularity are the two calls to @code{Pack2.Pure} and
23868 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
23869 F2 is safe, even though F2 calls F1, because the call appears after the
23870 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
23871 remove the warning on the call. It is also possible to use pragma (2)
23872 because there are no other potentially unsafe calls in the block.
23873
23874 @noindent
23875 The call to @code{Pure} is safe because this function does not depend on the
23876 state of @code{Pack2}. Therefore any call to this function is safe, and it
23877 is correct to place pragma (3) in the corresponding package spec.
23878
23879 @noindent
23880 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
23881 warnings on all calls to functions declared therein. Note that this is not
23882 necessarily safe, and requires more detailed examination of the subprogram
23883 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
23884 be already elaborated.
23885 @end table
23886
23887 @noindent
23888 It is hard to generalize on which of these four approaches should be
23889 taken. Obviously if it is possible to fix the program so that the default
23890 treatment works, this is preferable, but this may not always be practical.
23891 It is certainly simple enough to use
23892 @option{-gnatE}
23893 but the danger in this case is that, even if the GNAT binder
23894 finds a correct elaboration order, it may not always do so,
23895 and certainly a binder from another Ada compiler might not. A
23896 combination of testing and analysis (for which the warnings generated
23897 with the
23898 @option{-gnatwl}
23899 switch can be useful) must be used to ensure that the program is free
23900 of errors. One switch that is useful in this testing is the
23901 @option{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
23902 switch for
23903 @code{gnatbind}.
23904 Normally the binder tries to find an order that has the best chance
23905 of avoiding elaboration problems. However, if this switch is used, the binder
23906 plays a devil's advocate role, and tries to choose the order that
23907 has the best chance of failing. If your program works even with this
23908 switch, then it has a better chance of being error free, but this is still
23909 not a guarantee.
23910
23911 For an example of this approach in action, consider the C-tests (executable
23912 tests) from the ACVC suite. If these are compiled and run with the default
23913 treatment, then all but one of them succeed without generating any error
23914 diagnostics from the binder. However, there is one test that fails, and
23915 this is not surprising, because the whole point of this test is to ensure
23916 that the compiler can handle cases where it is impossible to determine
23917 a correct order statically, and it checks that an exception is indeed
23918 raised at run time.
23919
23920 This one test must be compiled and run using the
23921 @option{-gnatE}
23922 switch, and then it passes. Alternatively, the entire suite can
23923 be run using this switch. It is never wrong to run with the dynamic
23924 elaboration switch if your code is correct, and we assume that the
23925 C-tests are indeed correct (it is less efficient, but efficiency is
23926 not a factor in running the ACVC tests.)
23927
23928 @node Elaboration for Access-to-Subprogram Values
23929 @section Elaboration for Access-to-Subprogram Values
23930 @cindex Access-to-subprogram
23931
23932 @noindent
23933 Access-to-subprogram types (introduced in Ada 95) complicate
23934 the handling of elaboration. The trouble is that it becomes
23935 impossible to tell at compile time which procedure
23936 is being called. This means that it is not possible for the binder
23937 to analyze the elaboration requirements in this case.
23938
23939 If at the point at which the access value is created
23940 (i.e., the evaluation of @code{P'Access} for a subprogram @code{P}),
23941 the body of the subprogram is
23942 known to have been elaborated, then the access value is safe, and its use
23943 does not require a check. This may be achieved by appropriate arrangement
23944 of the order of declarations if the subprogram is in the current unit,
23945 or, if the subprogram is in another unit, by using pragma
23946 @code{Pure}, @code{Preelaborate}, or @code{Elaborate_Body}
23947 on the referenced unit.
23948
23949 If the referenced body is not known to have been elaborated at the point
23950 the access value is created, then any use of the access value must do a
23951 dynamic check, and this dynamic check will fail and raise a
23952 @code{Program_Error} exception if the body has not been elaborated yet.
23953 GNAT will generate the necessary checks, and in addition, if the
23954 @option{-gnatwl}
23955 switch is set, will generate warnings that such checks are required.
23956
23957 The use of dynamic dispatching for tagged types similarly generates
23958 a requirement for dynamic checks, and premature calls to any primitive
23959 operation of a tagged type before the body of the operation has been
23960 elaborated, will result in the raising of @code{Program_Error}.
23961
23962 @node Summary of Procedures for Elaboration Control
23963 @section Summary of Procedures for Elaboration Control
23964 @cindex Elaboration control
23965
23966 @noindent
23967 First, compile your program with the default options, using none of
23968 the special elaboration control switches. If the binder successfully
23969 binds your program, then you can be confident that, apart from issues
23970 raised by the use of access-to-subprogram types and dynamic dispatching,
23971 the program is free of elaboration errors. If it is important that the
23972 program be portable, then use the
23973 @option{-gnatwl}
23974 switch to generate warnings about missing @code{Elaborate} or
23975 @code{Elaborate_All} pragmas, and supply the missing pragmas.
23976
23977 If the program fails to bind using the default static elaboration
23978 handling, then you can fix the program to eliminate the binder
23979 message, or recompile the entire program with the
23980 @option{-gnatE} switch to generate dynamic elaboration checks,
23981 and, if you are sure there really are no elaboration problems,
23982 use a global pragma @code{Suppress (Elaboration_Check)}.
23983
23984 @node Other Elaboration Order Considerations
23985 @section Other Elaboration Order Considerations
23986 @noindent
23987 This section has been entirely concerned with the issue of finding a valid
23988 elaboration order, as defined by the Ada Reference Manual. In a case
23989 where several elaboration orders are valid, the task is to find one
23990 of the possible valid elaboration orders (and the static model in GNAT
23991 will ensure that this is achieved).
23992
23993 The purpose of the elaboration rules in the Ada Reference Manual is to
23994 make sure that no entity is accessed before it has been elaborated. For
23995 a subprogram, this means that the spec and body must have been elaborated
23996 before the subprogram is called. For an object, this means that the object
23997 must have been elaborated before its value is read or written. A violation
23998 of either of these two requirements is an access before elaboration order,
23999 and this section has been all about avoiding such errors.
24000
24001 In the case where more than one order of elaboration is possible, in the
24002 sense that access before elaboration errors are avoided, then any one of
24003 the orders is ``correct'' in the sense that it meets the requirements of
24004 the Ada Reference Manual, and no such error occurs.
24005
24006 However, it may be the case for a given program, that there are
24007 constraints on the order of elaboration that come not from consideration
24008 of avoiding elaboration errors, but rather from extra-lingual logic
24009 requirements. Consider this example:
24010
24011 @smallexample @c ada
24012 with Init_Constants;
24013 package Constants is
24014    X : Integer := 0;
24015    Y : Integer := 0;
24016 end Constants;
24017
24018 package Init_Constants is
24019    procedure P; -- require a body
24020 end Init_Constants;
24021
24022 with Constants;
24023 package body Init_Constants is
24024    procedure P is begin null; end;
24025 begin
24026    Constants.X := 3;
24027    Constants.Y := 4;
24028 end Init_Constants;
24029
24030 with Constants;
24031 package Calc is
24032    Z : Integer := Constants.X + Constants.Y;
24033 end Calc;
24034
24035 with Calc;
24036 with Text_IO; use Text_IO;
24037 procedure Main is
24038 begin
24039    Put_Line (Calc.Z'Img);
24040 end Main;
24041 @end smallexample
24042
24043 @noindent
24044 In this example, there is more than one valid order of elaboration. For
24045 example both the following are correct orders:
24046
24047 @smallexample
24048 Init_Constants spec
24049 Constants spec
24050 Calc spec
24051 Init_Constants body
24052 Main body
24053
24054   and
24055
24056 Init_Constants spec
24057 Init_Constants body
24058 Constants spec
24059 Calc spec
24060 Main body
24061 @end smallexample
24062
24063 @noindent
24064 There is no language rule to prefer one or the other, both are correct
24065 from an order of elaboration point of view. But the programmatic effects
24066 of the two orders are very different. In the first, the elaboration routine
24067 of @code{Calc} initializes @code{Z} to zero, and then the main program
24068 runs with this value of zero. But in the second order, the elaboration
24069 routine of @code{Calc} runs after the body of Init_Constants has set
24070 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
24071 runs.
24072
24073 One could perhaps by applying pretty clever non-artificial intelligence
24074 to the situation guess that it is more likely that the second order of
24075 elaboration is the one desired, but there is no formal linguistic reason
24076 to prefer one over the other. In fact in this particular case, GNAT will
24077 prefer the second order, because of the rule that bodies are elaborated
24078 as soon as possible, but it's just luck that this is what was wanted
24079 (if indeed the second order was preferred).
24080
24081 If the program cares about the order of elaboration routines in a case like
24082 this, it is important to specify the order required. In this particular
24083 case, that could have been achieved by adding to the spec of Calc:
24084
24085 @smallexample @c ada
24086 pragma Elaborate_All (Constants);
24087 @end smallexample
24088
24089 @noindent
24090 which requires that the body (if any) and spec of @code{Constants},
24091 as well as the body and spec of any unit @code{with}'ed by
24092 @code{Constants} be elaborated before @code{Calc} is elaborated.
24093
24094 Clearly no automatic method can always guess which alternative you require,
24095 and if you are working with legacy code that had constraints of this kind
24096 which were not properly specified by adding @code{Elaborate} or
24097 @code{Elaborate_All} pragmas, then indeed it is possible that two different
24098 compilers can choose different orders.
24099
24100 However, GNAT does attempt to diagnose the common situation where there
24101 are uninitialized variables in the visible part of a package spec, and the
24102 corresponding package body has an elaboration block that directly or
24103 indirectly initialized one or more of these variables. This is the situation
24104 in which a pragma Elaborate_Body is usually desirable, and GNAT will generate
24105 a warning that suggests this addition if it detects this situation.
24106
24107 The @code{gnatbind}
24108 @option{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
24109 out problems. This switch causes bodies to be elaborated as late as possible
24110 instead of as early as possible. In the example above, it would have forced
24111 the choice of the first elaboration order. If you get different results
24112 when using this switch, and particularly if one set of results is right,
24113 and one is wrong as far as you are concerned, it shows that you have some
24114 missing @code{Elaborate} pragmas. For the example above, we have the
24115 following output:
24116
24117 @smallexample
24118 gnatmake -f -q main
24119 main
24120  7
24121 gnatmake -f -q main -bargs -p
24122 main
24123  0
24124 @end smallexample
24125
24126 @noindent
24127 It is of course quite unlikely that both these results are correct, so
24128 it is up to you in a case like this to investigate the source of the
24129 difference, by looking at the two elaboration orders that are chosen,
24130 and figuring out which is correct, and then adding the necessary
24131 @code{Elaborate} or @code{Elaborate_All} pragmas to ensure the desired order.
24132
24133
24134
24135 @c *******************************
24136 @node Conditional Compilation
24137 @appendix Conditional Compilation
24138 @c *******************************
24139 @cindex Conditional compilation
24140
24141 @noindent
24142 It is often necessary to arrange for a single source program
24143 to serve multiple purposes, where it is compiled in different
24144 ways to achieve these different goals. Some examples of the
24145 need for this feature are
24146
24147 @itemize @bullet
24148 @item  Adapting a program to a different hardware environment
24149 @item  Adapting a program to a different target architecture
24150 @item  Turning debugging features on and off
24151 @item  Arranging for a program to compile with different compilers
24152 @end itemize
24153
24154 @noindent
24155 In C, or C++, the typical approach would be to use the preprocessor
24156 that is defined as part of the language. The Ada language does not
24157 contain such a feature. This is not an oversight, but rather a very
24158 deliberate design decision, based on the experience that overuse of
24159 the preprocessing features in C and C++ can result in programs that
24160 are extremely difficult to maintain. For example, if we have ten
24161 switches that can be on or off, this means that there are a thousand
24162 separate programs, any one of which might not even be syntactically
24163 correct, and even if syntactically correct, the resulting program
24164 might not work correctly. Testing all combinations can quickly become
24165 impossible.
24166
24167 Nevertheless, the need to tailor programs certainly exists, and in
24168 this Appendix we will discuss how this can
24169 be achieved using Ada in general, and GNAT in particular.
24170
24171 @menu
24172 * Use of Boolean Constants::
24173 * Debugging - A Special Case::
24174 * Conditionalizing Declarations::
24175 * Use of Alternative Implementations::
24176 * Preprocessing::
24177 @end menu
24178
24179 @node Use of Boolean Constants
24180 @section Use of Boolean Constants
24181
24182 @noindent
24183 In the case where the difference is simply which code
24184 sequence is executed, the cleanest solution is to use Boolean
24185 constants to control which code is executed.
24186
24187 @smallexample @c ada
24188 @group
24189 FP_Initialize_Required : constant Boolean := True;
24190 @dots{}
24191 if FP_Initialize_Required then
24192 @dots{}
24193 end if;
24194 @end group
24195 @end smallexample
24196
24197 @noindent
24198 Not only will the code inside the @code{if} statement not be executed if
24199 the constant Boolean is @code{False}, but it will also be completely
24200 deleted from the program.
24201 However, the code is only deleted after the @code{if} statement
24202 has been checked for syntactic and semantic correctness.
24203 (In contrast, with preprocessors the code is deleted before the
24204 compiler ever gets to see it, so it is not checked until the switch
24205 is turned on.)
24206 @cindex Preprocessors (contrasted with conditional compilation)
24207
24208 Typically the Boolean constants will be in a separate package,
24209 something like:
24210
24211 @smallexample @c ada
24212 @group
24213 package Config is
24214    FP_Initialize_Required : constant Boolean := True;
24215    Reset_Available        : constant Boolean := False;
24216    @dots{}
24217 end Config;
24218 @end group
24219 @end smallexample
24220
24221 @noindent
24222 The @code{Config} package exists in multiple forms for the various targets,
24223 with an appropriate script selecting the version of @code{Config} needed.
24224 Then any other unit requiring conditional compilation can do a @code{with}
24225 of @code{Config} to make the constants visible.
24226
24227
24228 @node Debugging - A Special Case
24229 @section Debugging - A Special Case
24230
24231 @noindent
24232 A common use of conditional code is to execute statements (for example
24233 dynamic checks, or output of intermediate results) under control of a
24234 debug switch, so that the debugging behavior can be turned on and off.
24235 This can be done using a Boolean constant to control whether the code
24236 is active:
24237
24238 @smallexample @c ada
24239 @group
24240 if Debugging then
24241    Put_Line ("got to the first stage!");
24242 end if;
24243 @end group
24244 @end smallexample
24245
24246 @noindent
24247 or
24248
24249 @smallexample @c ada
24250 @group
24251 if Debugging and then Temperature > 999.0 then
24252    raise Temperature_Crazy;
24253 end if;
24254 @end group
24255 @end smallexample
24256
24257 @noindent
24258 Since this is a common case, there are special features to deal with
24259 this in a convenient manner. For the case of tests, Ada 2005 has added
24260 a pragma @code{Assert} that can be used for such tests. This pragma is modeled
24261 @cindex pragma @code{Assert}
24262 on the @code{Assert} pragma that has always been available in GNAT, so this
24263 feature may be used with GNAT even if you are not using Ada 2005 features.
24264 The use of pragma @code{Assert} is described in
24265 @ref{Pragma Assert,,, gnat_rm, GNAT Reference Manual}, but as an
24266 example, the last test could be written:
24267
24268 @smallexample @c ada
24269 pragma Assert (Temperature <= 999.0, "Temperature Crazy");
24270 @end smallexample
24271
24272 @noindent
24273 or simply
24274
24275 @smallexample @c ada
24276 pragma Assert (Temperature <= 999.0);
24277 @end smallexample
24278
24279 @noindent
24280 In both cases, if assertions are active and the temperature is excessive,
24281 the exception @code{Assert_Failure} will be raised, with the given string in
24282 the first case or a string indicating the location of the pragma in the second
24283 case used as the exception message.
24284
24285 You can turn assertions on and off by using the @code{Assertion_Policy}
24286 pragma.
24287 @cindex pragma @code{Assertion_Policy}
24288 This is an Ada 2005 pragma which is implemented in all modes by
24289 GNAT, but only in the latest versions of GNAT which include Ada 2005
24290 capability. Alternatively, you can use the @option{-gnata} switch
24291 @cindex @option{-gnata} switch
24292 to enable assertions from the command line (this is recognized by all versions
24293 of GNAT).
24294
24295 For the example above with the @code{Put_Line}, the GNAT-specific pragma
24296 @code{Debug} can be used:
24297 @cindex pragma @code{Debug}
24298
24299 @smallexample @c ada
24300 pragma Debug (Put_Line ("got to the first stage!"));
24301 @end smallexample
24302
24303 @noindent
24304 If debug pragmas are enabled, the argument, which must be of the form of
24305 a procedure call, is executed (in this case, @code{Put_Line} will be called).
24306 Only one call can be present, but of course a special debugging procedure
24307 containing any code you like can be included in the program and then
24308 called in a pragma @code{Debug} argument as needed.
24309
24310 One advantage of pragma @code{Debug} over the @code{if Debugging then}
24311 construct is that pragma @code{Debug} can appear in declarative contexts,
24312 such as at the very beginning of a procedure, before local declarations have
24313 been elaborated.
24314
24315 Debug pragmas are enabled using either the @option{-gnata} switch that also
24316 controls assertions, or with a separate Debug_Policy pragma.
24317 @cindex pragma @code{Debug_Policy}
24318 The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
24319 in Ada 95 and Ada 83 programs as well), and is analogous to
24320 pragma @code{Assertion_Policy} to control assertions.
24321
24322 @code{Assertion_Policy} and @code{Debug_Policy} are configuration pragmas,
24323 and thus they can appear in @file{gnat.adc} if you are not using a
24324 project file, or in the file designated to contain configuration pragmas
24325 in a project file.
24326 They then apply to all subsequent compilations. In practice the use of
24327 the @option{-gnata} switch is often the most convenient method of controlling
24328 the status of these pragmas.
24329
24330 Note that a pragma is not a statement, so in contexts where a statement
24331 sequence is required, you can't just write a pragma on its own. You have
24332 to add a @code{null} statement.
24333
24334 @smallexample @c ada
24335 @group
24336 if @dots{} then
24337    @dots{} -- some statements
24338 else
24339    pragma Assert (Num_Cases < 10);
24340    null;
24341 end if;
24342 @end group
24343 @end smallexample
24344
24345
24346 @node Conditionalizing Declarations
24347 @section Conditionalizing Declarations
24348
24349 @noindent
24350 In some cases, it may be necessary to conditionalize declarations to meet
24351 different requirements. For example we might want a bit string whose length
24352 is set to meet some hardware message requirement.
24353
24354 In some cases, it may be possible to do this using declare blocks controlled
24355 by conditional constants:
24356
24357 @smallexample @c ada
24358 @group
24359 if Small_Machine then
24360    declare
24361       X : Bit_String (1 .. 10);
24362    begin
24363       @dots{}
24364    end;
24365 else
24366    declare
24367       X : Large_Bit_String (1 .. 1000);
24368    begin
24369       @dots{}
24370    end;
24371 end if;
24372 @end group
24373 @end smallexample
24374
24375 @noindent
24376 Note that in this approach, both declarations are analyzed by the
24377 compiler so this can only be used where both declarations are legal,
24378 even though one of them will not be used.
24379
24380 Another approach is to define integer constants, e.g.@: @code{Bits_Per_Word},
24381 or Boolean constants, e.g.@: @code{Little_Endian}, and then write declarations
24382 that are parameterized by these constants. For example
24383
24384 @smallexample @c ada
24385 @group
24386 for Rec use
24387   Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
24388 end record;
24389 @end group
24390 @end smallexample
24391
24392 @noindent
24393 If @code{Bits_Per_Word} is set to 32, this generates either
24394
24395 @smallexample @c ada
24396 @group
24397 for Rec use
24398   Field1 at 0 range 0 .. 32;
24399 end record;
24400 @end group
24401 @end smallexample
24402
24403 @noindent
24404 for the big endian case, or
24405
24406 @smallexample @c ada
24407 @group
24408 for Rec use record
24409   Field1 at 0 range 10 .. 32;
24410 end record;
24411 @end group
24412 @end smallexample
24413
24414 @noindent
24415 for the little endian case. Since a powerful subset of Ada expression
24416 notation is usable for creating static constants, clever use of this
24417 feature can often solve quite difficult problems in conditionalizing
24418 compilation (note incidentally that in Ada 95, the little endian
24419 constant was introduced as @code{System.Default_Bit_Order}, so you do not
24420 need to define this one yourself).
24421
24422
24423 @node Use of Alternative Implementations
24424 @section Use of Alternative Implementations
24425
24426 @noindent
24427 In some cases, none of the approaches described above are adequate. This
24428 can occur for example if the set of declarations required is radically
24429 different for two different configurations.
24430
24431 In this situation, the official Ada way of dealing with conditionalizing
24432 such code is to write separate units for the different cases. As long as
24433 this does not result in excessive duplication of code, this can be done
24434 without creating maintenance problems. The approach is to share common
24435 code as far as possible, and then isolate the code and declarations
24436 that are different. Subunits are often a convenient method for breaking
24437 out a piece of a unit that is to be conditionalized, with separate files
24438 for different versions of the subunit for different targets, where the
24439 build script selects the right one to give to the compiler.
24440 @cindex Subunits (and conditional compilation)
24441
24442 As an example, consider a situation where a new feature in Ada 2005
24443 allows something to be done in a really nice way. But your code must be able
24444 to compile with an Ada 95 compiler. Conceptually you want to say:
24445
24446 @smallexample @c ada
24447 @group
24448 if Ada_2005 then
24449    @dots{} neat Ada 2005 code
24450 else
24451    @dots{} not quite as neat Ada 95 code
24452 end if;
24453 @end group
24454 @end smallexample
24455
24456 @noindent
24457 where @code{Ada_2005} is a Boolean constant.
24458
24459 But this won't work when @code{Ada_2005} is set to @code{False},
24460 since the @code{then} clause will be illegal for an Ada 95 compiler.
24461 (Recall that although such unreachable code would eventually be deleted
24462 by the compiler, it still needs to be legal.  If it uses features
24463 introduced in Ada 2005, it will be illegal in Ada 95.)
24464
24465 So instead we write
24466
24467 @smallexample @c ada
24468 procedure Insert is separate;
24469 @end smallexample
24470
24471 @noindent
24472 Then we have two files for the subunit @code{Insert}, with the two sets of
24473 code.
24474 If the package containing this is called @code{File_Queries}, then we might
24475 have two files
24476
24477 @itemize @bullet
24478 @item    @file{file_queries-insert-2005.adb}
24479 @item    @file{file_queries-insert-95.adb}
24480 @end itemize
24481
24482 @noindent
24483 and the build script renames the appropriate file to
24484
24485 @smallexample
24486 file_queries-insert.adb
24487 @end smallexample
24488
24489 @noindent
24490 and then carries out the compilation.
24491
24492 This can also be done with project files' naming schemes. For example:
24493
24494 @smallexample @c project
24495 For Body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
24496 @end smallexample
24497
24498 @noindent
24499 Note also that with project files it is desirable to use a different extension
24500 than @file{ads} / @file{adb} for alternative versions. Otherwise a naming
24501 conflict may arise through another commonly used feature: to declare as part
24502 of the project a set of directories containing all the sources obeying the
24503 default naming scheme.
24504
24505 The use of alternative units is certainly feasible in all situations,
24506 and for example the Ada part of the GNAT run-time is conditionalized
24507 based on the target architecture using this approach. As a specific example,
24508 consider the implementation of the AST feature in VMS. There is one
24509 spec:
24510
24511 @smallexample
24512 s-asthan.ads
24513 @end smallexample
24514
24515 @noindent
24516 which is the same for all architectures, and three bodies:
24517
24518 @table @file
24519 @item    s-asthan.adb
24520 used for all non-VMS operating systems
24521 @item    s-asthan-vms-alpha.adb
24522 used for VMS on the Alpha
24523 @item    s-asthan-vms-ia64.adb
24524 used for VMS on the ia64
24525 @end table
24526
24527 @noindent
24528 The dummy version @file{s-asthan.adb} simply raises exceptions noting that
24529 this operating system feature is not available, and the two remaining
24530 versions interface with the corresponding versions of VMS to provide
24531 VMS-compatible AST handling. The GNAT build script knows the architecture
24532 and operating system, and automatically selects the right version,
24533 renaming it if necessary to @file{s-asthan.adb} before the run-time build.
24534
24535 Another style for arranging alternative implementations is through Ada's
24536 access-to-subprogram facility.
24537 In case some functionality is to be conditionally included,
24538 you can declare an access-to-procedure variable @code{Ref} that is initialized
24539 to designate a ``do nothing'' procedure, and then invoke @code{Ref.all}
24540 when appropriate.
24541 In some library package, set @code{Ref} to @code{Proc'Access} for some
24542 procedure @code{Proc} that performs the relevant processing.
24543 The initialization only occurs if the library package is included in the
24544 program.
24545 The same idea can also be implemented using tagged types and dispatching
24546 calls.
24547
24548
24549 @node Preprocessing
24550 @section Preprocessing
24551 @cindex Preprocessing
24552
24553 @noindent
24554 Although it is quite possible to conditionalize code without the use of
24555 C-style preprocessing, as described earlier in this section, it is
24556 nevertheless convenient in some cases to use the C approach. Moreover,
24557 older Ada compilers have often provided some preprocessing capability,
24558 so legacy code may depend on this approach, even though it is not
24559 standard.
24560
24561 To accommodate such use, GNAT provides a preprocessor (modeled to a large
24562 extent on the various preprocessors that have been used
24563 with legacy code on other compilers, to enable easier transition).
24564
24565 The preprocessor may be used in two separate modes. It can be used quite
24566 separately from the compiler, to generate a separate output source file
24567 that is then fed to the compiler as a separate step. This is the
24568 @code{gnatprep} utility, whose use is fully described in
24569 @ref{Preprocessing Using gnatprep}.
24570 @cindex @code{gnatprep}
24571
24572 The preprocessing language allows such constructs as
24573
24574 @smallexample
24575 @group
24576 #if DEBUG or PRIORITY > 4 then
24577    bunch of declarations
24578 #else
24579    completely different bunch of declarations
24580 #end if;
24581 @end group
24582 @end smallexample
24583
24584 @noindent
24585 The values of the symbols @code{DEBUG} and @code{PRIORITY} can be
24586 defined either on the command line or in a separate file.
24587
24588 The other way of running the preprocessor is even closer to the C style and
24589 often more convenient. In this approach the preprocessing is integrated into
24590 the compilation process. The compiler is fed the preprocessor input which
24591 includes @code{#if} lines etc, and then the compiler carries out the
24592 preprocessing internally and processes the resulting output.
24593 For more details on this approach, see @ref{Integrated Preprocessing}.
24594
24595
24596 @c *******************************
24597 @node Inline Assembler
24598 @appendix Inline Assembler
24599 @c *******************************
24600
24601 @noindent
24602 If you need to write low-level software that interacts directly
24603 with the hardware, Ada provides two ways to incorporate assembly
24604 language code into your program.  First, you can import and invoke
24605 external routines written in assembly language, an Ada feature fully
24606 supported by GNAT@.  However, for small sections of code it may be simpler
24607 or more efficient to include assembly language statements directly
24608 in your Ada source program, using the facilities of the implementation-defined
24609 package @code{System.Machine_Code}, which incorporates the gcc
24610 Inline Assembler.  The Inline Assembler approach offers a number of advantages,
24611 including the following:
24612
24613 @itemize @bullet
24614 @item No need to use non-Ada tools
24615 @item Consistent interface over different targets
24616 @item Automatic usage of the proper calling conventions
24617 @item Access to Ada constants and variables
24618 @item Definition of intrinsic routines
24619 @item Possibility of inlining a subprogram comprising assembler code
24620 @item Code optimizer can take Inline Assembler code into account
24621 @end itemize
24622
24623 This chapter presents a series of examples to show you how to use
24624 the Inline Assembler.  Although it focuses on the Intel x86,
24625 the general approach applies also to other processors.
24626 It is assumed that you are familiar with Ada
24627 and with assembly language programming.
24628
24629 @menu
24630 * Basic Assembler Syntax::
24631 * A Simple Example of Inline Assembler::
24632 * Output Variables in Inline Assembler::
24633 * Input Variables in Inline Assembler::
24634 * Inlining Inline Assembler Code::
24635 * Other Asm Functionality::
24636 @end menu
24637
24638 @c ---------------------------------------------------------------------------
24639 @node Basic Assembler Syntax
24640 @section Basic Assembler Syntax
24641
24642 @noindent
24643 The assembler used by GNAT and gcc is based not on the Intel assembly
24644 language, but rather on a language that descends from the AT&T Unix
24645 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
24646 The following table summarizes the main features of @emph{as} syntax
24647 and points out the differences from the Intel conventions.
24648 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
24649 pre-processor) documentation for further information.
24650
24651 @table @asis
24652 @item Register names
24653 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
24654 @*
24655 Intel: No extra punctuation; for example @code{eax}
24656
24657 @item Immediate operand
24658 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
24659 @*
24660 Intel: No extra punctuation; for example @code{4}
24661
24662 @item Address
24663 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
24664 @*
24665 Intel: No extra punctuation; for example @code{loc}
24666
24667 @item Memory contents
24668 gcc / @emph{as}: No extra punctuation; for example @code{loc}
24669 @*
24670 Intel: Square brackets; for example @code{[loc]}
24671
24672 @item Register contents
24673 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
24674 @*
24675 Intel: Square brackets; for example @code{[eax]}
24676
24677 @item Hexadecimal numbers
24678 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
24679 @*
24680 Intel: Trailing ``h''; for example @code{A0h}
24681
24682 @item Operand size
24683 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
24684 a 16-bit word
24685 @*
24686 Intel: Implicit, deduced by assembler; for example @code{mov}
24687
24688 @item Instruction repetition
24689 gcc / @emph{as}: Split into two lines; for example
24690 @*
24691 @code{rep}
24692 @*
24693 @code{stosl}
24694 @*
24695 Intel: Keep on one line; for example @code{rep stosl}
24696
24697 @item Order of operands
24698 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
24699 @*
24700 Intel: Destination first; for example @code{mov eax, 4}
24701 @end table
24702
24703 @c ---------------------------------------------------------------------------
24704 @node A Simple Example of Inline Assembler
24705 @section A Simple Example of Inline Assembler
24706
24707 @noindent
24708 The following example will generate a single assembly language statement,
24709 @code{nop}, which does nothing.  Despite its lack of run-time effect,
24710 the example will be useful in illustrating the basics of
24711 the Inline Assembler facility.
24712
24713 @smallexample @c ada
24714 @group
24715 with System.Machine_Code; use System.Machine_Code;
24716 procedure Nothing is
24717 begin
24718    Asm ("nop");
24719 end Nothing;
24720 @end group
24721 @end smallexample
24722
24723 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
24724 here it takes one parameter, a @emph{template string} that must be a static
24725 expression and that will form the generated instruction.
24726 @code{Asm} may be regarded as a compile-time procedure that parses
24727 the template string and additional parameters (none here),
24728 from which it generates a sequence of assembly language instructions.
24729
24730 The examples in this chapter will illustrate several of the forms
24731 for invoking @code{Asm}; a complete specification of the syntax
24732 is found in @ref{Machine Code Insertions,,, gnat_rm, GNAT Reference
24733 Manual}.
24734
24735 Under the standard GNAT conventions, the @code{Nothing} procedure
24736 should be in a file named @file{nothing.adb}.
24737 You can build the executable in the usual way:
24738 @smallexample
24739 gnatmake nothing
24740 @end smallexample
24741 However, the interesting aspect of this example is not its run-time behavior
24742 but rather the generated assembly code.
24743 To see this output, invoke the compiler as follows:
24744 @smallexample
24745    gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
24746 @end smallexample
24747 where the options are:
24748
24749 @table @code
24750 @item -c
24751 compile only (no bind or link)
24752 @item -S
24753 generate assembler listing
24754 @item -fomit-frame-pointer
24755 do not set up separate stack frames
24756 @item -gnatp
24757 do not add runtime checks
24758 @end table
24759
24760 This gives a human-readable assembler version of the code. The resulting
24761 file will have the same name as the Ada source file, but with a @code{.s}
24762 extension. In our example, the file @file{nothing.s} has the following
24763 contents:
24764
24765 @smallexample
24766 @group
24767 .file "nothing.adb"
24768 gcc2_compiled.:
24769 ___gnu_compiled_ada:
24770 .text
24771    .align 4
24772 .globl __ada_nothing
24773 __ada_nothing:
24774 #APP
24775    nop
24776 #NO_APP
24777    jmp L1
24778    .align 2,0x90
24779 L1:
24780    ret
24781 @end group
24782 @end smallexample
24783
24784 The assembly code you included is clearly indicated by
24785 the compiler, between the @code{#APP} and @code{#NO_APP}
24786 delimiters. The character before the 'APP' and 'NOAPP'
24787 can differ on different targets. For example, GNU/Linux uses '#APP' while
24788 on NT you will see '/APP'.
24789
24790 If you make a mistake in your assembler code (such as using the
24791 wrong size modifier, or using a wrong operand for the instruction) GNAT
24792 will report this error in a temporary file, which will be deleted when
24793 the compilation is finished.  Generating an assembler file will help
24794 in such cases, since you can assemble this file separately using the
24795 @emph{as} assembler that comes with gcc.
24796
24797 Assembling the file using the command
24798
24799 @smallexample
24800 as @file{nothing.s}
24801 @end smallexample
24802 @noindent
24803 will give you error messages whose lines correspond to the assembler
24804 input file, so you can easily find and correct any mistakes you made.
24805 If there are no errors, @emph{as} will generate an object file
24806 @file{nothing.out}.
24807
24808 @c ---------------------------------------------------------------------------
24809 @node Output Variables in Inline Assembler
24810 @section Output Variables in Inline Assembler
24811
24812 @noindent
24813 The examples in this section, showing how to access the processor flags,
24814 illustrate how to specify the destination operands for assembly language
24815 statements.
24816
24817 @smallexample @c ada
24818 @group
24819 with Interfaces; use Interfaces;
24820 with Ada.Text_IO; use Ada.Text_IO;
24821 with System.Machine_Code; use System.Machine_Code;
24822 procedure Get_Flags is
24823    Flags : Unsigned_32;
24824    use ASCII;
24825 begin
24826    Asm ("pushfl"          & LF & HT & -- push flags on stack
24827         "popl %%eax"      & LF & HT & -- load eax with flags
24828         "movl %%eax, %0",             -- store flags in variable
24829         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
24830    Put_Line ("Flags register:" & Flags'Img);
24831 end Get_Flags;
24832 @end group
24833 @end smallexample
24834
24835 In order to have a nicely aligned assembly listing, we have separated
24836 multiple assembler statements in the Asm template string with linefeed
24837 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
24838 The resulting section of the assembly output file is:
24839
24840 @smallexample
24841 @group
24842 #APP
24843    pushfl
24844    popl %eax
24845    movl %eax, -40(%ebp)
24846 #NO_APP
24847 @end group
24848 @end smallexample
24849
24850 It would have been legal to write the Asm invocation as:
24851
24852 @smallexample
24853 Asm ("pushfl popl %%eax movl %%eax, %0")
24854 @end smallexample
24855
24856 but in the generated assembler file, this would come out as:
24857
24858 @smallexample
24859 #APP
24860    pushfl popl %eax movl %eax, -40(%ebp)
24861 #NO_APP
24862 @end smallexample
24863
24864 which is not so convenient for the human reader.
24865
24866 We use Ada comments
24867 at the end of each line to explain what the assembler instructions
24868 actually do.  This is a useful convention.
24869
24870 When writing Inline Assembler instructions, you need to precede each register
24871 and variable name with a percent sign.  Since the assembler already requires
24872 a percent sign at the beginning of a register name, you need two consecutive
24873 percent signs for such names in the Asm template string, thus @code{%%eax}.
24874 In the generated assembly code, one of the percent signs will be stripped off.
24875
24876 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
24877 variables: operands you later define using @code{Input} or @code{Output}
24878 parameters to @code{Asm}.
24879 An output variable is illustrated in
24880 the third statement in the Asm template string:
24881 @smallexample
24882 movl %%eax, %0
24883 @end smallexample
24884 The intent is to store the contents of the eax register in a variable that can
24885 be accessed in Ada.  Simply writing @code{movl %%eax, Flags} would not
24886 necessarily work, since the compiler might optimize by using a register
24887 to hold Flags, and the expansion of the @code{movl} instruction would not be
24888 aware of this optimization.  The solution is not to store the result directly
24889 but rather to advise the compiler to choose the correct operand form;
24890 that is the purpose of the @code{%0} output variable.
24891
24892 Information about the output variable is supplied in the @code{Outputs}
24893 parameter to @code{Asm}:
24894 @smallexample
24895 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
24896 @end smallexample
24897
24898 The output is defined by the @code{Asm_Output} attribute of the target type;
24899 the general format is
24900 @smallexample
24901 Type'Asm_Output (constraint_string, variable_name)
24902 @end smallexample
24903
24904 The constraint string directs the compiler how
24905 to store/access the associated variable.  In the example
24906 @smallexample
24907 Unsigned_32'Asm_Output ("=m", Flags);
24908 @end smallexample
24909 the @code{"m"} (memory) constraint tells the compiler that the variable
24910 @code{Flags} should be stored in a memory variable, thus preventing
24911 the optimizer from keeping it in a register.  In contrast,
24912 @smallexample
24913 Unsigned_32'Asm_Output ("=r", Flags);
24914 @end smallexample
24915 uses the @code{"r"} (register) constraint, telling the compiler to
24916 store the variable in a register.
24917
24918 If the constraint is preceded by the equal character (@strong{=}), it tells
24919 the compiler that the variable will be used to store data into it.
24920
24921 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
24922 allowing the optimizer to choose whatever it deems best.
24923
24924 There are a fairly large number of constraints, but the ones that are
24925 most useful (for the Intel x86 processor) are the following:
24926
24927 @table @code
24928 @item =
24929 output constraint
24930 @item g
24931 global (i.e.@: can be stored anywhere)
24932 @item m
24933 in memory
24934 @item I
24935 a constant
24936 @item a
24937 use eax
24938 @item b
24939 use ebx
24940 @item c
24941 use ecx
24942 @item d
24943 use edx
24944 @item S
24945 use esi
24946 @item D
24947 use edi
24948 @item r
24949 use one of eax, ebx, ecx or edx
24950 @item q
24951 use one of eax, ebx, ecx, edx, esi or edi
24952 @end table
24953
24954 The full set of constraints is described in the gcc and @emph{as}
24955 documentation; note that it is possible to combine certain constraints
24956 in one constraint string.
24957
24958 You specify the association of an output variable with an assembler operand
24959 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
24960 integer.  Thus in
24961 @smallexample @c ada
24962 @group
24963 Asm ("pushfl"          & LF & HT & -- push flags on stack
24964      "popl %%eax"      & LF & HT & -- load eax with flags
24965      "movl %%eax, %0",             -- store flags in variable
24966      Outputs => Unsigned_32'Asm_Output ("=g", Flags));
24967 @end group
24968 @end smallexample
24969 @noindent
24970 @code{%0} will be replaced in the expanded code by the appropriate operand,
24971 whatever
24972 the compiler decided for the @code{Flags} variable.
24973
24974 In general, you may have any number of output variables:
24975 @itemize @bullet
24976 @item
24977 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
24978 @item
24979 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
24980 of @code{Asm_Output} attributes
24981 @end itemize
24982
24983 For example:
24984 @smallexample @c ada
24985 @group
24986 Asm ("movl %%eax, %0" & LF & HT &
24987      "movl %%ebx, %1" & LF & HT &
24988      "movl %%ecx, %2",
24989      Outputs => (Unsigned_32'Asm_Output ("=g", Var_A),   --  %0 = Var_A
24990                  Unsigned_32'Asm_Output ("=g", Var_B),   --  %1 = Var_B
24991                  Unsigned_32'Asm_Output ("=g", Var_C))); --  %2 = Var_C
24992 @end group
24993 @end smallexample
24994 @noindent
24995 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
24996 in the Ada program.
24997
24998 As a variation on the @code{Get_Flags} example, we can use the constraints
24999 string to direct the compiler to store the eax register into the @code{Flags}
25000 variable, instead of including the store instruction explicitly in the
25001 @code{Asm} template string:
25002
25003 @smallexample @c ada
25004 @group
25005 with Interfaces; use Interfaces;
25006 with Ada.Text_IO; use Ada.Text_IO;
25007 with System.Machine_Code; use System.Machine_Code;
25008 procedure Get_Flags_2 is
25009    Flags : Unsigned_32;
25010    use ASCII;
25011 begin
25012    Asm ("pushfl"      & LF & HT & -- push flags on stack
25013         "popl %%eax",             -- save flags in eax
25014         Outputs => Unsigned_32'Asm_Output ("=a", Flags));
25015    Put_Line ("Flags register:" & Flags'Img);
25016 end Get_Flags_2;
25017 @end group
25018 @end smallexample
25019
25020 @noindent
25021 The @code{"a"} constraint tells the compiler that the @code{Flags}
25022 variable will come from the eax register. Here is the resulting code:
25023
25024 @smallexample
25025 @group
25026 #APP
25027    pushfl
25028    popl %eax
25029 #NO_APP
25030    movl %eax,-40(%ebp)
25031 @end group
25032 @end smallexample
25033
25034 @noindent
25035 The compiler generated the store of eax into Flags after
25036 expanding the assembler code.
25037
25038 Actually, there was no need to pop the flags into the eax register;
25039 more simply, we could just pop the flags directly into the program variable:
25040
25041 @smallexample @c ada
25042 @group
25043 with Interfaces; use Interfaces;
25044 with Ada.Text_IO; use Ada.Text_IO;
25045 with System.Machine_Code; use System.Machine_Code;
25046 procedure Get_Flags_3 is
25047    Flags : Unsigned_32;
25048    use ASCII;
25049 begin
25050    Asm ("pushfl"  & LF & HT & -- push flags on stack
25051         "pop %0",             -- save flags in Flags
25052         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25053    Put_Line ("Flags register:" & Flags'Img);
25054 end Get_Flags_3;
25055 @end group
25056 @end smallexample
25057
25058 @c ---------------------------------------------------------------------------
25059 @node Input Variables in Inline Assembler
25060 @section Input Variables in Inline Assembler
25061
25062 @noindent
25063 The example in this section illustrates how to specify the source operands
25064 for assembly language statements.
25065 The program simply increments its input value by 1:
25066
25067 @smallexample @c ada
25068 @group
25069 with Interfaces; use Interfaces;
25070 with Ada.Text_IO; use Ada.Text_IO;
25071 with System.Machine_Code; use System.Machine_Code;
25072 procedure Increment is
25073
25074    function Incr (Value : Unsigned_32) return Unsigned_32 is
25075       Result : Unsigned_32;
25076    begin
25077       Asm ("incl %0",
25078            Inputs  => Unsigned_32'Asm_Input ("a", Value),
25079            Outputs => Unsigned_32'Asm_Output ("=a", Result));
25080       return Result;
25081    end Incr;
25082
25083    Value : Unsigned_32;
25084
25085 begin
25086    Value := 5;
25087    Put_Line ("Value before is" & Value'Img);
25088    Value := Incr (Value);
25089    Put_Line ("Value after is" & Value'Img);
25090 end Increment;
25091 @end group
25092 @end smallexample
25093
25094 The @code{Outputs} parameter to @code{Asm} specifies
25095 that the result will be in the eax register and that it is to be stored
25096 in the @code{Result} variable.
25097
25098 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
25099 but with an @code{Asm_Input} attribute.
25100 The @code{"="} constraint, indicating an output value, is not present.
25101
25102 You can have multiple input variables, in the same way that you can have more
25103 than one output variable.
25104
25105 The parameter count (%0, %1) etc, now starts at the first input
25106 statement, and continues with the output statements.
25107 When both parameters use the same variable, the
25108 compiler will treat them as the same %n operand, which is the case here.
25109
25110 Just as the @code{Outputs} parameter causes the register to be stored into the
25111 target variable after execution of the assembler statements, so does the
25112 @code{Inputs} parameter cause its variable to be loaded into the register
25113 before execution of the assembler statements.
25114
25115 Thus the effect of the @code{Asm} invocation is:
25116 @enumerate
25117 @item load the 32-bit value of @code{Value} into eax
25118 @item execute the @code{incl %eax} instruction
25119 @item store the contents of eax into the @code{Result} variable
25120 @end enumerate
25121
25122 The resulting assembler file (with @option{-O2} optimization) contains:
25123 @smallexample
25124 @group
25125 _increment__incr.1:
25126    subl $4,%esp
25127    movl 8(%esp),%eax
25128 #APP
25129    incl %eax
25130 #NO_APP
25131    movl %eax,%edx
25132    movl %ecx,(%esp)
25133    addl $4,%esp
25134    ret
25135 @end group
25136 @end smallexample
25137
25138 @c ---------------------------------------------------------------------------
25139 @node Inlining Inline Assembler Code
25140 @section Inlining Inline Assembler Code
25141
25142 @noindent
25143 For a short subprogram such as the @code{Incr} function in the previous
25144 section, the overhead of the call and return (creating / deleting the stack
25145 frame) can be significant, compared to the amount of code in the subprogram
25146 body.  A solution is to apply Ada's @code{Inline} pragma to the subprogram,
25147 which directs the compiler to expand invocations of the subprogram at the
25148 point(s) of call, instead of setting up a stack frame for out-of-line calls.
25149 Here is the resulting program:
25150
25151 @smallexample @c ada
25152 @group
25153 with Interfaces; use Interfaces;
25154 with Ada.Text_IO; use Ada.Text_IO;
25155 with System.Machine_Code; use System.Machine_Code;
25156 procedure Increment_2 is
25157
25158    function Incr (Value : Unsigned_32) return Unsigned_32 is
25159       Result : Unsigned_32;
25160    begin
25161       Asm ("incl %0",
25162            Inputs  => Unsigned_32'Asm_Input ("a", Value),
25163            Outputs => Unsigned_32'Asm_Output ("=a", Result));
25164       return Result;
25165    end Incr;
25166    pragma Inline (Increment);
25167
25168    Value : Unsigned_32;
25169
25170 begin
25171    Value := 5;
25172    Put_Line ("Value before is" & Value'Img);
25173    Value := Increment (Value);
25174    Put_Line ("Value after is" & Value'Img);
25175 end Increment_2;
25176 @end group
25177 @end smallexample
25178
25179 Compile the program with both optimization (@option{-O2}) and inlining
25180 (@option{-gnatn}) enabled.
25181
25182 The @code{Incr} function is still compiled as usual, but at the
25183 point in @code{Increment} where our function used to be called:
25184
25185 @smallexample
25186 @group
25187 pushl %edi
25188 call _increment__incr.1
25189 @end group
25190 @end smallexample
25191
25192 @noindent
25193 the code for the function body directly appears:
25194
25195 @smallexample
25196 @group
25197 movl %esi,%eax
25198 #APP
25199    incl %eax
25200 #NO_APP
25201    movl %eax,%edx
25202 @end group
25203 @end smallexample
25204
25205 @noindent
25206 thus saving the overhead of stack frame setup and an out-of-line call.
25207
25208 @c ---------------------------------------------------------------------------
25209 @node Other Asm Functionality
25210 @section Other @code{Asm} Functionality
25211
25212 @noindent
25213 This section describes two important parameters to the @code{Asm}
25214 procedure: @code{Clobber}, which identifies register usage;
25215 and @code{Volatile}, which inhibits unwanted optimizations.
25216
25217 @menu
25218 * The Clobber Parameter::
25219 * The Volatile Parameter::
25220 @end menu
25221
25222 @c ---------------------------------------------------------------------------
25223 @node The Clobber Parameter
25224 @subsection The @code{Clobber} Parameter
25225
25226 @noindent
25227 One of the dangers of intermixing assembly language and a compiled language
25228 such as Ada is that the compiler needs to be aware of which registers are
25229 being used by the assembly code.  In some cases, such as the earlier examples,
25230 the constraint string is sufficient to indicate register usage (e.g.,
25231 @code{"a"} for
25232 the eax register).  But more generally, the compiler needs an explicit
25233 identification of the registers that are used by the Inline Assembly
25234 statements.
25235
25236 Using a register that the compiler doesn't know about
25237 could be a side effect of an instruction (like @code{mull}
25238 storing its result in both eax and edx).
25239 It can also arise from explicit register usage in your
25240 assembly code; for example:
25241 @smallexample
25242 @group
25243 Asm ("movl %0, %%ebx" & LF & HT &
25244      "movl %%ebx, %1",
25245      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
25246      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out));
25247 @end group
25248 @end smallexample
25249 @noindent
25250 where the compiler (since it does not analyze the @code{Asm} template string)
25251 does not know you are using the ebx register.
25252
25253 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
25254 to identify the registers that will be used by your assembly code:
25255
25256 @smallexample
25257 @group
25258 Asm ("movl %0, %%ebx" & LF & HT &
25259      "movl %%ebx, %1",
25260      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
25261      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
25262      Clobber => "ebx");
25263 @end group
25264 @end smallexample
25265
25266 The Clobber parameter is a static string expression specifying the
25267 register(s) you are using.  Note that register names are @emph{not} prefixed
25268 by a percent sign. Also, if more than one register is used then their names
25269 are separated by commas; e.g., @code{"eax, ebx"}
25270
25271 The @code{Clobber} parameter has several additional uses:
25272 @enumerate
25273 @item Use ``register'' name @code{cc} to indicate that flags might have changed
25274 @item Use ``register'' name @code{memory} if you changed a memory location
25275 @end enumerate
25276
25277 @c ---------------------------------------------------------------------------
25278 @node The Volatile Parameter
25279 @subsection The @code{Volatile} Parameter
25280 @cindex Volatile parameter
25281
25282 @noindent
25283 Compiler optimizations in the presence of Inline Assembler may sometimes have
25284 unwanted effects.  For example, when an @code{Asm} invocation with an input
25285 variable is inside a loop, the compiler might move the loading of the input
25286 variable outside the loop, regarding it as a one-time initialization.
25287
25288 If this effect is not desired, you can disable such optimizations by setting
25289 the @code{Volatile} parameter to @code{True}; for example:
25290
25291 @smallexample @c ada
25292 @group
25293 Asm ("movl %0, %%ebx" & LF & HT &
25294      "movl %%ebx, %1",
25295      Inputs   => Unsigned_32'Asm_Input  ("g", Var_In),
25296      Outputs  => Unsigned_32'Asm_Output ("=g", Var_Out),
25297      Clobber  => "ebx",
25298      Volatile => True);
25299 @end group
25300 @end smallexample
25301
25302 By default, @code{Volatile} is set to @code{False} unless there is no
25303 @code{Outputs} parameter.
25304
25305 Although setting @code{Volatile} to @code{True} prevents unwanted
25306 optimizations, it will also disable other optimizations that might be
25307 important for efficiency. In general, you should set @code{Volatile}
25308 to @code{True} only if the compiler's optimizations have created
25309 problems.
25310 @c END OF INLINE ASSEMBLER CHAPTER
25311 @c ===============================
25312
25313 @c ***********************************
25314 @c * Compatibility and Porting Guide *
25315 @c ***********************************
25316 @node Compatibility and Porting Guide
25317 @appendix Compatibility and Porting Guide
25318
25319 @noindent
25320 This chapter describes the compatibility issues that may arise between
25321 GNAT and other Ada compilation systems (including those for Ada 83),
25322 and shows how GNAT can expedite porting
25323 applications developed in other Ada environments.
25324
25325 @menu
25326 * Compatibility with Ada 83::
25327 * Compatibility between Ada 95 and Ada 2005::
25328 * Implementation-dependent characteristics::
25329 * Compatibility with Other Ada Systems::
25330 * Representation Clauses::
25331 @ifclear vms
25332 @c Brief section is only in non-VMS version
25333 @c Full chapter is in VMS version
25334 * Compatibility with HP Ada 83::
25335 @end ifclear
25336 @ifset vms
25337 * Transitioning to 64-Bit GNAT for OpenVMS::
25338 @end ifset
25339 @end menu
25340
25341 @node Compatibility with Ada 83
25342 @section Compatibility with Ada 83
25343 @cindex Compatibility (between Ada 83 and Ada 95 / Ada 2005)
25344
25345 @noindent
25346 Ada 95 and Ada 2005 are highly upwards compatible with Ada 83.  In
25347 particular, the design intention was that the difficulties associated
25348 with moving from Ada 83 to Ada 95 or Ada 2005 should be no greater than those
25349 that occur when moving from one Ada 83 system to another.
25350
25351 However, there are a number of points at which there are minor
25352 incompatibilities.  The @cite{Ada 95 Annotated Reference Manual} contains
25353 full details of these issues,
25354 and should be consulted for a complete treatment.
25355 In practice the
25356 following subsections treat the most likely issues to be encountered.
25357
25358 @menu
25359 * Legal Ada 83 programs that are illegal in Ada 95::
25360 * More deterministic semantics::
25361 * Changed semantics::
25362 * Other language compatibility issues::
25363 @end menu
25364
25365 @node Legal Ada 83 programs that are illegal in Ada 95
25366 @subsection Legal Ada 83 programs that are illegal in Ada 95
25367
25368 Some legal Ada 83 programs are illegal (i.e., they will fail to compile) in
25369 Ada 95 and thus also in Ada 2005:
25370
25371 @table @emph
25372 @item Character literals
25373 Some uses of character literals are ambiguous.  Since Ada 95 has introduced
25374 @code{Wide_Character} as a new predefined character type, some uses of
25375 character literals that were legal in Ada 83 are illegal in Ada 95.
25376 For example:
25377 @smallexample @c ada
25378    for Char in 'A' .. 'Z' loop @dots{} end loop;
25379 @end smallexample
25380
25381 @noindent
25382 The problem is that @code{'A'} and @code{'Z'} could be from either
25383 @code{Character} or @code{Wide_Character}.  The simplest correction
25384 is to make the type explicit; e.g.:
25385 @smallexample @c ada
25386    for Char in Character range 'A' .. 'Z' loop @dots{} end loop;
25387 @end smallexample
25388
25389 @item New reserved words
25390 The identifiers @code{abstract}, @code{aliased}, @code{protected},
25391 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
25392 Existing Ada 83 code using any of these identifiers must be edited to
25393 use some alternative name.
25394
25395 @item Freezing rules
25396 The rules in Ada 95 are slightly different with regard to the point at
25397 which entities are frozen, and representation pragmas and clauses are
25398 not permitted past the freeze point.  This shows up most typically in
25399 the form of an error message complaining that a representation item
25400 appears too late, and the appropriate corrective action is to move
25401 the item nearer to the declaration of the entity to which it refers.
25402
25403 A particular case is that representation pragmas
25404 @ifset vms
25405 (including the
25406 extended HP Ada 83 compatibility pragmas such as @code{Export_Procedure})
25407 @end ifset
25408 cannot be applied to a subprogram body.  If necessary, a separate subprogram
25409 declaration must be introduced to which the pragma can be applied.
25410
25411 @item Optional bodies for library packages
25412 In Ada 83, a package that did not require a package body was nevertheless
25413 allowed to have one.  This lead to certain surprises in compiling large
25414 systems (situations in which the body could be unexpectedly ignored by the
25415 binder).  In Ada 95, if a package does not require a body then it is not
25416 permitted to have a body.  To fix this problem, simply remove a redundant
25417 body if it is empty, or, if it is non-empty, introduce a dummy declaration
25418 into the spec that makes the body required.  One approach is to add a private
25419 part to the package declaration (if necessary), and define a parameterless
25420 procedure called @code{Requires_Body}, which must then be given a dummy
25421 procedure body in the package body, which then becomes required.
25422 Another approach (assuming that this does not introduce elaboration
25423 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
25424 since one effect of this pragma is to require the presence of a package body.
25425
25426 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
25427 In Ada 95, the exception @code{Numeric_Error} is a renaming of
25428 @code{Constraint_Error}.
25429 This means that it is illegal to have separate exception handlers for
25430 the two exceptions.  The fix is simply to remove the handler for the
25431 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
25432 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
25433
25434 @item Indefinite subtypes in generics
25435 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
25436 as the actual for a generic formal private type, but then the instantiation
25437 would be illegal if there were any instances of declarations of variables
25438 of this type in the generic body.  In Ada 95, to avoid this clear violation
25439 of the methodological principle known as the ``contract model'',
25440 the generic declaration explicitly indicates whether
25441 or not such instantiations are permitted.  If a generic formal parameter
25442 has explicit unknown discriminants, indicated by using @code{(<>)} after the
25443 type name, then it can be instantiated with indefinite types, but no
25444 stand-alone variables can be declared of this type.  Any attempt to declare
25445 such a variable will result in an illegality at the time the generic is
25446 declared.  If the @code{(<>)} notation is not used, then it is illegal
25447 to instantiate the generic with an indefinite type.
25448 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
25449 It will show up as a compile time error, and
25450 the fix is usually simply to add the @code{(<>)} to the generic declaration.
25451 @end table
25452
25453 @node More deterministic semantics
25454 @subsection More deterministic semantics
25455
25456 @table @emph
25457 @item Conversions
25458 Conversions from real types to integer types round away from 0.  In Ada 83
25459 the conversion Integer(2.5) could deliver either 2 or 3 as its value.  This
25460 implementation freedom was intended to support unbiased rounding in
25461 statistical applications, but in practice it interfered with portability.
25462 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
25463 is required.  Numeric code may be affected by this change in semantics.
25464 Note, though, that this issue is no worse than already existed in Ada 83
25465 when porting code from one vendor to another.
25466
25467 @item Tasking
25468 The Real-Time Annex introduces a set of policies that define the behavior of
25469 features that were implementation dependent in Ada 83, such as the order in
25470 which open select branches are executed.
25471 @end table
25472
25473 @node Changed semantics
25474 @subsection Changed semantics
25475
25476 @noindent
25477 The worst kind of incompatibility is one where a program that is legal in
25478 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
25479 possible in Ada 83.  Fortunately this is extremely rare, but the one
25480 situation that you should be alert to is the change in the predefined type
25481 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
25482
25483 @table @emph
25484 @item Range of type @code{Character}
25485 The range of @code{Standard.Character} is now the full 256 characters
25486 of Latin-1, whereas in most Ada 83 implementations it was restricted
25487 to 128 characters. Although some of the effects of
25488 this change will be manifest in compile-time rejection of legal
25489 Ada 83 programs it is possible for a working Ada 83 program to have
25490 a different effect in Ada 95, one that was not permitted in Ada 83.
25491 As an example, the expression
25492 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
25493 delivers @code{255} as its value.
25494 In general, you should look at the logic of any
25495 character-processing Ada 83 program and see whether it needs to be adapted
25496 to work correctly with Latin-1.  Note that the predefined Ada 95 API has a
25497 character handling package that may be relevant if code needs to be adapted
25498 to account for the additional Latin-1 elements.
25499 The desirable fix is to
25500 modify the program to accommodate the full character set, but in some cases
25501 it may be convenient to define a subtype or derived type of Character that
25502 covers only the restricted range.
25503 @cindex Latin-1
25504 @end table
25505
25506 @node Other language compatibility issues
25507 @subsection Other language compatibility issues
25508
25509 @table @emph
25510 @item @option{-gnat83} switch
25511 All implementations of GNAT provide a switch that causes GNAT to operate
25512 in Ada 83 mode.  In this mode, some but not all compatibility problems
25513 of the type described above are handled automatically.  For example, the
25514 new reserved words introduced in Ada 95 and Ada 2005 are treated simply
25515 as identifiers as in Ada 83.
25516 However,
25517 in practice, it is usually advisable to make the necessary modifications
25518 to the program to remove the need for using this switch.
25519 See @ref{Compiling Different Versions of Ada}.
25520
25521 @item Support for removed Ada 83 pragmas and attributes
25522 A number of pragmas and attributes from Ada 83 were removed from Ada 95,
25523 generally because they were replaced by other mechanisms.  Ada 95 and Ada 2005
25524 compilers are allowed, but not required, to implement these missing
25525 elements.  In contrast with some other compilers, GNAT implements all
25526 such pragmas and attributes, eliminating this compatibility concern.  These
25527 include @code{pragma Interface} and the floating point type attributes
25528 (@code{Emax}, @code{Mantissa}, etc.), among other items.
25529 @end table
25530
25531
25532 @node Compatibility between Ada 95 and Ada 2005
25533 @section Compatibility between Ada 95 and Ada 2005
25534 @cindex Compatibility between Ada 95 and Ada 2005
25535
25536 @noindent
25537 Although Ada 2005 was designed to be upwards compatible with Ada 95, there are
25538 a number of incompatibilities. Several are enumerated below;
25539 for a complete description please see the
25540 Annotated Ada 2005 Reference Manual, or section 9.1.1 in
25541 @cite{Rationale for Ada 2005}.
25542
25543 @table @emph
25544 @item New reserved words.
25545 The words @code{interface}, @code{overriding} and @code{synchronized} are
25546 reserved in Ada 2005.
25547 A pre-Ada 2005 program that uses any of these as an identifier will be
25548 illegal.
25549
25550 @item New declarations in predefined packages.
25551 A number of packages in the predefined environment contain new declarations:
25552 @code{Ada.Exceptions}, @code{Ada.Real_Time}, @code{Ada.Strings},
25553 @code{Ada.Strings.Fixed}, @code{Ada.Strings.Bounded},
25554 @code{Ada.Strings.Unbounded}, @code{Ada.Strings.Wide_Fixed},
25555 @code{Ada.Strings.Wide_Bounded}, @code{Ada.Strings.Wide_Unbounded},
25556 @code{Ada.Tags}, @code{Ada.Text_IO}, and @code{Interfaces.C}.
25557 If an Ada 95 program does a @code{with} and @code{use} of any of these
25558 packages, the new declarations may cause name clashes.
25559
25560 @item Access parameters.
25561 A nondispatching subprogram with an access parameter cannot be renamed
25562 as a dispatching operation.  This was permitted in Ada 95.
25563
25564 @item Access types, discriminants, and constraints.
25565 Rule changes in this area have led to some incompatibilities; for example,
25566 constrained subtypes of some access types are not permitted in Ada 2005.
25567
25568 @item Aggregates for limited types.
25569 The allowance of aggregates for limited types in Ada 2005 raises the
25570 possibility of ambiguities in legal Ada 95 programs, since additional types
25571 now need to be considered in expression resolution.
25572
25573 @item Fixed-point multiplication and division.
25574 Certain expressions involving ``*'' or ``/'' for a fixed-point type, which
25575 were legal in Ada 95 and invoked the predefined versions of these operations,
25576 are now ambiguous.
25577 The ambiguity may be resolved either by applying a type conversion to the
25578 expression, or by explicitly invoking the operation from package
25579 @code{Standard}.
25580
25581 @item Return-by-reference types.
25582 The Ada 95 return-by-reference mechanism has been removed.  Instead, the user
25583 can declare a function returning a value from an anonymous access type.
25584 @end table
25585
25586
25587 @node Implementation-dependent characteristics
25588 @section Implementation-dependent characteristics
25589 @noindent
25590 Although the Ada language defines the semantics of each construct as
25591 precisely as practical, in some situations (for example for reasons of
25592 efficiency, or where the effect is heavily dependent on the host or target
25593 platform) the implementation is allowed some freedom.  In porting Ada 83
25594 code to GNAT, you need to be aware of whether / how the existing code
25595 exercised such implementation dependencies.  Such characteristics fall into
25596 several categories, and GNAT offers specific support in assisting the
25597 transition from certain Ada 83 compilers.
25598
25599 @menu
25600 * Implementation-defined pragmas::
25601 * Implementation-defined attributes::
25602 * Libraries::
25603 * Elaboration order::
25604 * Target-specific aspects::
25605 @end menu
25606
25607 @node Implementation-defined pragmas
25608 @subsection Implementation-defined pragmas
25609
25610 @noindent
25611 Ada compilers are allowed to supplement the language-defined pragmas, and
25612 these are a potential source of non-portability.  All GNAT-defined pragmas
25613 are described in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT
25614 Reference Manual}, and these include several that are specifically
25615 intended to correspond to other vendors' Ada 83 pragmas.
25616 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
25617 For compatibility with HP Ada 83, GNAT supplies the pragmas
25618 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
25619 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
25620 and @code{Volatile}.
25621 Other relevant pragmas include @code{External} and @code{Link_With}.
25622 Some vendor-specific
25623 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
25624 recognized, thus
25625 avoiding compiler rejection of units that contain such pragmas; they are not
25626 relevant in a GNAT context and hence are not otherwise implemented.
25627
25628 @node Implementation-defined attributes
25629 @subsection Implementation-defined attributes
25630
25631 Analogous to pragmas, the set of attributes may be extended by an
25632 implementation.  All GNAT-defined attributes are described in
25633 @ref{Implementation Defined Attributes,,, gnat_rm, GNAT Reference
25634 Manual}, and these include several that are specifically intended
25635 to correspond to other vendors' Ada 83 attributes.  For migrating from VADS,
25636 the attribute @code{VADS_Size} may be useful.  For compatibility with HP
25637 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
25638 @code{Type_Class}.
25639
25640 @node Libraries
25641 @subsection Libraries
25642 @noindent
25643 Vendors may supply libraries to supplement the standard Ada API.  If Ada 83
25644 code uses vendor-specific libraries then there are several ways to manage
25645 this in Ada 95 or Ada 2005:
25646 @enumerate
25647 @item
25648 If the source code for the libraries (specs and bodies) are
25649 available, then the libraries can be migrated in the same way as the
25650 application.
25651 @item
25652 If the source code for the specs but not the bodies are
25653 available, then you can reimplement the bodies.
25654 @item
25655 Some features introduced by Ada 95 obviate the need for library support.  For
25656 example most Ada 83 vendors supplied a package for unsigned integers.  The
25657 Ada 95 modular type feature is the preferred way to handle this need, so
25658 instead of migrating or reimplementing the unsigned integer package it may
25659 be preferable to retrofit the application using modular types.
25660 @end enumerate
25661
25662 @node Elaboration order
25663 @subsection Elaboration order
25664 @noindent
25665 The implementation can choose any elaboration order consistent with the unit
25666 dependency relationship.  This freedom means that some orders can result in
25667 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
25668 to invoke a subprogram its body has been elaborated, or to instantiate a
25669 generic before the generic body has been elaborated.  By default GNAT
25670 attempts to choose a safe order (one that will not encounter access before
25671 elaboration problems) by implicitly inserting @code{Elaborate} or
25672 @code{Elaborate_All} pragmas where
25673 needed.  However, this can lead to the creation of elaboration circularities
25674 and a resulting rejection of the program by gnatbind.  This issue is
25675 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
25676 In brief, there are several
25677 ways to deal with this situation:
25678
25679 @itemize @bullet
25680 @item
25681 Modify the program to eliminate the circularities, e.g.@: by moving
25682 elaboration-time code into explicitly-invoked procedures
25683 @item
25684 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
25685 @code{Elaborate} pragmas, and then inhibit the generation of implicit
25686 @code{Elaborate_All}
25687 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
25688 (by selectively suppressing elaboration checks via pragma
25689 @code{Suppress(Elaboration_Check)} when it is safe to do so).
25690 @end itemize
25691
25692 @node Target-specific aspects
25693 @subsection Target-specific aspects
25694 @noindent
25695 Low-level applications need to deal with machine addresses, data
25696 representations, interfacing with assembler code, and similar issues.  If
25697 such an Ada 83 application is being ported to different target hardware (for
25698 example where the byte endianness has changed) then you will need to
25699 carefully examine the program logic; the porting effort will heavily depend
25700 on the robustness of the original design.  Moreover, Ada 95 (and thus
25701 Ada 2005) are sometimes
25702 incompatible with typical Ada 83 compiler practices regarding implicit
25703 packing, the meaning of the Size attribute, and the size of access values.
25704 GNAT's approach to these issues is described in @ref{Representation Clauses}.
25705
25706 @node Compatibility with Other Ada Systems
25707 @section Compatibility with Other Ada Systems
25708
25709 @noindent
25710 If programs avoid the use of implementation dependent and
25711 implementation defined features, as documented in the @cite{Ada
25712 Reference Manual}, there should be a high degree of portability between
25713 GNAT and other Ada systems.  The following are specific items which
25714 have proved troublesome in moving Ada 95 programs from GNAT to other Ada 95
25715 compilers, but do not affect porting code to GNAT@.
25716 (As of @value{NOW}, GNAT is the only compiler available for Ada 2005;
25717 the following issues may or may not arise for Ada 2005 programs
25718 when other compilers appear.)
25719
25720 @table @emph
25721 @item Ada 83 Pragmas and Attributes
25722 Ada 95 compilers are allowed, but not required, to implement the missing
25723 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
25724 GNAT implements all such pragmas and attributes, eliminating this as
25725 a compatibility concern, but some other Ada 95 compilers reject these
25726 pragmas and attributes.
25727
25728 @item Specialized Needs Annexes
25729 GNAT implements the full set of special needs annexes.  At the
25730 current time, it is the only Ada 95 compiler to do so.  This means that
25731 programs making use of these features may not be portable to other Ada
25732 95 compilation systems.
25733
25734 @item Representation Clauses
25735 Some other Ada 95 compilers implement only the minimal set of
25736 representation clauses required by the Ada 95 reference manual.  GNAT goes
25737 far beyond this minimal set, as described in the next section.
25738 @end table
25739
25740 @node Representation Clauses
25741 @section Representation Clauses
25742
25743 @noindent
25744 The Ada 83 reference manual was quite vague in describing both the minimal
25745 required implementation of representation clauses, and also their precise
25746 effects.  Ada 95 (and thus also Ada 2005) are much more explicit, but the
25747 minimal set of capabilities required is still quite limited.
25748
25749 GNAT implements the full required set of capabilities in
25750 Ada 95 and Ada 2005, but also goes much further, and in particular
25751 an effort has been made to be compatible with existing Ada 83 usage to the
25752 greatest extent possible.
25753
25754 A few cases exist in which Ada 83 compiler behavior is incompatible with
25755 the requirements in Ada 95 (and thus also Ada 2005).  These are instances of
25756 intentional or accidental dependence on specific implementation dependent
25757 characteristics of these Ada 83 compilers.  The following is a list of
25758 the cases most likely to arise in existing Ada 83 code.
25759
25760 @table @emph
25761 @item Implicit Packing
25762 Some Ada 83 compilers allowed a Size specification to cause implicit
25763 packing of an array or record.  This could cause expensive implicit
25764 conversions for change of representation in the presence of derived
25765 types, and the Ada design intends to avoid this possibility.
25766 Subsequent AI's were issued to make it clear that such implicit
25767 change of representation in response to a Size clause is inadvisable,
25768 and this recommendation is represented explicitly in the Ada 95 (and Ada 2005)
25769 Reference Manuals as implementation advice that is followed by GNAT@.
25770 The problem will show up as an error
25771 message rejecting the size clause.  The fix is simply to provide
25772 the explicit pragma @code{Pack}, or for more fine tuned control, provide
25773 a Component_Size clause.
25774
25775 @item Meaning of Size Attribute
25776 The Size attribute in Ada 95 (and Ada 2005) for discrete types is defined as
25777 the minimal number of bits required to hold values of the type.  For example,
25778 on a 32-bit machine, the size of @code{Natural} will typically be 31 and not
25779 32 (since no sign bit is required).  Some Ada 83 compilers gave 31, and
25780 some 32 in this situation.  This problem will usually show up as a compile
25781 time error, but not always.  It is a good idea to check all uses of the
25782 'Size attribute when porting Ada 83 code.  The GNAT specific attribute
25783 Object_Size can provide a useful way of duplicating the behavior of
25784 some Ada 83 compiler systems.
25785
25786 @item Size of Access Types
25787 A common assumption in Ada 83 code is that an access type is in fact a pointer,
25788 and that therefore it will be the same size as a System.Address value.  This
25789 assumption is true for GNAT in most cases with one exception.  For the case of
25790 a pointer to an unconstrained array type (where the bounds may vary from one
25791 value of the access type to another), the default is to use a ``fat pointer'',
25792 which is represented as two separate pointers, one to the bounds, and one to
25793 the array.  This representation has a number of advantages, including improved
25794 efficiency.  However, it may cause some difficulties in porting existing Ada 83
25795 code which makes the assumption that, for example, pointers fit in 32 bits on
25796 a machine with 32-bit addressing.
25797
25798 To get around this problem, GNAT also permits the use of ``thin pointers'' for
25799 access types in this case (where the designated type is an unconstrained array
25800 type).  These thin pointers are indeed the same size as a System.Address value.
25801 To specify a thin pointer, use a size clause for the type, for example:
25802
25803 @smallexample @c ada
25804 type X is access all String;
25805 for X'Size use Standard'Address_Size;
25806 @end smallexample
25807
25808 @noindent
25809 which will cause the type X to be represented using a single pointer.
25810 When using this representation, the bounds are right behind the array.
25811 This representation is slightly less efficient, and does not allow quite
25812 such flexibility in the use of foreign pointers or in using the
25813 Unrestricted_Access attribute to create pointers to non-aliased objects.
25814 But for any standard portable use of the access type it will work in
25815 a functionally correct manner and allow porting of existing code.
25816 Note that another way of forcing a thin pointer representation
25817 is to use a component size clause for the element size in an array,
25818 or a record representation clause for an access field in a record.
25819 @end table
25820
25821 @ifclear vms
25822 @c This brief section is only in the non-VMS version
25823 @c The complete chapter on HP Ada is in the VMS version
25824 @node Compatibility with HP Ada 83
25825 @section Compatibility with HP Ada 83
25826
25827 @noindent
25828 The VMS version of GNAT fully implements all the pragmas and attributes
25829 provided by HP Ada 83, as well as providing the standard HP Ada 83
25830 libraries, including Starlet.  In addition, data layouts and parameter
25831 passing conventions are highly compatible.  This means that porting
25832 existing HP Ada 83 code to GNAT in VMS systems should be easier than
25833 most other porting efforts.  The following are some of the most
25834 significant differences between GNAT and HP Ada 83.
25835
25836 @table @emph
25837 @item Default floating-point representation
25838 In GNAT, the default floating-point format is IEEE, whereas in HP Ada 83,
25839 it is VMS format.  GNAT does implement the necessary pragmas
25840 (Long_Float, Float_Representation) for changing this default.
25841
25842 @item System
25843 The package System in GNAT exactly corresponds to the definition in the
25844 Ada 95 reference manual, which means that it excludes many of the
25845 HP Ada 83 extensions.  However, a separate package Aux_DEC is provided
25846 that contains the additional definitions, and a special pragma,
25847 Extend_System allows this package to be treated transparently as an
25848 extension of package System.
25849
25850 @item To_Address
25851 The definitions provided by Aux_DEC are exactly compatible with those
25852 in the HP Ada 83 version of System, with one exception.
25853 HP Ada provides the following declarations:
25854
25855 @smallexample @c ada
25856 TO_ADDRESS (INTEGER)
25857 TO_ADDRESS (UNSIGNED_LONGWORD)
25858 TO_ADDRESS (@i{universal_integer})
25859 @end smallexample
25860
25861 @noindent
25862 The version of TO_ADDRESS taking a @i{universal integer} argument is in fact
25863 an extension to Ada 83 not strictly compatible with the reference manual.
25864 In GNAT, we are constrained to be exactly compatible with the standard,
25865 and this means we cannot provide this capability.  In HP Ada 83, the
25866 point of this definition is to deal with a call like:
25867
25868 @smallexample @c ada
25869 TO_ADDRESS (16#12777#);
25870 @end smallexample
25871
25872 @noindent
25873 Normally, according to the Ada 83 standard, one would expect this to be
25874 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
25875 of TO_ADDRESS@.  However, in HP Ada 83, there is no ambiguity, since the
25876 definition using @i{universal_integer} takes precedence.
25877
25878 In GNAT, since the version with @i{universal_integer} cannot be supplied, it
25879 is not possible to be 100% compatible.  Since there are many programs using
25880 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
25881 to change the name of the function in the UNSIGNED_LONGWORD case, so the
25882 declarations provided in the GNAT version of AUX_Dec are:
25883
25884 @smallexample @c ada
25885 function To_Address (X : Integer) return Address;
25886 pragma Pure_Function (To_Address);
25887
25888 function To_Address_Long (X : Unsigned_Longword)
25889  return Address;
25890 pragma Pure_Function (To_Address_Long);
25891 @end smallexample
25892
25893 @noindent
25894 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
25895 change the name to TO_ADDRESS_LONG@.
25896
25897 @item Task_Id values
25898 The Task_Id values assigned will be different in the two systems, and GNAT
25899 does not provide a specified value for the Task_Id of the environment task,
25900 which in GNAT is treated like any other declared task.
25901 @end table
25902
25903 @noindent
25904 For full details on these and other less significant compatibility issues,
25905 see appendix E of the HP publication entitled @cite{HP Ada, Technical
25906 Overview and Comparison on HP Platforms}.
25907
25908 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
25909 attributes are recognized, although only a subset of them can sensibly
25910 be implemented.  The description of pragmas in @ref{Implementation
25911 Defined Pragmas,,, gnat_rm, GNAT Reference Manual}
25912 indicates whether or not they are applicable to non-VMS systems.
25913 @end ifclear
25914
25915 @ifset vms
25916 @node Transitioning to 64-Bit GNAT for OpenVMS
25917 @section Transitioning to 64-Bit @value{EDITION} for OpenVMS
25918
25919 @noindent
25920 This section is meant to assist users of pre-2006 @value{EDITION}
25921 for Alpha OpenVMS who are transitioning to 64-bit @value{EDITION},
25922 the version of the GNAT technology supplied in 2006 and later for
25923 OpenVMS on both Alpha and I64.
25924
25925 @menu
25926 * Introduction to transitioning::
25927 * Migration of 32 bit code::
25928 * Taking advantage of 64 bit addressing::
25929 * Technical details::
25930 @end menu
25931
25932 @node Introduction to transitioning
25933 @subsection Introduction
25934
25935 @noindent
25936 64-bit @value{EDITION} for Open VMS has been designed to meet
25937 three main goals:
25938
25939 @enumerate
25940 @item
25941 Providing a full conforming implementation of Ada 95 and Ada 2005
25942
25943 @item
25944 Allowing maximum backward compatibility, thus easing migration of existing
25945 Ada source code
25946
25947 @item
25948 Supplying a path for exploiting the full 64-bit address range
25949 @end enumerate
25950
25951 @noindent
25952 Ada's strong typing semantics has made it
25953 impractical to have different 32-bit and 64-bit modes. As soon as
25954 one object could possibly be outside the 32-bit address space, this
25955 would make it necessary for the @code{System.Address} type to be 64 bits.
25956 In particular, this would cause inconsistencies if 32-bit code is
25957 called from 64-bit code that raises an exception.
25958
25959 This issue has been resolved by always using 64-bit addressing
25960 at the system level, but allowing for automatic conversions between
25961 32-bit and 64-bit addresses where required. Thus users who
25962 do not currently require 64-bit addressing capabilities, can
25963 recompile their code with only minimal changes (and indeed
25964 if the code is written in portable Ada, with no assumptions about
25965 the size of the @code{Address} type, then no changes at all are necessary).
25966 At the same time,
25967 this approach provides a simple, gradual upgrade path to future
25968 use of larger memories than available for 32-bit systems.
25969 Also, newly written applications or libraries will by default
25970 be fully compatible with future systems exploiting 64-bit
25971 addressing capabilities.
25972
25973 @ref{Migration of 32 bit code}, will focus on porting applications
25974 that do not require more than 2 GB of
25975 addressable memory. This code will be referred to as
25976 @emph{32-bit code}.
25977 For applications intending to exploit the full 64-bit address space,
25978 @ref{Taking advantage of 64 bit addressing},
25979 will consider further changes that may be required.
25980 Such code will be referred to below as @emph{64-bit code}.
25981
25982 @node Migration of 32 bit code
25983 @subsection Migration of 32-bit code
25984
25985 @menu
25986 * Address types::
25987 * Access types and 32/64-bit allocation::
25988 * Unchecked conversions::
25989 * Predefined constants::
25990 * Interfacing with C::
25991 * 32/64-bit descriptors::
25992 * Experience with source compatibility::
25993 @end menu
25994
25995 @node Address types
25996 @subsubsection Address types
25997
25998 @noindent
25999 To solve the problem of mixing 64-bit and 32-bit addressing,
26000 while maintaining maximum backward compatibility, the following
26001 approach has been taken:
26002
26003 @itemize @bullet
26004 @item
26005 @code{System.Address} always has a size of 64 bits
26006 @cindex @code{System.Address} size
26007 @cindex @code{Address} size
26008
26009 @item
26010 @code{System.Short_Address} is a 32-bit subtype of @code{System.Address}
26011 @cindex @code{System.Short_Address} size
26012 @cindex @code{Short_Address} size
26013 @end itemize
26014
26015 @noindent
26016 Since @code{System.Short_Address} is a subtype of @code{System.Address},
26017 a @code{Short_Address}
26018 may be used where an @code{Address} is required, and vice versa, without
26019 needing explicit type conversions.
26020 By virtue of the Open VMS parameter passing conventions,
26021 even imported
26022 and exported subprograms that have 32-bit address parameters are
26023 compatible with those that have 64-bit address parameters.
26024 (See @ref{Making code 64 bit clean} for details.)
26025
26026 The areas that may need attention are those where record types have
26027 been defined that contain components of the type @code{System.Address}, and
26028 where objects of this type are passed to code expecting a record layout with
26029 32-bit addresses.
26030
26031 Different compilers on different platforms cannot be
26032 expected to represent the same type in the same way,
26033 since alignment constraints
26034 and other system-dependent properties affect the compiler's decision.
26035 For that reason, Ada code
26036 generally uses representation clauses to specify the expected
26037 layout where required.
26038
26039 If such a representation clause uses 32 bits for a component having
26040 the type @code{System.Address}, 64-bit @value{EDITION} for OpenVMS
26041 will detect that error and produce a specific diagnostic message.
26042 The developer should then determine whether the representation
26043 should be 64 bits or not and make either of two changes:
26044 change the size to 64 bits and leave the type as @code{System.Address}, or
26045 leave the size as 32 bits and change the type to @code{System.Short_Address}.
26046 Since @code{Short_Address} is a subtype of @code{Address}, no changes are
26047 required in any code setting or accessing the field; the compiler will
26048 automatically perform any needed conversions between address
26049 formats.
26050
26051 @node Access types and 32/64-bit allocation
26052 @subsubsection Access types and 32/64-bit allocation
26053 @cindex 32-bit allocation
26054 @cindex 64-bit allocation
26055
26056 @noindent
26057 By default, objects designated by access values are always allocated in
26058 the 64-bit address space, and access values themselves are represented
26059 in 64 bits.  If these defaults are not appropriate, and 32-bit allocation
26060 is required (for example if the address of an allocated object is assigned
26061 to a @code{Short_Address} variable), then several alternatives are available:
26062
26063 @itemize @bullet
26064 @item
26065 A pool-specific access type (ie, an @w{Ada 83} access type, whose
26066 definition is @code{access T} versus @code{access all T} or
26067 @code{access constant T}), may be declared with a @code{'Size} representation
26068 clause that establishes the size as 32 bits.
26069 In such circumstances allocations for that type will
26070 be from the 32-bit heap.  Such a clause is not permitted
26071 for a general access type (declared with @code{access all} or
26072 @code{access constant}) as values of such types must be able to refer
26073 to any object of the designated type, including objects residing outside
26074 the 32-bit address range.  Existing @w{Ada 83} code will not contain such
26075 type definitions, however, since general access types were introduced
26076 in @w{Ada 95}.
26077
26078 @item
26079 Switches for @command{GNAT BIND} control whether the internal GNAT
26080 allocation routine @code{__gnat_malloc} uses 64-bit or 32-bit allocations.
26081 @cindex @code{__gnat_malloc}
26082 The switches are respectively @option{-H64} (the default) and
26083 @option{-H32}.
26084 @cindex @option{-H32} (@command{gnatbind})
26085 @cindex @option{-H64} (@command{gnatbind})
26086
26087 @item
26088 The environment variable (logical name) @code{GNAT$NO_MALLOC_64}
26089 @cindex @code{GNAT$NO_MALLOC_64} environment variable
26090 may be used to force @code{__gnat_malloc} to use 32-bit allocation.
26091 If this variable is left
26092 undefined, or defined as @code{"DISABLE"}, @code{"FALSE"}, or @code{"0"},
26093 then the default (64-bit) allocation is used.
26094 If defined as @code{"ENABLE"}, @code{"TRUE"}, or @code{"1"},
26095 then 32-bit allocation is used.  The gnatbind qualifiers described above
26096 override this logical name.
26097
26098 @item
26099 A ^gcc switch^gcc switch^ for OpenVMS, @option{-mno-malloc64}, operates
26100 @cindex @option{-mno-malloc64} (^gcc^gcc^)
26101 at a low level to convert explicit calls to @code{malloc} and related
26102 functions from the C run-time library so that they perform allocations
26103 in the 32-bit heap.
26104 Since all internal allocations from GNAT use @code{__gnat_malloc},
26105 this switch is not required unless the program makes explicit calls on
26106 @code{malloc} (or related functions) from interfaced C code.
26107 @end itemize
26108
26109
26110 @node Unchecked conversions
26111 @subsubsection Unchecked conversions
26112
26113 @noindent
26114 In the case of an @code{Unchecked_Conversion} where the source type is a
26115 64-bit access type or the type @code{System.Address}, and the target
26116 type is a 32-bit type, the compiler will generate a warning.
26117 Even though the generated code will still perform the required
26118 conversions, it is highly recommended in these cases to use
26119 respectively a 32-bit access type or @code{System.Short_Address}
26120 as the source type.
26121
26122 @node Predefined constants
26123 @subsubsection Predefined constants
26124
26125 @noindent
26126 The following table shows the correspondence between pre-2006 versions of
26127 @value{EDITION} on Alpha OpenVMS (``Old'') and 64-bit @value{EDITION}
26128 (``New''):
26129
26130 @multitable {@code{System.Short_Memory_Size}} {2**32} {2**64}
26131 @item   @b{Constant}                     @tab @b{Old} @tab @b{New}
26132 @item   @code{System.Word_Size}          @tab 32      @tab 64
26133 @item   @code{System.Memory_Size}        @tab 2**32   @tab 2**64
26134 @item   @code{System.Short_Memory_Size}  @tab 2**32   @tab 2**32
26135 @item   @code{System.Address_Size}       @tab 32      @tab 64
26136 @end multitable
26137
26138 @noindent
26139 If you need to refer to the specific
26140 memory size of a 32-bit implementation, instead of the
26141 actual memory size, use @code{System.Short_Memory_Size}
26142 rather than @code{System.Memory_Size}.
26143 Similarly, references to @code{System.Address_Size} may need
26144 to be replaced by @code{System.Short_Address'Size}.
26145 The program @command{gnatfind} may be useful for locating
26146 references to the above constants, so that you can verify that they
26147 are still correct.
26148
26149 @node Interfacing with C
26150 @subsubsection Interfacing with C
26151
26152 @noindent
26153 In order to minimize the impact of the transition to 64-bit addresses on
26154 legacy programs, some fundamental types in the @code{Interfaces.C}
26155 package hierarchy continue to be represented in 32 bits.
26156 These types are: @code{ptrdiff_t}, @code{size_t}, and @code{chars_ptr}.
26157 This eases integration with the default HP C layout choices, for example
26158 as found in the system routines in @code{DECC$SHR.EXE}.
26159 Because of this implementation choice, the type fully compatible with
26160 @code{chars_ptr} is now @code{Short_Address} and not @code{Address}.
26161 Depending on the context the compiler will issue a
26162 warning or an error when type @code{Address} is used, alerting the user to a
26163 potential problem. Otherwise 32-bit programs that use
26164 @code{Interfaces.C} should normally not require code modifications
26165
26166 The other issue arising with C interfacing concerns pragma @code{Convention}.
26167 For VMS 64-bit systems, there is an issue of the appropriate default size
26168 of C convention pointers in the absence of an explicit size clause. The HP
26169 C compiler can choose either 32 or 64 bits depending on compiler options.
26170 GNAT chooses 32-bits rather than 64-bits in the default case where no size
26171 clause is given. This proves a better choice for porting 32-bit legacy
26172 applications. In order to have a 64-bit representation, it is necessary to
26173 specify a size representation clause. For example:
26174
26175 @smallexample @c ada
26176 type int_star is access Interfaces.C.int;
26177 pragma Convention(C, int_star);
26178 for int_star'Size use 64;  -- Necessary to get 64 and not 32 bits
26179 @end smallexample
26180
26181 @node 32/64-bit descriptors
26182 @subsubsection 32/64-bit descriptors
26183
26184 @noindent
26185 By default, GNAT uses a 64-bit descriptor mechanism.  For an imported
26186 subprogram (i.e., a subprogram identified by pragma @code{Import_Function},
26187 @code{Import_Procedure}, or @code{Import_Valued_Procedure}) that specifies
26188 @code{Short_Descriptor} as its mechanism, a 32-bit descriptor is used.
26189 @cindex @code{Short_Descriptor} mechanism for imported subprograms
26190
26191 If the configuration pragma @code{Short_Descriptors} is supplied, then
26192 all descriptors will be 32 bits.
26193 @cindex pragma @code{Short_Descriptors}
26194
26195 @node Experience with source compatibility
26196 @subsubsection Experience with source compatibility
26197
26198 @noindent
26199 The Security Server and STARLET on I64 provide an interesting ``test case''
26200 for source compatibility issues, since it is in such system code
26201 where assumptions about @code{Address} size might be expected to occur.
26202 Indeed, there were a small number of occasions in the Security Server
26203 file @file{jibdef.ads}
26204 where a representation clause for a record type specified
26205 32 bits for a component of type @code{Address}.
26206 All of these errors were detected by the compiler.
26207 The repair was obvious and immediate; to simply replace @code{Address} by
26208 @code{Short_Address}.
26209
26210 In the case of STARLET, there were several record types that should
26211 have had representation clauses but did not.  In these record types
26212 there was an implicit assumption that an @code{Address} value occupied
26213 32 bits.
26214 These compiled without error, but their usage resulted in run-time error
26215 returns from STARLET system calls.
26216 Future GNAT technology enhancements may include a tool that detects and flags
26217 these sorts of potential source code porting problems.
26218
26219 @c ****************************************
26220 @node Taking advantage of 64 bit addressing
26221 @subsection Taking advantage of 64-bit addressing
26222
26223 @menu
26224 * Making code 64 bit clean::
26225 * Allocating memory from the 64 bit storage pool::
26226 * Restrictions on use of 64 bit objects::
26227 * STARLET and other predefined libraries::
26228 @end menu
26229
26230 @node Making code 64 bit clean
26231 @subsubsection Making code 64-bit clean
26232
26233 @noindent
26234 In order to prevent problems that may occur when (parts of) a
26235 system start using memory outside the 32-bit address range,
26236 we recommend some additional guidelines:
26237
26238 @itemize @bullet
26239 @item
26240 For imported subprograms that take parameters of the
26241 type @code{System.Address}, ensure that these subprograms can
26242 indeed handle 64-bit addresses. If not, or when in doubt,
26243 change the subprogram declaration to specify
26244 @code{System.Short_Address} instead.
26245
26246 @item
26247 Resolve all warnings related to size mismatches in
26248 unchecked conversions. Failing to do so causes
26249 erroneous execution if the source object is outside
26250 the 32-bit address space.
26251
26252 @item
26253 (optional) Explicitly use the 32-bit storage pool
26254 for access types used in a 32-bit context, or use
26255 generic access types where possible
26256 (@pxref{Restrictions on use of 64 bit objects}).
26257 @end itemize
26258
26259 @noindent
26260 If these rules are followed, the compiler will automatically insert
26261 any necessary checks to ensure that no addresses or access values
26262 passed to 32-bit code ever refer to objects outside the 32-bit
26263 address range.
26264 Any attempt to do this will raise @code{Constraint_Error}.
26265
26266 @node Allocating memory from the 64 bit storage pool
26267 @subsubsection Allocating memory from the 64-bit storage pool
26268
26269 @noindent
26270 By default, all allocations -- for both pool-specific and general
26271 access types -- use the 64-bit storage pool.  To override
26272 this default, for an individual access type or globally, see
26273 @ref{Access types and 32/64-bit allocation}.
26274
26275 @node Restrictions on use of 64 bit objects
26276 @subsubsection Restrictions on use of 64-bit objects
26277
26278 @noindent
26279 Taking the address of an object allocated from a 64-bit storage pool,
26280 and then passing this address to a subprogram expecting
26281 @code{System.Short_Address},
26282 or assigning it to a variable of type @code{Short_Address}, will cause
26283 @code{Constraint_Error} to be raised. In case the code is not 64-bit clean
26284 (@pxref{Making code 64 bit clean}), or checks are suppressed,
26285 no exception is raised and execution
26286 will become erroneous.
26287
26288 @node STARLET and other predefined libraries
26289 @subsubsection STARLET and other predefined libraries
26290
26291 @noindent
26292 All code that comes as part of GNAT is 64-bit clean, but the
26293 restrictions given in @ref{Restrictions on use of 64 bit objects},
26294 still apply. Look at the package
26295 specs to see in which contexts objects allocated
26296 in 64-bit address space are acceptable.
26297
26298 @node Technical details
26299 @subsection Technical details
26300
26301 @noindent
26302 64-bit @value{EDITION} for Open VMS takes advantage of the freedom given in the
26303 Ada standard with respect to the type of @code{System.Address}. Previous
26304 versions of GNAT Pro have defined this type as private and implemented it as a
26305 modular type.
26306
26307 In order to allow defining @code{System.Short_Address} as a proper subtype,
26308 and to match the implicit sign extension in parameter passing,
26309 in 64-bit @value{EDITION} for Open VMS, @code{System.Address} is defined as a
26310 visible (i.e., non-private) integer type.
26311 Standard operations on the type, such as the binary operators ``+'', ``-'',
26312 etc., that take @code{Address} operands and return an @code{Address} result,
26313 have been hidden by declaring these
26314 @code{abstract}, a feature introduced in Ada 95 that helps avoid the potential
26315 ambiguities that would otherwise result from overloading.
26316 (Note that, although @code{Address} is a visible integer type,
26317 good programming practice dictates against exploiting the type's
26318 integer properties such as literals, since this will compromise
26319 code portability.)
26320
26321 Defining @code{Address} as a visible integer type helps achieve
26322 maximum compatibility for existing Ada code,
26323 without sacrificing the capabilities of the 64-bit architecture.
26324 @end ifset
26325
26326 @c ************************************************
26327 @ifset unw
26328 @node Microsoft Windows Topics
26329 @appendix Microsoft Windows Topics
26330 @cindex Windows NT
26331 @cindex Windows 95
26332 @cindex Windows 98
26333
26334 @noindent
26335 This chapter describes topics that are specific to the Microsoft Windows
26336 platforms (NT, 2000, and XP Professional).
26337
26338 @menu
26339 * Using GNAT on Windows::
26340 * Using a network installation of GNAT::
26341 * CONSOLE and WINDOWS subsystems::
26342 * Temporary Files::
26343 * Mixed-Language Programming on Windows::
26344 * Windows Calling Conventions::
26345 * Introduction to Dynamic Link Libraries (DLLs)::
26346 * Using DLLs with GNAT::
26347 * Building DLLs with GNAT Project files::
26348 * Building DLLs with GNAT::
26349 * Building DLLs with gnatdll::
26350 * GNAT and Windows Resources::
26351 * Debugging a DLL::
26352 * Setting Stack Size from gnatlink::
26353 * Setting Heap Size from gnatlink::
26354 @end menu
26355
26356 @node Using GNAT on Windows
26357 @section Using GNAT on Windows
26358
26359 @noindent
26360 One of the strengths of the GNAT technology is that its tool set
26361 (@command{gcc}, @command{gnatbind}, @command{gnatlink}, @command{gnatmake}, the
26362 @code{gdb} debugger, etc.) is used in the same way regardless of the
26363 platform.
26364
26365 On Windows this tool set is complemented by a number of Microsoft-specific
26366 tools that have been provided to facilitate interoperability with Windows
26367 when this is required. With these tools:
26368
26369 @itemize @bullet
26370
26371 @item
26372 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
26373 subsystems.
26374
26375 @item
26376 You can use any Dynamically Linked Library (DLL) in your Ada code (both
26377 relocatable and non-relocatable DLLs are supported).
26378
26379 @item
26380 You can build Ada DLLs for use in other applications. These applications
26381 can be written in a language other than Ada (e.g., C, C++, etc). Again both
26382 relocatable and non-relocatable Ada DLLs are supported.
26383
26384 @item
26385 You can include Windows resources in your Ada application.
26386
26387 @item
26388 You can use or create COM/DCOM objects.
26389 @end itemize
26390
26391 @noindent
26392 Immediately below are listed all known general GNAT-for-Windows restrictions.
26393 Other restrictions about specific features like Windows Resources and DLLs
26394 are listed in separate sections below.
26395
26396 @itemize @bullet
26397
26398 @item
26399 It is not possible to use @code{GetLastError} and @code{SetLastError}
26400 when tasking, protected records, or exceptions are used. In these
26401 cases, in order to implement Ada semantics, the GNAT run-time system
26402 calls certain Win32 routines that set the last error variable to 0 upon
26403 success. It should be possible to use @code{GetLastError} and
26404 @code{SetLastError} when tasking, protected record, and exception
26405 features are not used, but it is not guaranteed to work.
26406
26407 @item
26408 It is not possible to link against Microsoft libraries except for
26409 import libraries. Interfacing must be done by the mean of DLLs.
26410
26411 @item
26412 When the compilation environment is located on FAT32 drives, users may
26413 experience recompilations of the source files that have not changed if
26414 Daylight Saving Time (DST) state has changed since the last time files
26415 were compiled. NTFS drives do not have this problem.
26416
26417 @item
26418 No components of the GNAT toolset use any entries in the Windows
26419 registry. The only entries that can be created are file associations and
26420 PATH settings, provided the user has chosen to create them at installation
26421 time, as well as some minimal book-keeping information needed to correctly
26422 uninstall or integrate different GNAT products.
26423 @end itemize
26424
26425 @node Using a network installation of GNAT
26426 @section Using a network installation of GNAT
26427
26428 @noindent
26429 Make sure the system on which GNAT is installed is accessible from the
26430 current machine, i.e., the install location is shared over the network.
26431 Shared resources are accessed on Windows by means of UNC paths, which
26432 have the format @code{\\server\sharename\path}
26433
26434 In order to use such a network installation, simply add the UNC path of the
26435 @file{bin} directory of your GNAT installation in front of your PATH. For
26436 example, if GNAT is installed in @file{\GNAT} directory of a share location
26437 called @file{c-drive} on a machine @file{LOKI}, the following command will
26438 make it available:
26439
26440 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
26441
26442 Be aware that every compilation using the network installation results in the
26443 transfer of large amounts of data across the network and will likely cause
26444 serious performance penalty.
26445
26446 @node CONSOLE and WINDOWS subsystems
26447 @section CONSOLE and WINDOWS subsystems
26448 @cindex CONSOLE Subsystem
26449 @cindex WINDOWS Subsystem
26450 @cindex -mwindows
26451
26452 @noindent
26453 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
26454 (which is the default subsystem) will always create a console when
26455 launching the application. This is not something desirable when the
26456 application has a Windows GUI. To get rid of this console the
26457 application must be using the @code{WINDOWS} subsystem. To do so
26458 the @option{-mwindows} linker option must be specified.
26459
26460 @smallexample
26461 $ gnatmake winprog -largs -mwindows
26462 @end smallexample
26463
26464 @node Temporary Files
26465 @section Temporary Files
26466 @cindex Temporary files
26467
26468 @noindent
26469 It is possible to control where temporary files gets created by setting
26470 the @env{TMP} environment variable. The file will be created:
26471
26472 @itemize
26473 @item Under the directory pointed to by the @env{TMP} environment variable if
26474 this directory exists.
26475
26476 @item Under @file{c:\temp}, if the @env{TMP} environment variable is not
26477 set (or not pointing to a directory) and if this directory exists.
26478
26479 @item Under the current working directory otherwise.
26480 @end itemize
26481
26482 @noindent
26483 This allows you to determine exactly where the temporary
26484 file will be created. This is particularly useful in networked
26485 environments where you may not have write access to some
26486 directories.
26487
26488 @node Mixed-Language Programming on Windows
26489 @section Mixed-Language Programming on Windows
26490
26491 @noindent
26492 Developing pure Ada applications on Windows is no different than on
26493 other GNAT-supported platforms. However, when developing or porting an
26494 application that contains a mix of Ada and C/C++, the choice of your
26495 Windows C/C++ development environment conditions your overall
26496 interoperability strategy.
26497
26498 If you use @command{gcc} to compile the non-Ada part of your application,
26499 there are no Windows-specific restrictions that affect the overall
26500 interoperability with your Ada code. If you do want to use the
26501 Microsoft tools for your non-Ada code, you have two choices:
26502
26503 @enumerate
26504 @item
26505 Encapsulate your non-Ada code in a DLL to be linked with your Ada
26506 application. In this case, use the Microsoft or whatever environment to
26507 build the DLL and use GNAT to build your executable
26508 (@pxref{Using DLLs with GNAT}).
26509
26510 @item
26511 Or you can encapsulate your Ada code in a DLL to be linked with the
26512 other part of your application. In this case, use GNAT to build the DLL
26513 (@pxref{Building DLLs with GNAT Project files}) and use the Microsoft
26514 or whatever environment to build your executable.
26515 @end enumerate
26516
26517 @node Windows Calling Conventions
26518 @section Windows Calling Conventions
26519 @findex Stdcall
26520 @findex APIENTRY
26521
26522 This section pertain only to Win32. On Win64 there is a single native
26523 calling convention. All convention specifiers are ignored on this
26524 platform.
26525
26526 @menu
26527 * C Calling Convention::
26528 * Stdcall Calling Convention::
26529 * Win32 Calling Convention::
26530 * DLL Calling Convention::
26531 @end menu
26532
26533 @noindent
26534 When a subprogram @code{F} (caller) calls a subprogram @code{G}
26535 (callee), there are several ways to push @code{G}'s parameters on the
26536 stack and there are several possible scenarios to clean up the stack
26537 upon @code{G}'s return. A calling convention is an agreed upon software
26538 protocol whereby the responsibilities between the caller (@code{F}) and
26539 the callee (@code{G}) are clearly defined. Several calling conventions
26540 are available for Windows:
26541
26542 @itemize @bullet
26543 @item
26544 @code{C} (Microsoft defined)
26545
26546 @item
26547 @code{Stdcall} (Microsoft defined)
26548
26549 @item
26550 @code{Win32} (GNAT specific)
26551
26552 @item
26553 @code{DLL} (GNAT specific)
26554 @end itemize
26555
26556 @node C Calling Convention
26557 @subsection @code{C} Calling Convention
26558
26559 @noindent
26560 This is the default calling convention used when interfacing to C/C++
26561 routines compiled with either @command{gcc} or Microsoft Visual C++.
26562
26563 In the @code{C} calling convention subprogram parameters are pushed on the
26564 stack by the caller from right to left. The caller itself is in charge of
26565 cleaning up the stack after the call. In addition, the name of a routine
26566 with @code{C} calling convention is mangled by adding a leading underscore.
26567
26568 The name to use on the Ada side when importing (or exporting) a routine
26569 with @code{C} calling convention is the name of the routine. For
26570 instance the C function:
26571
26572 @smallexample
26573 int get_val (long);
26574 @end smallexample
26575
26576 @noindent
26577 should be imported from Ada as follows:
26578
26579 @smallexample @c ada
26580 @group
26581 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
26582 pragma Import (C, Get_Val, External_Name => "get_val");
26583 @end group
26584 @end smallexample
26585
26586 @noindent
26587 Note that in this particular case the @code{External_Name} parameter could
26588 have been omitted since, when missing, this parameter is taken to be the
26589 name of the Ada entity in lower case. When the @code{Link_Name} parameter
26590 is missing, as in the above example, this parameter is set to be the
26591 @code{External_Name} with a leading underscore.
26592
26593 When importing a variable defined in C, you should always use the @code{C}
26594 calling convention unless the object containing the variable is part of a
26595 DLL (in which case you should use the @code{Stdcall} calling
26596 convention, @pxref{Stdcall Calling Convention}).
26597
26598 @node Stdcall Calling Convention
26599 @subsection @code{Stdcall} Calling Convention
26600
26601 @noindent
26602 This convention, which was the calling convention used for Pascal
26603 programs, is used by Microsoft for all the routines in the Win32 API for
26604 efficiency reasons. It must be used to import any routine for which this
26605 convention was specified.
26606
26607 In the @code{Stdcall} calling convention subprogram parameters are pushed
26608 on the stack by the caller from right to left. The callee (and not the
26609 caller) is in charge of cleaning the stack on routine exit. In addition,
26610 the name of a routine with @code{Stdcall} calling convention is mangled by
26611 adding a leading underscore (as for the @code{C} calling convention) and a
26612 trailing @code{@@}@code{@var{nn}}, where @var{nn} is the overall size (in
26613 bytes) of the parameters passed to the routine.
26614
26615 The name to use on the Ada side when importing a C routine with a
26616 @code{Stdcall} calling convention is the name of the C routine. The leading
26617 underscore and trailing @code{@@}@code{@var{nn}} are added automatically by
26618 the compiler. For instance the Win32 function:
26619
26620 @smallexample
26621 @b{APIENTRY} int get_val (long);
26622 @end smallexample
26623
26624 @noindent
26625 should be imported from Ada as follows:
26626
26627 @smallexample @c ada
26628 @group
26629 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
26630 pragma Import (Stdcall, Get_Val);
26631 --  On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
26632 @end group
26633 @end smallexample
26634
26635 @noindent
26636 As for the @code{C} calling convention, when the @code{External_Name}
26637 parameter is missing, it is taken to be the name of the Ada entity in lower
26638 case. If instead of writing the above import pragma you write:
26639
26640 @smallexample @c ada
26641 @group
26642 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
26643 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
26644 @end group
26645 @end smallexample
26646
26647 @noindent
26648 then the imported routine is @code{_retrieve_val@@4}. However, if instead
26649 of specifying the @code{External_Name} parameter you specify the
26650 @code{Link_Name} as in the following example:
26651
26652 @smallexample @c ada
26653 @group
26654 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
26655 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
26656 @end group
26657 @end smallexample
26658
26659 @noindent
26660 then the imported routine is @code{retrieve_val}, that is, there is no
26661 decoration at all. No leading underscore and no Stdcall suffix
26662 @code{@@}@code{@var{nn}}.
26663
26664 @noindent
26665 This is especially important as in some special cases a DLL's entry
26666 point name lacks a trailing @code{@@}@code{@var{nn}} while the exported
26667 name generated for a call has it.
26668
26669 @noindent
26670 It is also possible to import variables defined in a DLL by using an
26671 import pragma for a variable. As an example, if a DLL contains a
26672 variable defined as:
26673
26674 @smallexample
26675 int my_var;
26676 @end smallexample
26677
26678 @noindent
26679 then, to access this variable from Ada you should write:
26680
26681 @smallexample @c ada
26682 @group
26683 My_Var : Interfaces.C.int;
26684 pragma Import (Stdcall, My_Var);
26685 @end group
26686 @end smallexample
26687
26688 @noindent
26689 Note that to ease building cross-platform bindings this convention
26690 will be handled as a @code{C} calling convention on non-Windows platforms.
26691
26692 @node Win32 Calling Convention
26693 @subsection @code{Win32} Calling Convention
26694
26695 @noindent
26696 This convention, which is GNAT-specific is fully equivalent to the
26697 @code{Stdcall} calling convention described above.
26698
26699 @node DLL Calling Convention
26700 @subsection @code{DLL} Calling Convention
26701
26702 @noindent
26703 This convention, which is GNAT-specific is fully equivalent to the
26704 @code{Stdcall} calling convention described above.
26705
26706 @node Introduction to Dynamic Link Libraries (DLLs)
26707 @section Introduction to Dynamic Link Libraries (DLLs)
26708 @findex DLL
26709
26710 @noindent
26711 A Dynamically Linked Library (DLL) is a library that can be shared by
26712 several applications running under Windows. A DLL can contain any number of
26713 routines and variables.
26714
26715 One advantage of DLLs is that you can change and enhance them without
26716 forcing all the applications that depend on them to be relinked or
26717 recompiled. However, you should be aware than all calls to DLL routines are
26718 slower since, as you will understand below, such calls are indirect.
26719
26720 To illustrate the remainder of this section, suppose that an application
26721 wants to use the services of a DLL @file{API.dll}. To use the services
26722 provided by @file{API.dll} you must statically link against the DLL or
26723 an import library which contains a jump table with an entry for each
26724 routine and variable exported by the DLL. In the Microsoft world this
26725 import library is called @file{API.lib}. When using GNAT this import
26726 library is called either @file{libAPI.dll.a}, @file{libapi.dll.a},
26727 @file{libAPI.a} or @file{libapi.a} (names are case insensitive).
26728
26729 After you have linked your application with the DLL or the import library
26730 and you run your application, here is what happens:
26731
26732 @enumerate
26733 @item
26734 Your application is loaded into memory.
26735
26736 @item
26737 The DLL @file{API.dll} is mapped into the address space of your
26738 application. This means that:
26739
26740 @itemize @bullet
26741 @item
26742 The DLL will use the stack of the calling thread.
26743
26744 @item
26745 The DLL will use the virtual address space of the calling process.
26746
26747 @item
26748 The DLL will allocate memory from the virtual address space of the calling
26749 process.
26750
26751 @item
26752 Handles (pointers) can be safely exchanged between routines in the DLL
26753 routines and routines in the application using the DLL.
26754 @end itemize
26755
26756 @item
26757 The entries in the jump table (from the import library @file{libAPI.dll.a}
26758 or @file{API.lib} or automatically created when linking against a DLL)
26759 which is part of your application are initialized with the addresses
26760 of the routines and variables in @file{API.dll}.
26761
26762 @item
26763 If present in @file{API.dll}, routines @code{DllMain} or
26764 @code{DllMainCRTStartup} are invoked. These routines typically contain
26765 the initialization code needed for the well-being of the routines and
26766 variables exported by the DLL.
26767 @end enumerate
26768
26769 @noindent
26770 There is an additional point which is worth mentioning. In the Windows
26771 world there are two kind of DLLs: relocatable and non-relocatable
26772 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
26773 in the target application address space. If the addresses of two
26774 non-relocatable DLLs overlap and these happen to be used by the same
26775 application, a conflict will occur and the application will run
26776 incorrectly. Hence, when possible, it is always preferable to use and
26777 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
26778 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
26779 User's Guide) removes the debugging symbols from the DLL but the DLL can
26780 still be relocated.
26781
26782 As a side note, an interesting difference between Microsoft DLLs and
26783 Unix shared libraries, is the fact that on most Unix systems all public
26784 routines are exported by default in a Unix shared library, while under
26785 Windows it is possible (but not required) to list exported routines in
26786 a definition file (@pxref{The Definition File}).
26787
26788 @node Using DLLs with GNAT
26789 @section Using DLLs with GNAT
26790
26791 @menu
26792 * Creating an Ada Spec for the DLL Services::
26793 * Creating an Import Library::
26794 @end menu
26795
26796 @noindent
26797 To use the services of a DLL, say @file{API.dll}, in your Ada application
26798 you must have:
26799
26800 @enumerate
26801 @item
26802 The Ada spec for the routines and/or variables you want to access in
26803 @file{API.dll}. If not available this Ada spec must be built from the C/C++
26804 header files provided with the DLL.
26805
26806 @item
26807 The import library (@file{libAPI.dll.a} or @file{API.lib}). As previously
26808 mentioned an import library is a statically linked library containing the
26809 import table which will be filled at load time to point to the actual
26810 @file{API.dll} routines. Sometimes you don't have an import library for the
26811 DLL you want to use. The following sections will explain how to build
26812 one. Note that this is optional.
26813
26814 @item
26815 The actual DLL, @file{API.dll}.
26816 @end enumerate
26817
26818 @noindent
26819 Once you have all the above, to compile an Ada application that uses the
26820 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
26821 you simply issue the command
26822
26823 @smallexample
26824 $ gnatmake my_ada_app -largs -lAPI
26825 @end smallexample
26826
26827 @noindent
26828 The argument @option{-largs -lAPI} at the end of the @command{gnatmake} command
26829 tells the GNAT linker to look for an import library. The linker will
26830 look for a library name in this specific order:
26831
26832 @enumerate
26833 @item @file{libAPI.dll.a}
26834 @item @file{API.dll.a}
26835 @item @file{libAPI.a}
26836 @item @file{API.lib}
26837 @item @file{libAPI.dll}
26838 @item @file{API.dll}
26839 @end enumerate
26840
26841 The first three are the GNU style import libraries. The third is the
26842 Microsoft style import libraries. The last two are the DLL themself.
26843
26844 Note that if the Ada package spec for @file{API.dll} contains the
26845 following pragma
26846
26847 @smallexample @c ada
26848 pragma Linker_Options ("-lAPI");
26849 @end smallexample
26850
26851 @noindent
26852 you do not have to add @option{-largs -lAPI} at the end of the
26853 @command{gnatmake} command.
26854
26855 If any one of the items above is missing you will have to create it
26856 yourself. The following sections explain how to do so using as an
26857 example a fictitious DLL called @file{API.dll}.
26858
26859 @node Creating an Ada Spec for the DLL Services
26860 @subsection Creating an Ada Spec for the DLL Services
26861
26862 @noindent
26863 A DLL typically comes with a C/C++ header file which provides the
26864 definitions of the routines and variables exported by the DLL. The Ada
26865 equivalent of this header file is a package spec that contains definitions
26866 for the imported entities. If the DLL you intend to use does not come with
26867 an Ada spec you have to generate one such spec yourself. For example if
26868 the header file of @file{API.dll} is a file @file{api.h} containing the
26869 following two definitions:
26870
26871 @smallexample
26872 @group
26873 @cartouche
26874 int some_var;
26875 int get (char *);
26876 @end cartouche
26877 @end group
26878 @end smallexample
26879
26880 @noindent
26881 then the equivalent Ada spec could be:
26882
26883 @smallexample @c ada
26884 @group
26885 @cartouche
26886 with Interfaces.C.Strings;
26887 package API is
26888    use Interfaces;
26889
26890    Some_Var : C.int;
26891    function Get (Str : C.Strings.Chars_Ptr) return C.int;
26892
26893 private
26894    pragma Import (C, Get);
26895    pragma Import (DLL, Some_Var);
26896 end API;
26897 @end cartouche
26898 @end group
26899 @end smallexample
26900
26901 @noindent
26902 Note that a variable is
26903 @strong{always imported with a DLL convention}. A function
26904 can have @code{C} or @code{Stdcall} convention.
26905 (@pxref{Windows Calling Conventions}).
26906
26907 @node Creating an Import Library
26908 @subsection Creating an Import Library
26909 @cindex Import library
26910
26911 @menu
26912 * The Definition File::
26913 * GNAT-Style Import Library::
26914 * Microsoft-Style Import Library::
26915 @end menu
26916
26917 @noindent
26918 If a Microsoft-style import library @file{API.lib} or a GNAT-style
26919 import library @file{libAPI.dll.a} or @file{libAPI.a} is available
26920 with @file{API.dll} you can skip this section. You can also skip this
26921 section if @file{API.dll} or @file{libAPI.dll} is built with GNU tools
26922 as in this case it is possible to link directly against the
26923 DLL. Otherwise read on.
26924
26925 @node The Definition File
26926 @subsubsection The Definition File
26927 @cindex Definition file
26928 @findex .def
26929
26930 @noindent
26931 As previously mentioned, and unlike Unix systems, the list of symbols
26932 that are exported from a DLL must be provided explicitly in Windows.
26933 The main goal of a definition file is precisely that: list the symbols
26934 exported by a DLL. A definition file (usually a file with a @code{.def}
26935 suffix) has the following structure:
26936
26937 @smallexample
26938 @group
26939 @cartouche
26940 @r{[}LIBRARY @var{name}@r{]}
26941 @r{[}DESCRIPTION @var{string}@r{]}
26942 EXPORTS
26943    @var{symbol1}
26944    @var{symbol2}
26945    @dots{}
26946 @end cartouche
26947 @end group
26948 @end smallexample
26949
26950 @table @code
26951 @item LIBRARY @var{name}
26952 This section, which is optional, gives the name of the DLL.
26953
26954 @item DESCRIPTION @var{string}
26955 This section, which is optional, gives a description string that will be
26956 embedded in the import library.
26957
26958 @item EXPORTS
26959 This section gives the list of exported symbols (procedures, functions or
26960 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
26961 section of @file{API.def} looks like:
26962
26963 @smallexample
26964 @group
26965 @cartouche
26966 EXPORTS
26967    some_var
26968    get
26969 @end cartouche
26970 @end group
26971 @end smallexample
26972 @end table
26973
26974 @noindent
26975 Note that you must specify the correct suffix (@code{@@}@code{@var{nn}})
26976 (@pxref{Windows Calling Conventions}) for a Stdcall
26977 calling convention function in the exported symbols list.
26978
26979 @noindent
26980 There can actually be other sections in a definition file, but these
26981 sections are not relevant to the discussion at hand.
26982
26983 @node GNAT-Style Import Library
26984 @subsubsection GNAT-Style Import Library
26985
26986 @noindent
26987 To create a static import library from @file{API.dll} with the GNAT tools
26988 you should proceed as follows:
26989
26990 @enumerate
26991 @item
26992 Create the definition file @file{API.def} (@pxref{The Definition File}).
26993 For that use the @code{dll2def} tool as follows:
26994
26995 @smallexample
26996 $ dll2def API.dll > API.def
26997 @end smallexample
26998
26999 @noindent
27000 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
27001 to standard output the list of entry points in the DLL. Note that if
27002 some routines in the DLL have the @code{Stdcall} convention
27003 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@var{nn}
27004 suffix then you'll have to edit @file{api.def} to add it, and specify
27005 @option{-k} to @command{gnatdll} when creating the import library.
27006
27007 @noindent
27008 Here are some hints to find the right @code{@@}@var{nn} suffix.
27009
27010 @enumerate
27011 @item
27012 If you have the Microsoft import library (.lib), it is possible to get
27013 the right symbols by using Microsoft @code{dumpbin} tool (see the
27014 corresponding Microsoft documentation for further details).
27015
27016 @smallexample
27017 $ dumpbin /exports api.lib
27018 @end smallexample
27019
27020 @item
27021 If you have a message about a missing symbol at link time the compiler
27022 tells you what symbol is expected. You just have to go back to the
27023 definition file and add the right suffix.
27024 @end enumerate
27025
27026 @item
27027 Build the import library @code{libAPI.dll.a}, using @code{gnatdll}
27028 (@pxref{Using gnatdll}) as follows:
27029
27030 @smallexample
27031 $ gnatdll -e API.def -d API.dll
27032 @end smallexample
27033
27034 @noindent
27035 @code{gnatdll} takes as input a definition file @file{API.def} and the
27036 name of the DLL containing the services listed in the definition file
27037 @file{API.dll}. The name of the static import library generated is
27038 computed from the name of the definition file as follows: if the
27039 definition file name is @var{xyz}@code{.def}, the import library name will
27040 be @code{lib}@var{xyz}@code{.a}. Note that in the previous example option
27041 @option{-e} could have been removed because the name of the definition
27042 file (before the ``@code{.def}'' suffix) is the same as the name of the
27043 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
27044 @end enumerate
27045
27046 @node Microsoft-Style Import Library
27047 @subsubsection Microsoft-Style Import Library
27048
27049 @noindent
27050 With GNAT you can either use a GNAT-style or Microsoft-style import
27051 library. A Microsoft import library is needed only if you plan to make an
27052 Ada DLL available to applications developed with Microsoft
27053 tools (@pxref{Mixed-Language Programming on Windows}).
27054
27055 To create a Microsoft-style import library for @file{API.dll} you
27056 should proceed as follows:
27057
27058 @enumerate
27059 @item
27060 Create the definition file @file{API.def} from the DLL. For this use either
27061 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
27062 tool (see the corresponding Microsoft documentation for further details).
27063
27064 @item
27065 Build the actual import library using Microsoft's @code{lib} utility:
27066
27067 @smallexample
27068 $ lib -machine:IX86 -def:API.def -out:API.lib
27069 @end smallexample
27070
27071 @noindent
27072 If you use the above command the definition file @file{API.def} must
27073 contain a line giving the name of the DLL:
27074
27075 @smallexample
27076 LIBRARY      "API"
27077 @end smallexample
27078
27079 @noindent
27080 See the Microsoft documentation for further details about the usage of
27081 @code{lib}.
27082 @end enumerate
27083
27084 @node Building DLLs with GNAT Project files
27085 @section Building DLLs with GNAT Project files
27086 @cindex DLLs, building
27087
27088 @noindent
27089 There is nothing specific to Windows in the build process.
27090 @pxref{Library Projects}.
27091
27092 @noindent
27093 Due to a system limitation, it is not possible under Windows to create threads
27094 when inside the @code{DllMain} routine which is used for auto-initialization
27095 of shared libraries, so it is not possible to have library level tasks in SALs.
27096
27097 @node Building DLLs with GNAT
27098 @section Building DLLs with GNAT
27099 @cindex DLLs, building
27100
27101 @noindent
27102 This section explain how to build DLLs using the GNAT built-in DLL
27103 support. With the following procedure it is straight forward to build
27104 and use DLLs with GNAT.
27105
27106 @enumerate
27107
27108 @item building object files
27109
27110 The first step is to build all objects files that are to be included
27111 into the DLL. This is done by using the standard @command{gnatmake} tool.
27112
27113 @item building the DLL
27114
27115 To build the DLL you must use @command{gcc}'s @option{-shared} and
27116 @option{-shared-libgcc} options. It is quite simple to use this method:
27117
27118 @smallexample
27119 $ gcc -shared -shared-libgcc -o api.dll obj1.o obj2.o @dots{}
27120 @end smallexample
27121
27122 It is important to note that in this case all symbols found in the
27123 object files are automatically exported. It is possible to restrict
27124 the set of symbols to export by passing to @command{gcc} a definition
27125 file, @pxref{The Definition File}. For example:
27126
27127 @smallexample
27128 $ gcc -shared -shared-libgcc -o api.dll api.def obj1.o obj2.o @dots{}
27129 @end smallexample
27130
27131 If you use a definition file you must export the elaboration procedures
27132 for every package that required one. Elaboration procedures are named
27133 using the package name followed by "_E".
27134
27135 @item preparing DLL to be used
27136
27137 For the DLL to be used by client programs the bodies must be hidden
27138 from it and the .ali set with read-only attribute. This is very important
27139 otherwise GNAT will recompile all packages and will not actually use
27140 the code in the DLL. For example:
27141
27142 @smallexample
27143 $ mkdir apilib
27144 $ copy *.ads *.ali api.dll apilib
27145 $ attrib +R apilib\*.ali
27146 @end smallexample
27147
27148 @end enumerate
27149
27150 At this point it is possible to use the DLL by directly linking
27151 against it. Note that you must use the GNAT shared runtime when using
27152 GNAT shared libraries. This is achieved by using @option{-shared} binder's
27153 option.
27154
27155 @smallexample
27156 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
27157 @end smallexample
27158
27159 @node Building DLLs with gnatdll
27160 @section Building DLLs with gnatdll
27161 @cindex DLLs, building
27162
27163 @menu
27164 * Limitations When Using Ada DLLs from Ada::
27165 * Exporting Ada Entities::
27166 * Ada DLLs and Elaboration::
27167 * Ada DLLs and Finalization::
27168 * Creating a Spec for Ada DLLs::
27169 * Creating the Definition File::
27170 * Using gnatdll::
27171 @end menu
27172
27173 @noindent
27174 Note that it is preferred to use GNAT Project files
27175 (@pxref{Building DLLs with GNAT Project files}) or the built-in GNAT
27176 DLL support (@pxref{Building DLLs with GNAT}) or to build DLLs.
27177
27178 This section explains how to build DLLs containing Ada code using
27179 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
27180 remainder of this section.
27181
27182 The steps required to build an Ada DLL that is to be used by Ada as well as
27183 non-Ada applications are as follows:
27184
27185 @enumerate
27186 @item
27187 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
27188 @code{Stdcall} calling convention to avoid any Ada name mangling for the
27189 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
27190 skip this step if you plan to use the Ada DLL only from Ada applications.
27191
27192 @item
27193 Your Ada code must export an initialization routine which calls the routine
27194 @code{adainit} generated by @command{gnatbind} to perform the elaboration of
27195 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
27196 routine exported by the Ada DLL must be invoked by the clients of the DLL
27197 to initialize the DLL.
27198
27199 @item
27200 When useful, the DLL should also export a finalization routine which calls
27201 routine @code{adafinal} generated by @command{gnatbind} to perform the
27202 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
27203 The finalization routine exported by the Ada DLL must be invoked by the
27204 clients of the DLL when the DLL services are no further needed.
27205
27206 @item
27207 You must provide a spec for the services exported by the Ada DLL in each
27208 of the programming languages to which you plan to make the DLL available.
27209
27210 @item
27211 You must provide a definition file listing the exported entities
27212 (@pxref{The Definition File}).
27213
27214 @item
27215 Finally you must use @code{gnatdll} to produce the DLL and the import
27216 library (@pxref{Using gnatdll}).
27217 @end enumerate
27218
27219 @noindent
27220 Note that a relocatable DLL stripped using the @code{strip}
27221 binutils tool will not be relocatable anymore. To build a DLL without
27222 debug information pass @code{-largs -s} to @code{gnatdll}. This
27223 restriction does not apply to a DLL built using a Library Project.
27224 @pxref{Library Projects}.
27225
27226 @node Limitations When Using Ada DLLs from Ada
27227 @subsection Limitations When Using Ada DLLs from Ada
27228
27229 @noindent
27230 When using Ada DLLs from Ada applications there is a limitation users
27231 should be aware of. Because on Windows the GNAT run time is not in a DLL of
27232 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
27233 each Ada DLL includes the services of the GNAT run time that are necessary
27234 to the Ada code inside the DLL. As a result, when an Ada program uses an
27235 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
27236 one in the main program.
27237
27238 It is therefore not possible to exchange GNAT run-time objects between the
27239 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
27240 handles (e.g.@: @code{Text_IO.File_Type}), tasks types, protected objects
27241 types, etc.
27242
27243 It is completely safe to exchange plain elementary, array or record types,
27244 Windows object handles, etc.
27245
27246 @node Exporting Ada Entities
27247 @subsection Exporting Ada Entities
27248 @cindex Export table
27249
27250 @noindent
27251 Building a DLL is a way to encapsulate a set of services usable from any
27252 application. As a result, the Ada entities exported by a DLL should be
27253 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
27254 any Ada name mangling. As an example here is an Ada package
27255 @code{API}, spec and body, exporting two procedures, a function, and a
27256 variable:
27257
27258 @smallexample @c ada
27259 @group
27260 @cartouche
27261 with Interfaces.C; use Interfaces;
27262 package API is
27263    Count : C.int := 0;
27264    function Factorial (Val : C.int) return C.int;
27265
27266    procedure Initialize_API;
27267    procedure Finalize_API;
27268    --  Initialization & Finalization routines. More in the next section.
27269 private
27270    pragma Export (C, Initialize_API);
27271    pragma Export (C, Finalize_API);
27272    pragma Export (C, Count);
27273    pragma Export (C, Factorial);
27274 end API;
27275 @end cartouche
27276 @end group
27277 @end smallexample
27278
27279 @smallexample @c ada
27280 @group
27281 @cartouche
27282 package body API is
27283    function Factorial (Val : C.int) return C.int is
27284       Fact : C.int := 1;
27285    begin
27286       Count := Count + 1;
27287       for K in 1 .. Val loop
27288          Fact := Fact * K;
27289       end loop;
27290       return Fact;
27291    end Factorial;
27292
27293    procedure Initialize_API is
27294       procedure Adainit;
27295       pragma Import (C, Adainit);
27296    begin
27297       Adainit;
27298    end Initialize_API;
27299
27300    procedure Finalize_API is
27301       procedure Adafinal;
27302       pragma Import (C, Adafinal);
27303    begin
27304       Adafinal;
27305    end Finalize_API;
27306 end API;
27307 @end cartouche
27308 @end group
27309 @end smallexample
27310
27311 @noindent
27312 If the Ada DLL you are building will only be used by Ada applications
27313 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
27314 convention. As an example, the previous package could be written as
27315 follows:
27316
27317 @smallexample @c ada
27318 @group
27319 @cartouche
27320 package API is
27321    Count : Integer := 0;
27322    function Factorial (Val : Integer) return Integer;
27323
27324    procedure Initialize_API;
27325    procedure Finalize_API;
27326    --  Initialization and Finalization routines.
27327 end API;
27328 @end cartouche
27329 @end group
27330 @end smallexample
27331
27332 @smallexample @c ada
27333 @group
27334 @cartouche
27335 package body API is
27336    function Factorial (Val : Integer) return Integer is
27337       Fact : Integer := 1;
27338    begin
27339       Count := Count + 1;
27340       for K in 1 .. Val loop
27341          Fact := Fact * K;
27342       end loop;
27343       return Fact;
27344    end Factorial;
27345
27346    @dots{}
27347    --  The remainder of this package body is unchanged.
27348 end API;
27349 @end cartouche
27350 @end group
27351 @end smallexample
27352
27353 @noindent
27354 Note that if you do not export the Ada entities with a @code{C} or
27355 @code{Stdcall} convention you will have to provide the mangled Ada names
27356 in the definition file of the Ada DLL
27357 (@pxref{Creating the Definition File}).
27358
27359 @node Ada DLLs and Elaboration
27360 @subsection Ada DLLs and Elaboration
27361 @cindex DLLs and elaboration
27362
27363 @noindent
27364 The DLL that you are building contains your Ada code as well as all the
27365 routines in the Ada library that are needed by it. The first thing a
27366 user of your DLL must do is elaborate the Ada code
27367 (@pxref{Elaboration Order Handling in GNAT}).
27368
27369 To achieve this you must export an initialization routine
27370 (@code{Initialize_API} in the previous example), which must be invoked
27371 before using any of the DLL services. This elaboration routine must call
27372 the Ada elaboration routine @code{adainit} generated by the GNAT binder
27373 (@pxref{Binding with Non-Ada Main Programs}). See the body of
27374 @code{Initialize_Api} for an example. Note that the GNAT binder is
27375 automatically invoked during the DLL build process by the @code{gnatdll}
27376 tool (@pxref{Using gnatdll}).
27377
27378 When a DLL is loaded, Windows systematically invokes a routine called
27379 @code{DllMain}. It would therefore be possible to call @code{adainit}
27380 directly from @code{DllMain} without having to provide an explicit
27381 initialization routine. Unfortunately, it is not possible to call
27382 @code{adainit} from the @code{DllMain} if your program has library level
27383 tasks because access to the @code{DllMain} entry point is serialized by
27384 the system (that is, only a single thread can execute ``through'' it at a
27385 time), which means that the GNAT run time will deadlock waiting for the
27386 newly created task to complete its initialization.
27387
27388 @node Ada DLLs and Finalization
27389 @subsection Ada DLLs and Finalization
27390 @cindex DLLs and finalization
27391
27392 @noindent
27393 When the services of an Ada DLL are no longer needed, the client code should
27394 invoke the DLL finalization routine, if available. The DLL finalization
27395 routine is in charge of releasing all resources acquired by the DLL. In the
27396 case of the Ada code contained in the DLL, this is achieved by calling
27397 routine @code{adafinal} generated by the GNAT binder
27398 (@pxref{Binding with Non-Ada Main Programs}).
27399 See the body of @code{Finalize_Api} for an
27400 example. As already pointed out the GNAT binder is automatically invoked
27401 during the DLL build process by the @code{gnatdll} tool
27402 (@pxref{Using gnatdll}).
27403
27404 @node Creating a Spec for Ada DLLs
27405 @subsection Creating a Spec for Ada DLLs
27406
27407 @noindent
27408 To use the services exported by the Ada DLL from another programming
27409 language (e.g.@: C), you have to translate the specs of the exported Ada
27410 entities in that language. For instance in the case of @code{API.dll},
27411 the corresponding C header file could look like:
27412
27413 @smallexample
27414 @group
27415 @cartouche
27416 extern int *_imp__count;
27417 #define count (*_imp__count)
27418 int factorial (int);
27419 @end cartouche
27420 @end group
27421 @end smallexample
27422
27423 @noindent
27424 It is important to understand that when building an Ada DLL to be used by
27425 other Ada applications, you need two different specs for the packages
27426 contained in the DLL: one for building the DLL and the other for using
27427 the DLL. This is because the @code{DLL} calling convention is needed to
27428 use a variable defined in a DLL, but when building the DLL, the variable
27429 must have either the @code{Ada} or @code{C} calling convention. As an
27430 example consider a DLL comprising the following package @code{API}:
27431
27432 @smallexample @c ada
27433 @group
27434 @cartouche
27435 package API is
27436    Count : Integer := 0;
27437    @dots{}
27438    --  Remainder of the package omitted.
27439 end API;
27440 @end cartouche
27441 @end group
27442 @end smallexample
27443
27444 @noindent
27445 After producing a DLL containing package @code{API}, the spec that
27446 must be used to import @code{API.Count} from Ada code outside of the
27447 DLL is:
27448
27449 @smallexample @c ada
27450 @group
27451 @cartouche
27452 package API is
27453    Count : Integer;
27454    pragma Import (DLL, Count);
27455 end API;
27456 @end cartouche
27457 @end group
27458 @end smallexample
27459
27460 @node Creating the Definition File
27461 @subsection Creating the Definition File
27462
27463 @noindent
27464 The definition file is the last file needed to build the DLL. It lists
27465 the exported symbols. As an example, the definition file for a DLL
27466 containing only package @code{API} (where all the entities are exported
27467 with a @code{C} calling convention) is:
27468
27469 @smallexample
27470 @group
27471 @cartouche
27472 EXPORTS
27473     count
27474     factorial
27475     finalize_api
27476     initialize_api
27477 @end cartouche
27478 @end group
27479 @end smallexample
27480
27481 @noindent
27482 If the @code{C} calling convention is missing from package @code{API},
27483 then the definition file contains the mangled Ada names of the above
27484 entities, which in this case are:
27485
27486 @smallexample
27487 @group
27488 @cartouche
27489 EXPORTS
27490     api__count
27491     api__factorial
27492     api__finalize_api
27493     api__initialize_api
27494 @end cartouche
27495 @end group
27496 @end smallexample
27497
27498 @node Using gnatdll
27499 @subsection Using @code{gnatdll}
27500 @findex gnatdll
27501
27502 @menu
27503 * gnatdll Example::
27504 * gnatdll behind the Scenes::
27505 * Using dlltool::
27506 @end menu
27507
27508 @noindent
27509 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
27510 and non-Ada sources that make up your DLL have been compiled.
27511 @code{gnatdll} is actually in charge of two distinct tasks: build the
27512 static import library for the DLL and the actual DLL. The form of the
27513 @code{gnatdll} command is
27514
27515 @smallexample
27516 @cartouche
27517 @c $ gnatdll @ovar{switches} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
27518 @c Expanding @ovar macro inline (explanation in macro def comments)
27519 $ gnatdll @r{[}@var{switches}@r{]} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
27520 @end cartouche
27521 @end smallexample
27522
27523 @noindent
27524 where @var{list-of-files} is a list of ALI and object files. The object
27525 file list must be the exact list of objects corresponding to the non-Ada
27526 sources whose services are to be included in the DLL. The ALI file list
27527 must be the exact list of ALI files for the corresponding Ada sources
27528 whose services are to be included in the DLL. If @var{list-of-files} is
27529 missing, only the static import library is generated.
27530
27531 @noindent
27532 You may specify any of the following switches to @code{gnatdll}:
27533
27534 @table @code
27535 @c @item -a@ovar{address}
27536 @c Expanding @ovar macro inline (explanation in macro def comments)
27537 @item -a@r{[}@var{address}@r{]}
27538 @cindex @option{-a} (@code{gnatdll})
27539 Build a non-relocatable DLL at @var{address}. If @var{address} is not
27540 specified the default address @var{0x11000000} will be used. By default,
27541 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
27542 advise the reader to build relocatable DLL.
27543
27544 @item -b @var{address}
27545 @cindex @option{-b} (@code{gnatdll})
27546 Set the relocatable DLL base address. By default the address is
27547 @code{0x11000000}.
27548
27549 @item -bargs @var{opts}
27550 @cindex @option{-bargs} (@code{gnatdll})
27551 Binder options. Pass @var{opts} to the binder.
27552
27553 @item -d @var{dllfile}
27554 @cindex @option{-d} (@code{gnatdll})
27555 @var{dllfile} is the name of the DLL. This switch must be present for
27556 @code{gnatdll} to do anything. The name of the generated import library is
27557 obtained algorithmically from @var{dllfile} as shown in the following
27558 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
27559 @code{libxyz.dll.a}. The name of the definition file to use (if not specified
27560 by option @option{-e}) is obtained algorithmically from @var{dllfile}
27561 as shown in the following example:
27562 if @var{dllfile} is @code{xyz.dll}, the definition
27563 file used is @code{xyz.def}.
27564
27565 @item -e @var{deffile}
27566 @cindex @option{-e} (@code{gnatdll})
27567 @var{deffile} is the name of the definition file.
27568
27569 @item -g
27570 @cindex @option{-g} (@code{gnatdll})
27571 Generate debugging information. This information is stored in the object
27572 file and copied from there to the final DLL file by the linker,
27573 where it can be read by the debugger. You must use the
27574 @option{-g} switch if you plan on using the debugger or the symbolic
27575 stack traceback.
27576
27577 @item -h
27578 @cindex @option{-h} (@code{gnatdll})
27579 Help mode. Displays @code{gnatdll} switch usage information.
27580
27581 @item -Idir
27582 @cindex @option{-I} (@code{gnatdll})
27583 Direct @code{gnatdll} to search the @var{dir} directory for source and
27584 object files needed to build the DLL.
27585 (@pxref{Search Paths and the Run-Time Library (RTL)}).
27586
27587 @item -k
27588 @cindex @option{-k} (@code{gnatdll})
27589 Removes the @code{@@}@var{nn} suffix from the import library's exported
27590 names, but keeps them for the link names. You must specify this
27591 option if you want to use a @code{Stdcall} function in a DLL for which
27592 the @code{@@}@var{nn} suffix has been removed. This is the case for most
27593 of the Windows NT DLL for example. This option has no effect when
27594 @option{-n} option is specified.
27595
27596 @item -l @var{file}
27597 @cindex @option{-l} (@code{gnatdll})
27598 The list of ALI and object files used to build the DLL are listed in
27599 @var{file}, instead of being given in the command line. Each line in
27600 @var{file} contains the name of an ALI or object file.
27601
27602 @item -n
27603 @cindex @option{-n} (@code{gnatdll})
27604 No Import. Do not create the import library.
27605
27606 @item -q
27607 @cindex @option{-q} (@code{gnatdll})
27608 Quiet mode. Do not display unnecessary messages.
27609
27610 @item -v
27611 @cindex @option{-v} (@code{gnatdll})
27612 Verbose mode. Display extra information.
27613
27614 @item -largs @var{opts}
27615 @cindex @option{-largs} (@code{gnatdll})
27616 Linker options. Pass @var{opts} to the linker.
27617 @end table
27618
27619 @node gnatdll Example
27620 @subsubsection @code{gnatdll} Example
27621
27622 @noindent
27623 As an example the command to build a relocatable DLL from @file{api.adb}
27624 once @file{api.adb} has been compiled and @file{api.def} created is
27625
27626 @smallexample
27627 $ gnatdll -d api.dll api.ali
27628 @end smallexample
27629
27630 @noindent
27631 The above command creates two files: @file{libapi.dll.a} (the import
27632 library) and @file{api.dll} (the actual DLL). If you want to create
27633 only the DLL, just type:
27634
27635 @smallexample
27636 $ gnatdll -d api.dll -n api.ali
27637 @end smallexample
27638
27639 @noindent
27640 Alternatively if you want to create just the import library, type:
27641
27642 @smallexample
27643 $ gnatdll -d api.dll
27644 @end smallexample
27645
27646 @node gnatdll behind the Scenes
27647 @subsubsection @code{gnatdll} behind the Scenes
27648
27649 @noindent
27650 This section details the steps involved in creating a DLL. @code{gnatdll}
27651 does these steps for you. Unless you are interested in understanding what
27652 goes on behind the scenes, you should skip this section.
27653
27654 We use the previous example of a DLL containing the Ada package @code{API},
27655 to illustrate the steps necessary to build a DLL. The starting point is a
27656 set of objects that will make up the DLL and the corresponding ALI
27657 files. In the case of this example this means that @file{api.o} and
27658 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
27659 the following:
27660
27661 @enumerate
27662 @item
27663 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
27664 the information necessary to generate relocation information for the
27665 DLL.
27666
27667 @smallexample
27668 @group
27669 $ gnatbind -n api
27670 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
27671 @end group
27672 @end smallexample
27673
27674 @noindent
27675 In addition to the base file, the @command{gnatlink} command generates an
27676 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
27677 asks @command{gnatlink} to generate the routines @code{DllMain} and
27678 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
27679 is loaded into memory.
27680
27681 @item
27682 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
27683 export table (@file{api.exp}). The export table contains the relocation
27684 information in a form which can be used during the final link to ensure
27685 that the Windows loader is able to place the DLL anywhere in memory.
27686
27687 @smallexample
27688 @group
27689 $ dlltool --dllname api.dll --def api.def --base-file api.base \
27690           --output-exp api.exp
27691 @end group
27692 @end smallexample
27693
27694 @item
27695 @code{gnatdll} builds the base file using the new export table. Note that
27696 @command{gnatbind} must be called once again since the binder generated file
27697 has been deleted during the previous call to @command{gnatlink}.
27698
27699 @smallexample
27700 @group
27701 $ gnatbind -n api
27702 $ gnatlink api -o api.jnk api.exp -mdll
27703       -Wl,--base-file,api.base
27704 @end group
27705 @end smallexample
27706
27707 @item
27708 @code{gnatdll} builds the new export table using the new base file and
27709 generates the DLL import library @file{libAPI.dll.a}.
27710
27711 @smallexample
27712 @group
27713 $ dlltool --dllname api.dll --def api.def --base-file api.base \
27714           --output-exp api.exp --output-lib libAPI.a
27715 @end group
27716 @end smallexample
27717
27718 @item
27719 Finally @code{gnatdll} builds the relocatable DLL using the final export
27720 table.
27721
27722 @smallexample
27723 @group
27724 $ gnatbind -n api
27725 $ gnatlink api api.exp -o api.dll -mdll
27726 @end group
27727 @end smallexample
27728 @end enumerate
27729
27730 @node Using dlltool
27731 @subsubsection Using @code{dlltool}
27732
27733 @noindent
27734 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
27735 DLLs and static import libraries. This section summarizes the most
27736 common @code{dlltool} switches. The form of the @code{dlltool} command
27737 is
27738
27739 @smallexample
27740 @c $ dlltool @ovar{switches}
27741 @c Expanding @ovar macro inline (explanation in macro def comments)
27742 $ dlltool @r{[}@var{switches}@r{]}
27743 @end smallexample
27744
27745 @noindent
27746 @code{dlltool} switches include:
27747
27748 @table @option
27749 @item --base-file @var{basefile}
27750 @cindex @option{--base-file} (@command{dlltool})
27751 Read the base file @var{basefile} generated by the linker. This switch
27752 is used to create a relocatable DLL.
27753
27754 @item --def @var{deffile}
27755 @cindex @option{--def} (@command{dlltool})
27756 Read the definition file.
27757
27758 @item --dllname @var{name}
27759 @cindex @option{--dllname} (@command{dlltool})
27760 Gives the name of the DLL. This switch is used to embed the name of the
27761 DLL in the static import library generated by @code{dlltool} with switch
27762 @option{--output-lib}.
27763
27764 @item -k
27765 @cindex @option{-k} (@command{dlltool})
27766 Kill @code{@@}@var{nn} from exported names
27767 (@pxref{Windows Calling Conventions}
27768 for a discussion about @code{Stdcall}-style symbols.
27769
27770 @item --help
27771 @cindex @option{--help} (@command{dlltool})
27772 Prints the @code{dlltool} switches with a concise description.
27773
27774 @item --output-exp @var{exportfile}
27775 @cindex @option{--output-exp} (@command{dlltool})
27776 Generate an export file @var{exportfile}. The export file contains the
27777 export table (list of symbols in the DLL) and is used to create the DLL.
27778
27779 @item --output-lib @var{libfile}
27780 @cindex @option{--output-lib} (@command{dlltool})
27781 Generate a static import library @var{libfile}.
27782
27783 @item -v
27784 @cindex @option{-v} (@command{dlltool})
27785 Verbose mode.
27786
27787 @item --as @var{assembler-name}
27788 @cindex @option{--as} (@command{dlltool})
27789 Use @var{assembler-name} as the assembler. The default is @code{as}.
27790 @end table
27791
27792 @node GNAT and Windows Resources
27793 @section GNAT and Windows Resources
27794 @cindex Resources, windows
27795
27796 @menu
27797 * Building Resources::
27798 * Compiling Resources::
27799 * Using Resources::
27800 @end menu
27801
27802 @noindent
27803 Resources are an easy way to add Windows specific objects to your
27804 application. The objects that can be added as resources include:
27805
27806 @itemize @bullet
27807 @item
27808 menus
27809
27810 @item
27811 accelerators
27812
27813 @item
27814 dialog boxes
27815
27816 @item
27817 string tables
27818
27819 @item
27820 bitmaps
27821
27822 @item
27823 cursors
27824
27825 @item
27826 icons
27827
27828 @item
27829 fonts
27830 @end itemize
27831
27832 @noindent
27833 This section explains how to build, compile and use resources.
27834
27835 @node Building Resources
27836 @subsection Building Resources
27837 @cindex Resources, building
27838
27839 @noindent
27840 A resource file is an ASCII file. By convention resource files have an
27841 @file{.rc} extension.
27842 The easiest way to build a resource file is to use Microsoft tools
27843 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
27844 @code{dlgedit.exe} to build dialogs.
27845 It is always possible to build an @file{.rc} file yourself by writing a
27846 resource script.
27847
27848 It is not our objective to explain how to write a resource file. A
27849 complete description of the resource script language can be found in the
27850 Microsoft documentation.
27851
27852 @node Compiling Resources
27853 @subsection Compiling Resources
27854 @findex rc
27855 @findex windres
27856 @cindex Resources, compiling
27857
27858 @noindent
27859 This section describes how to build a GNAT-compatible (COFF) object file
27860 containing the resources. This is done using the Resource Compiler
27861 @code{windres} as follows:
27862
27863 @smallexample
27864 $ windres -i myres.rc -o myres.o
27865 @end smallexample
27866
27867 @noindent
27868 By default @code{windres} will run @command{gcc} to preprocess the @file{.rc}
27869 file. You can specify an alternate preprocessor (usually named
27870 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
27871 parameter. A list of all possible options may be obtained by entering
27872 the command @code{windres} @option{--help}.
27873
27874 It is also possible to use the Microsoft resource compiler @code{rc.exe}
27875 to produce a @file{.res} file (binary resource file). See the
27876 corresponding Microsoft documentation for further details. In this case
27877 you need to use @code{windres} to translate the @file{.res} file to a
27878 GNAT-compatible object file as follows:
27879
27880 @smallexample
27881 $ windres -i myres.res -o myres.o
27882 @end smallexample
27883
27884 @node Using Resources
27885 @subsection Using Resources
27886 @cindex Resources, using
27887
27888 @noindent
27889 To include the resource file in your program just add the
27890 GNAT-compatible object file for the resource(s) to the linker
27891 arguments. With @command{gnatmake} this is done by using the @option{-largs}
27892 option:
27893
27894 @smallexample
27895 $ gnatmake myprog -largs myres.o
27896 @end smallexample
27897
27898 @node Debugging a DLL
27899 @section Debugging a DLL
27900 @cindex DLL debugging
27901
27902 @menu
27903 * Program and DLL Both Built with GCC/GNAT::
27904 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
27905 @end menu
27906
27907 @noindent
27908 Debugging a DLL is similar to debugging a standard program. But
27909 we have to deal with two different executable parts: the DLL and the
27910 program that uses it. We have the following four possibilities:
27911
27912 @enumerate 1
27913 @item
27914 The program and the DLL are built with @code{GCC/GNAT}.
27915 @item
27916 The program is built with foreign tools and the DLL is built with
27917 @code{GCC/GNAT}.
27918 @item
27919 The program is built with @code{GCC/GNAT} and the DLL is built with
27920 foreign tools.
27921 @end enumerate
27922
27923 @noindent
27924 In this section we address only cases one and two above.
27925 There is no point in trying to debug
27926 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
27927 information in it. To do so you must use a debugger compatible with the
27928 tools suite used to build the DLL.
27929
27930 @node Program and DLL Both Built with GCC/GNAT
27931 @subsection Program and DLL Both Built with GCC/GNAT
27932
27933 @noindent
27934 This is the simplest case. Both the DLL and the program have @code{GDB}
27935 compatible debugging information. It is then possible to break anywhere in
27936 the process. Let's suppose here that the main procedure is named
27937 @code{ada_main} and that in the DLL there is an entry point named
27938 @code{ada_dll}.
27939
27940 @noindent
27941 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
27942 program must have been built with the debugging information (see GNAT -g
27943 switch). Here are the step-by-step instructions for debugging it:
27944
27945 @enumerate 1
27946 @item Launch @code{GDB} on the main program.
27947
27948 @smallexample
27949 $ gdb -nw ada_main
27950 @end smallexample
27951
27952 @item Start the program and stop at the beginning of the main procedure
27953
27954 @smallexample
27955 (gdb) start
27956 @end smallexample
27957
27958 @noindent
27959 This step is required to be able to set a breakpoint inside the DLL. As long
27960 as the program is not run, the DLL is not loaded. This has the
27961 consequence that the DLL debugging information is also not loaded, so it is not
27962 possible to set a breakpoint in the DLL.
27963
27964 @item Set a breakpoint inside the DLL
27965
27966 @smallexample
27967 (gdb) break ada_dll
27968 (gdb) cont
27969 @end smallexample
27970
27971 @end enumerate
27972
27973 @noindent
27974 At this stage a breakpoint is set inside the DLL. From there on
27975 you can use the standard approach to debug the whole program
27976 (@pxref{Running and Debugging Ada Programs}).
27977
27978 @ignore
27979 @c This used to work, probably because the DLLs were non-relocatable
27980 @c keep this section around until the problem is sorted out.
27981
27982 To break on the @code{DllMain} routine it is not possible to follow
27983 the procedure above. At the time the program stop on @code{ada_main}
27984 the @code{DllMain} routine as already been called. Either you can use
27985 the procedure below @pxref{Debugging the DLL Directly} or this procedure:
27986
27987 @enumerate 1
27988 @item Launch @code{GDB} on the main program.
27989
27990 @smallexample
27991 $ gdb ada_main
27992 @end smallexample
27993
27994 @item Load DLL symbols
27995
27996 @smallexample
27997 (gdb) add-sym api.dll
27998 @end smallexample
27999
28000 @item Set a breakpoint inside the DLL
28001
28002 @smallexample
28003 (gdb) break ada_dll.adb:45
28004 @end smallexample
28005
28006 Note that at this point it is not possible to break using the routine symbol
28007 directly as the program is not yet running. The solution is to break
28008 on the proper line (break in @file{ada_dll.adb} line 45).
28009
28010 @item Start the program
28011
28012 @smallexample
28013 (gdb) run
28014 @end smallexample
28015
28016 @end enumerate
28017 @end ignore
28018
28019 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
28020 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
28021
28022 @menu
28023 * Debugging the DLL Directly::
28024 * Attaching to a Running Process::
28025 @end menu
28026
28027 @noindent
28028 In this case things are slightly more complex because it is not possible to
28029 start the main program and then break at the beginning to load the DLL and the
28030 associated DLL debugging information. It is not possible to break at the
28031 beginning of the program because there is no @code{GDB} debugging information,
28032 and therefore there is no direct way of getting initial control. This
28033 section addresses this issue by describing some methods that can be used
28034 to break somewhere in the DLL to debug it.
28035
28036 @noindent
28037 First suppose that the main procedure is named @code{main} (this is for
28038 example some C code built with Microsoft Visual C) and that there is a
28039 DLL named @code{test.dll} containing an Ada entry point named
28040 @code{ada_dll}.
28041
28042 @noindent
28043 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
28044 been built with debugging information (see GNAT -g option).
28045
28046 @node Debugging the DLL Directly
28047 @subsubsection Debugging the DLL Directly
28048
28049 @enumerate 1
28050 @item
28051 Find out the executable starting address
28052
28053 @smallexample
28054 $ objdump --file-header main.exe
28055 @end smallexample
28056
28057 The starting address is reported on the last line. For example:
28058
28059 @smallexample
28060 main.exe:     file format pei-i386
28061 architecture: i386, flags 0x0000010a:
28062 EXEC_P, HAS_DEBUG, D_PAGED
28063 start address 0x00401010
28064 @end smallexample
28065
28066 @item
28067 Launch the debugger on the executable.
28068
28069 @smallexample
28070 $ gdb main.exe
28071 @end smallexample
28072
28073 @item
28074 Set a breakpoint at the starting address, and launch the program.
28075
28076 @smallexample
28077 $ (gdb) break *0x00401010
28078 $ (gdb) run
28079 @end smallexample
28080
28081 The program will stop at the given address.
28082
28083 @item
28084 Set a breakpoint on a DLL subroutine.
28085
28086 @smallexample
28087 (gdb) break ada_dll.adb:45
28088 @end smallexample
28089
28090 Or if you want to break using a symbol on the DLL, you need first to
28091 select the Ada language (language used by the DLL).
28092
28093 @smallexample
28094 (gdb) set language ada
28095 (gdb) break ada_dll
28096 @end smallexample
28097
28098 @item
28099 Continue the program.
28100
28101 @smallexample
28102 (gdb) cont
28103 @end smallexample
28104
28105 @noindent
28106 This will run the program until it reaches the breakpoint that has been
28107 set. From that point you can use the standard way to debug a program
28108 as described in (@pxref{Running and Debugging Ada Programs}).
28109
28110 @end enumerate
28111
28112 @noindent
28113 It is also possible to debug the DLL by attaching to a running process.
28114
28115 @node Attaching to a Running Process
28116 @subsubsection Attaching to a Running Process
28117 @cindex DLL debugging, attach to process
28118
28119 @noindent
28120 With @code{GDB} it is always possible to debug a running process by
28121 attaching to it. It is possible to debug a DLL this way. The limitation
28122 of this approach is that the DLL must run long enough to perform the
28123 attach operation. It may be useful for instance to insert a time wasting
28124 loop in the code of the DLL to meet this criterion.
28125
28126 @enumerate 1
28127
28128 @item Launch the main program @file{main.exe}.
28129
28130 @smallexample
28131 $ main
28132 @end smallexample
28133
28134 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
28135 that the process PID for @file{main.exe} is 208.
28136
28137 @item Launch gdb.
28138
28139 @smallexample
28140 $ gdb
28141 @end smallexample
28142
28143 @item Attach to the running process to be debugged.
28144
28145 @smallexample
28146 (gdb) attach 208
28147 @end smallexample
28148
28149 @item Load the process debugging information.
28150
28151 @smallexample
28152 (gdb) symbol-file main.exe
28153 @end smallexample
28154
28155 @item Break somewhere in the DLL.
28156
28157 @smallexample
28158 (gdb) break ada_dll
28159 @end smallexample
28160
28161 @item Continue process execution.
28162
28163 @smallexample
28164 (gdb) cont
28165 @end smallexample
28166
28167 @end enumerate
28168
28169 @noindent
28170 This last step will resume the process execution, and stop at
28171 the breakpoint we have set. From there you can use the standard
28172 approach to debug a program as described in
28173 (@pxref{Running and Debugging Ada Programs}).
28174
28175 @node Setting Stack Size from gnatlink
28176 @section Setting Stack Size from @command{gnatlink}
28177
28178 @noindent
28179 It is possible to specify the program stack size at link time. On modern
28180 versions of Windows, starting with XP, this is mostly useful to set the size of
28181 the main stack (environment task). The other task stacks are set with pragma
28182 Storage_Size or with the @command{gnatbind -d} command.
28183
28184 Since older versions of Windows (2000, NT4, etc.) do not allow setting the
28185 reserve size of individual tasks, the link-time stack size applies to all
28186 tasks, and pragma Storage_Size has no effect.
28187 In particular, Stack Overflow checks are made against this
28188 link-time specified size.
28189
28190 This setting can be done with
28191 @command{gnatlink} using either:
28192
28193 @itemize @bullet
28194
28195 @item using @option{-Xlinker} linker option
28196
28197 @smallexample
28198 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
28199 @end smallexample
28200
28201 This sets the stack reserve size to 0x10000 bytes and the stack commit
28202 size to 0x1000 bytes.
28203
28204 @item using @option{-Wl} linker option
28205
28206 @smallexample
28207 $ gnatlink hello -Wl,--stack=0x1000000
28208 @end smallexample
28209
28210 This sets the stack reserve size to 0x1000000 bytes. Note that with
28211 @option{-Wl} option it is not possible to set the stack commit size
28212 because the coma is a separator for this option.
28213
28214 @end itemize
28215
28216 @node Setting Heap Size from gnatlink
28217 @section Setting Heap Size from @command{gnatlink}
28218
28219 @noindent
28220 Under Windows systems, it is possible to specify the program heap size from
28221 @command{gnatlink} using either:
28222
28223 @itemize @bullet
28224
28225 @item using @option{-Xlinker} linker option
28226
28227 @smallexample
28228 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
28229 @end smallexample
28230
28231 This sets the heap reserve size to 0x10000 bytes and the heap commit
28232 size to 0x1000 bytes.
28233
28234 @item using @option{-Wl} linker option
28235
28236 @smallexample
28237 $ gnatlink hello -Wl,--heap=0x1000000
28238 @end smallexample
28239
28240 This sets the heap reserve size to 0x1000000 bytes. Note that with
28241 @option{-Wl} option it is not possible to set the heap commit size
28242 because the coma is a separator for this option.
28243
28244 @end itemize
28245
28246 @end ifset
28247
28248 @c **********************************
28249 @c * GNU Free Documentation License *
28250 @c **********************************
28251 @include fdl.texi
28252 @c GNU Free Documentation License
28253
28254 @node Index,,GNU Free Documentation License, Top
28255 @unnumbered Index
28256
28257 @printindex cp
28258
28259 @contents
28260 @c Put table of contents at end, otherwise it precedes the "title page" in
28261 @c the .txt version
28262 @c Edit the pdf file to move the contents to the beginning, after the title
28263 @c page
28264
28265 @bye