OSDN Git Service

abf8093a8ed6416a69131f55e5b6efcf767ce08d
[pf3gnuchains/gcc-fork.git] / gcc / ada / gnat_ugn.texi
1 \input texinfo   @c -*-texinfo-*-
2 @c %**start of header
3
4 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
5 @c                                                                            o
6 @c                            GNAT DOCUMENTATION                              o
7 @c                                                                            o
8 @c                             G N A T _ U G N                                o
9 @c                                                                            o
10 @c           Copyright (C) 1992-2011, Free Software Foundation, Inc.          o
11 @c                                                                            o
12 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
13
14 @setfilename gnat_ugn.info
15
16 @copying
17 Copyright @copyright{} 1995-2009 Free Software Foundation,
18 Inc.
19
20 Permission is granted to copy, distribute and/or modify this document
21 under the terms of the GNU Free Documentation License, Version 1.3 or
22 any later version published by the Free Software Foundation; with no
23 Invariant Sections, with no Front-Cover Texts and with no Back-Cover
24 Texts.  A copy of the license is included in the section entitled
25 ``GNU Free Documentation License''.
26 @end copying
27
28 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
29 @c
30 @c                           GNAT_UGN Style Guide
31 @c
32 @c  1. Always put a @noindent on the line before the first paragraph
33 @c     after any of these commands:
34 @c
35 @c          @chapter
36 @c          @section
37 @c          @subsection
38 @c          @subsubsection
39 @c          @subsubsubsection
40 @c
41 @c          @end smallexample
42 @c          @end itemize
43 @c          @end enumerate
44 @c
45 @c  2. DO NOT use @example. Use @smallexample instead.
46 @c     a) DO NOT use highlighting commands (@b{}, @i{}) inside an @smallexample
47 @c        context.  These can interfere with the readability of the texi
48 @c        source file.  Instead, use one of the following annotated
49 @c        @smallexample commands, and preprocess the texi file with the
50 @c        ada2texi tool (which generates appropriate highlighting):
51 @c        @smallexample @c ada
52 @c        @smallexample @c adanocomment
53 @c        @smallexample @c projectfile
54 @c     b) The "@c ada" markup will result in boldface for reserved words
55 @c        and italics for comments
56 @c     c) The "@c adanocomment" markup will result only in boldface for
57 @c        reserved words (comments are left alone)
58 @c     d) The "@c projectfile" markup is like "@c ada" except that the set
59 @c        of reserved words include the new reserved words for project files
60 @c
61 @c  3. Each @chapter, @section, @subsection, @subsubsection, etc.
62 @c     command must be preceded by two empty lines
63 @c
64 @c  4. The @item command should be on a line of its own if it is in an
65 @c     @itemize or @enumerate command.
66 @c
67 @c  5. When talking about ALI files use "ALI" (all uppercase), not "Ali"
68 @c     or "ali".
69 @c
70 @c  6. DO NOT put trailing spaces at the end of a line.  Such spaces will
71 @c     cause the document build to fail.
72 @c
73 @c  7. DO NOT use @cartouche for examples that are longer than around 10 lines.
74 @c     This command inhibits page breaks, so long examples in a @cartouche can
75 @c     lead to large, ugly patches of empty space on a page.
76 @c
77 @c  NOTE: This file should be submitted to xgnatugn with either the vms flag
78 @c        or the unw flag set.  The unw flag covers topics for both Unix and
79 @c        Windows.
80 @c
81 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
82
83 @set NOW January 2007
84 @c This flag is used where the text refers to conditions that exist when the
85 @c text was entered into the document but which may change over time.
86 @c Update the setting for the flag, and (if necessary) the text surrounding,
87 @c the references to the flag, on future doc revisions:
88 @c search for @value{NOW}.
89
90 @set FSFEDITION
91 @set EDITION GNAT
92 @set DEFAULTLANGUAGEVERSION Ada 2005
93 @set NONDEFAULTLANGUAGEVERSION Ada 95
94
95 @ifset unw
96 @set PLATFORM
97 @end ifset
98
99 @ifset vms
100 @set PLATFORM OpenVMS
101 @end ifset
102
103 @c @ovar(ARG)
104 @c ----------
105 @c The ARG is an optional argument.  To be used for macro arguments in
106 @c their documentation (@defmac).
107 @macro ovar{varname}
108 @r{[}@var{\varname\}@r{]}@c
109 @end macro
110 @c Status as of November 2009:
111 @c Unfortunately texi2pdf and texi2html treat the trailing "@c"
112 @c differently, and faulty output is produced by one or the other
113 @c depending on whether the "@c" is present or absent.
114 @c As a result, the @ovar macro is not used, and all invocations
115 @c of the @ovar macro have been expanded inline.
116
117
118 @settitle @value{EDITION} User's Guide @value{PLATFORM}
119 @dircategory GNU Ada tools
120 @direntry
121 * @value{EDITION} User's Guide: (gnat_ugn). @value{PLATFORM}
122 @end direntry
123
124 @include gcc-common.texi
125
126 @setchapternewpage odd
127 @syncodeindex fn cp
128 @c %**end of header
129
130 @titlepage
131 @title @value{EDITION} User's Guide
132 @ifset vms
133 @sp 1
134 @flushright
135 @titlefont{@i{@value{PLATFORM}}}
136 @end flushright
137 @end ifset
138
139 @sp 2
140
141 @subtitle GNAT, The GNU Ada Compiler
142 @versionsubtitle
143 @author AdaCore
144
145 @page
146 @vskip 0pt plus 1filll
147
148 @insertcopying
149
150 @end titlepage
151
152 @ifnottex
153 @node Top, About This Guide, (dir), (dir)
154 @top @value{EDITION} User's Guide
155
156 @noindent
157 @value{EDITION} User's Guide @value{PLATFORM}
158
159 @noindent
160 GNAT, The GNU Ada Compiler@*
161 GCC version @value{version-GCC}@*
162
163 @noindent
164 AdaCore@*
165
166 @menu
167 * About This Guide::
168 * Getting Started with GNAT::
169 * The GNAT Compilation Model::
170 * Compiling Using gcc::
171 * Binding Using gnatbind::
172 * Linking Using gnatlink::
173 * The GNAT Make Program gnatmake::
174 * Improving Performance::
175 * Renaming Files Using gnatchop::
176 * Configuration Pragmas::
177 * Handling Arbitrary File Naming Conventions Using gnatname::
178 * GNAT Project Manager::
179 * Tools Supporting Project Files::
180 * The Cross-Referencing Tools gnatxref and gnatfind::
181 * The GNAT Pretty-Printer gnatpp::
182 * The GNAT Metric Tool gnatmetric::
183 * File Name Krunching Using gnatkr::
184 * Preprocessing Using gnatprep::
185 * The GNAT Library Browser gnatls::
186 * Cleaning Up Using gnatclean::
187 @ifclear vms
188 * GNAT and Libraries::
189 * Using the GNU make Utility::
190 @end ifclear
191 * Memory Management Issues::
192 * Stack Related Facilities::
193 * Verifying Properties Using gnatcheck::
194 * Creating Sample Bodies Using gnatstub::
195 * Creating Unit Tests Using gnattest::
196 * Generating Ada Bindings for C and C++ headers::
197 * Other Utility Programs::
198 * Running and Debugging Ada Programs::
199 @ifclear vms
200 * Code Coverage and Profiling::
201 @end ifclear
202 @ifset vms
203 * Compatibility with HP Ada::
204 @end ifset
205 * Platform-Specific Information for the Run-Time Libraries::
206 * Example of Binder Output File::
207 * Elaboration Order Handling in GNAT::
208 * Conditional Compilation::
209 * Inline Assembler::
210 * Compatibility and Porting Guide::
211 @ifset unw
212 * Microsoft Windows Topics::
213 @end ifset
214 * GNU Free Documentation License::
215 * Index::
216
217  --- The Detailed Node Listing ---
218
219 About This Guide
220
221 * What This Guide Contains::
222 * What You Should Know before Reading This Guide::
223 * Related Information::
224 * Conventions::
225
226 Getting Started with GNAT
227
228 * Running GNAT::
229 * Running a Simple Ada Program::
230 * Running a Program with Multiple Units::
231 * Using the gnatmake Utility::
232 @ifset vms
233 * Editing with Emacs::
234 @end ifset
235 @ifclear vms
236 * Introduction to GPS::
237 @end ifclear
238
239 The GNAT Compilation Model
240
241 * Source Representation::
242 * Foreign Language Representation::
243 * File Naming Rules::
244 * Using Other File Names::
245 * Alternative File Naming Schemes::
246 * Generating Object Files::
247 * Source Dependencies::
248 * The Ada Library Information Files::
249 * Binding an Ada Program::
250 * Mixed Language Programming::
251 @ifclear vms
252 * Building Mixed Ada & C++ Programs::
253 * Comparison between GNAT and C/C++ Compilation Models::
254 @end ifclear
255 * Comparison between GNAT and Conventional Ada Library Models::
256 @ifset vms
257 * Placement of temporary files::
258 @end ifset
259
260 Foreign Language Representation
261
262 * Latin-1::
263 * Other 8-Bit Codes::
264 * Wide Character Encodings::
265
266 Compiling Ada Programs With gcc
267
268 * Compiling Programs::
269 * Switches for gcc::
270 * Search Paths and the Run-Time Library (RTL)::
271 * Order of Compilation Issues::
272 * Examples::
273
274 Switches for gcc
275
276 * Output and Error Message Control::
277 * Warning Message Control::
278 * Debugging and Assertion Control::
279 * Validity Checking::
280 * Style Checking::
281 * Run-Time Checks::
282 * Using gcc for Syntax Checking::
283 * Using gcc for Semantic Checking::
284 * Compiling Different Versions of Ada::
285 * Character Set Control::
286 * File Naming Control::
287 * Subprogram Inlining Control::
288 * Auxiliary Output Control::
289 * Debugging Control::
290 * Exception Handling Control::
291 * Units to Sources Mapping Files::
292 * Integrated Preprocessing::
293 @ifset vms
294 * Return Codes::
295 @end ifset
296
297 Binding Ada Programs With gnatbind
298
299 * Running gnatbind::
300 * Switches for gnatbind::
301 * Command-Line Access::
302 * Search Paths for gnatbind::
303 * Examples of gnatbind Usage::
304
305 Switches for gnatbind
306
307 * Consistency-Checking Modes::
308 * Binder Error Message Control::
309 * Elaboration Control::
310 * Output Control::
311 * Binding with Non-Ada Main Programs::
312 * Binding Programs with No Main Subprogram::
313
314 Linking Using gnatlink
315
316 * Running gnatlink::
317 * Switches for gnatlink::
318
319 The GNAT Make Program gnatmake
320
321 * Running gnatmake::
322 * Switches for gnatmake::
323 * Mode Switches for gnatmake::
324 * Notes on the Command Line::
325 * How gnatmake Works::
326 * Examples of gnatmake Usage::
327
328 Improving Performance
329 * Performance Considerations::
330 * Text_IO Suggestions::
331 * Reducing Size of Ada Executables with gnatelim::
332 * Reducing Size of Executables with unused subprogram/data elimination::
333
334 Performance Considerations
335 * Controlling Run-Time Checks::
336 * Use of Restrictions::
337 * Optimization Levels::
338 * Debugging Optimized Code::
339 * Inlining of Subprograms::
340 * Other Optimization Switches::
341 * Optimization and Strict Aliasing::
342 @ifset vms
343 * Coverage Analysis::
344 @end ifset
345
346 Reducing Size of Ada Executables with gnatelim
347 * About gnatelim::
348 * Running gnatelim::
349 * Processing Precompiled Libraries::
350 * Correcting the List of Eliminate Pragmas::
351 * Making Your Executables Smaller::
352 * Summary of the gnatelim Usage Cycle::
353
354 Reducing Size of Executables with unused subprogram/data elimination
355 * About unused subprogram/data elimination::
356 * Compilation options::
357
358 Renaming Files Using gnatchop
359
360 * Handling Files with Multiple Units::
361 * Operating gnatchop in Compilation Mode::
362 * Command Line for gnatchop::
363 * Switches for gnatchop::
364 * Examples of gnatchop Usage::
365
366 Configuration Pragmas
367
368 * Handling of Configuration Pragmas::
369 * The Configuration Pragmas Files::
370
371 Handling Arbitrary File Naming Conventions Using gnatname
372
373 * Arbitrary File Naming Conventions::
374 * Running gnatname::
375 * Switches for gnatname::
376 * Examples of gnatname Usage::
377
378 The Cross-Referencing Tools gnatxref and gnatfind
379
380 * Switches for gnatxref::
381 * Switches for gnatfind::
382 * Project Files for gnatxref and gnatfind::
383 * Regular Expressions in gnatfind and gnatxref::
384 * Examples of gnatxref Usage::
385 * Examples of gnatfind Usage::
386
387 The GNAT Pretty-Printer gnatpp
388
389 * Switches for gnatpp::
390 * Formatting Rules::
391
392 The GNAT Metrics Tool gnatmetric
393
394 * Switches for gnatmetric::
395
396 File Name Krunching Using gnatkr
397
398 * About gnatkr::
399 * Using gnatkr::
400 * Krunching Method::
401 * Examples of gnatkr Usage::
402
403 Preprocessing Using gnatprep
404 * Preprocessing Symbols::
405 * Using gnatprep::
406 * Switches for gnatprep::
407 * Form of Definitions File::
408 * Form of Input Text for gnatprep::
409
410 The GNAT Library Browser gnatls
411
412 * Running gnatls::
413 * Switches for gnatls::
414 * Examples of gnatls Usage::
415
416 Cleaning Up Using gnatclean
417
418 * Running gnatclean::
419 * Switches for gnatclean::
420 @c * Examples of gnatclean Usage::
421
422 @ifclear vms
423
424 GNAT and Libraries
425
426 * Introduction to Libraries in GNAT::
427 * General Ada Libraries::
428 * Stand-alone Ada Libraries::
429 * Rebuilding the GNAT Run-Time Library::
430
431 Using the GNU make Utility
432
433 * Using gnatmake in a Makefile::
434 * Automatically Creating a List of Directories::
435 * Generating the Command Line Switches::
436 * Overcoming Command Line Length Limits::
437 @end ifclear
438
439 Memory Management Issues
440
441 * Some Useful Memory Pools::
442 * The GNAT Debug Pool Facility::
443 @ifclear vms
444 * The gnatmem Tool::
445 @end ifclear
446
447 Stack Related Facilities
448
449 * Stack Overflow Checking::
450 * Static Stack Usage Analysis::
451 * Dynamic Stack Usage Analysis::
452
453 Some Useful Memory Pools
454
455 The GNAT Debug Pool Facility
456
457 @ifclear vms
458 The gnatmem Tool
459
460 * Running gnatmem::
461 * Switches for gnatmem::
462 * Example of gnatmem Usage::
463 @end ifclear
464
465 Verifying Properties Using gnatcheck
466
467 Sample Bodies Using gnatstub
468
469 * Running gnatstub::
470 * Switches for gnatstub::
471
472 Creating Unit Tests Using gnattest
473
474 * Running gnattest::
475 * Switches for gnattest::
476 * Project Attributes for gnattest::
477 * Simple Example::
478 * Setting Up and Tearing Down Testing Environment::
479 * Regenerating Tests::
480 * Default Test Behavior::
481 * Testing Primitive Operations of Tagged Types::
482 * Test Inheritance::
483 * Tagged Types Substitutability Testing::
484 * Testing with Contracts::
485 * Additional Tests::
486 * Current Limitations::
487
488 Other Utility Programs
489
490 * Using Other Utility Programs with GNAT::
491 * The External Symbol Naming Scheme of GNAT::
492 * Converting Ada Files to html with gnathtml::
493
494 @ifclear vms
495 Code Coverage and Profiling
496
497 * Code Coverage of Ada Programs using gcov::
498 * Profiling an Ada Program using gprof::
499 @end ifclear
500
501 Running and Debugging Ada Programs
502
503 * The GNAT Debugger GDB::
504 * Running GDB::
505 * Introduction to GDB Commands::
506 * Using Ada Expressions::
507 * Calling User-Defined Subprograms::
508 * Using the Next Command in a Function::
509 * Ada Exceptions::
510 * Ada Tasks::
511 * Debugging Generic Units::
512 * Remote Debugging using gdbserver::
513 * GNAT Abnormal Termination or Failure to Terminate::
514 * Naming Conventions for GNAT Source Files::
515 * Getting Internal Debugging Information::
516 * Stack Traceback::
517
518 @ifset vms
519 * LSE::
520 @end ifset
521
522 @ifset vms
523 Compatibility with HP Ada
524
525 * Ada Language Compatibility::
526 * Differences in the Definition of Package System::
527 * Language-Related Features::
528 * The Package STANDARD::
529 * The Package SYSTEM::
530 * Tasking and Task-Related Features::
531 * Pragmas and Pragma-Related Features::
532 * Library of Predefined Units::
533 * Bindings::
534 * Main Program Definition::
535 * Implementation-Defined Attributes::
536 * Compiler and Run-Time Interfacing::
537 * Program Compilation and Library Management::
538 * Input-Output::
539 * Implementation Limits::
540 * Tools and Utilities::
541
542 Language-Related Features
543
544 * Integer Types and Representations::
545 * Floating-Point Types and Representations::
546 * Pragmas Float_Representation and Long_Float::
547 * Fixed-Point Types and Representations::
548 * Record and Array Component Alignment::
549 * Address Clauses::
550 * Other Representation Clauses::
551
552 Tasking and Task-Related Features
553
554 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
555 * Assigning Task IDs::
556 * Task IDs and Delays::
557 * Task-Related Pragmas::
558 * Scheduling and Task Priority::
559 * The Task Stack::
560 * External Interrupts::
561
562 Pragmas and Pragma-Related Features
563
564 * Restrictions on the Pragma INLINE::
565 * Restrictions on the Pragma INTERFACE::
566 * Restrictions on the Pragma SYSTEM_NAME::
567
568 Library of Predefined Units
569
570 * Changes to DECLIB::
571
572 Bindings
573
574 * Shared Libraries and Options Files::
575 * Interfaces to C::
576 @end ifset
577
578 Platform-Specific Information for the Run-Time Libraries
579
580 * Summary of Run-Time Configurations::
581 * Specifying a Run-Time Library::
582 * Choosing the Scheduling Policy::
583 * Solaris-Specific Considerations::
584 * Linux-Specific Considerations::
585 * AIX-Specific Considerations::
586 * Irix-Specific Considerations::
587 * RTX-Specific Considerations::
588 * HP-UX-Specific Considerations::
589
590 Example of Binder Output File
591
592 Elaboration Order Handling in GNAT
593
594 * Elaboration Code::
595 * Checking the Elaboration Order::
596 * Controlling the Elaboration Order::
597 * Controlling Elaboration in GNAT - Internal Calls::
598 * Controlling Elaboration in GNAT - External Calls::
599 * Default Behavior in GNAT - Ensuring Safety::
600 * Treatment of Pragma Elaborate::
601 * Elaboration Issues for Library Tasks::
602 * Mixing Elaboration Models::
603 * What to Do If the Default Elaboration Behavior Fails::
604 * Elaboration for Access-to-Subprogram Values::
605 * Summary of Procedures for Elaboration Control::
606 * Other Elaboration Order Considerations::
607
608 Conditional Compilation
609 * Use of Boolean Constants::
610 * Debugging - A Special Case::
611 * Conditionalizing Declarations::
612 * Use of Alternative Implementations::
613 * Preprocessing::
614
615 Inline Assembler
616
617 * Basic Assembler Syntax::
618 * A Simple Example of Inline Assembler::
619 * Output Variables in Inline Assembler::
620 * Input Variables in Inline Assembler::
621 * Inlining Inline Assembler Code::
622 * Other Asm Functionality::
623
624 Compatibility and Porting Guide
625
626 * Compatibility with Ada 83::
627 * Compatibility between Ada 95 and Ada 2005::
628 * Implementation-dependent characteristics::
629 @ifclear vms
630 @c This brief section is only in the non-VMS version
631 @c The complete chapter on HP Ada issues is in the VMS version
632 * Compatibility with HP Ada 83::
633 @end ifclear
634 * Compatibility with Other Ada Systems::
635 * Representation Clauses::
636 @ifset vms
637 * Transitioning to 64-Bit GNAT for OpenVMS::
638 @end ifset
639
640 @ifset unw
641 Microsoft Windows Topics
642
643 * Using GNAT on Windows::
644 * CONSOLE and WINDOWS subsystems::
645 * Temporary Files::
646 * Mixed-Language Programming on Windows::
647 * Windows Calling Conventions::
648 * Introduction to Dynamic Link Libraries (DLLs)::
649 * Using DLLs with GNAT::
650 * Building DLLs with GNAT::
651 * GNAT and Windows Resources::
652 * Debugging a DLL::
653 * Setting Stack Size from gnatlink::
654 * Setting Heap Size from gnatlink::
655 @end ifset
656
657 * Index::
658 @end menu
659 @end ifnottex
660
661 @node About This Guide
662 @unnumbered About This Guide
663
664 @noindent
665 @ifset vms
666 This guide describes the use of @value{EDITION},
667 a compiler and software development toolset for the full Ada
668 programming language, implemented on OpenVMS for HP's Alpha and
669 Integrity server (I64) platforms.
670 @end ifset
671 @ifclear vms
672 This guide describes the use of @value{EDITION},
673 a compiler and software development
674 toolset for the full Ada programming language.
675 @end ifclear
676 It documents the features of the compiler and tools, and explains
677 how to use them to build Ada applications.
678
679 @value{EDITION} implements Ada 95 and Ada 2005, and it may also be invoked in
680 Ada 83 compatibility mode.
681 By default, @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION},
682 but you can override with a compiler switch
683 (@pxref{Compiling Different Versions of Ada})
684 to explicitly specify the language version.
685 Throughout this manual, references to ``Ada'' without a year suffix
686 apply to both the Ada 95 and Ada 2005 versions of the language.
687
688
689 @ifclear FSFEDITION
690 For ease of exposition, ``@value{EDITION}'' will be referred to simply as
691 ``GNAT'' in the remainder of this document.
692 @end ifclear
693
694
695
696
697 @menu
698 * What This Guide Contains::
699 * What You Should Know before Reading This Guide::
700 * Related Information::
701 * Conventions::
702 @end menu
703
704 @node What This Guide Contains
705 @unnumberedsec What This Guide Contains
706
707 @noindent
708 This guide contains the following chapters:
709 @itemize @bullet
710
711 @item
712 @ref{Getting Started with GNAT}, describes how to get started compiling
713 and running Ada programs with the GNAT Ada programming environment.
714 @item
715 @ref{The GNAT Compilation Model}, describes the compilation model used
716 by GNAT.
717
718 @item
719 @ref{Compiling Using gcc}, describes how to compile
720 Ada programs with @command{gcc}, the Ada compiler.
721
722 @item
723 @ref{Binding Using gnatbind}, describes how to
724 perform binding of Ada programs with @code{gnatbind}, the GNAT binding
725 utility.
726
727 @item
728 @ref{Linking Using gnatlink},
729 describes @command{gnatlink}, a
730 program that provides for linking using the GNAT run-time library to
731 construct a program. @command{gnatlink} can also incorporate foreign language
732 object units into the executable.
733
734 @item
735 @ref{The GNAT Make Program gnatmake}, describes @command{gnatmake}, a
736 utility that automatically determines the set of sources
737 needed by an Ada compilation unit, and executes the necessary compilations
738 binding and link.
739
740 @item
741 @ref{Improving Performance}, shows various techniques for making your
742 Ada program run faster or take less space.
743 It discusses the effect of the compiler's optimization switch and
744 also describes the @command{gnatelim} tool and unused subprogram/data
745 elimination.
746
747 @item
748 @ref{Renaming Files Using gnatchop}, describes
749 @code{gnatchop}, a utility that allows you to preprocess a file that
750 contains Ada source code, and split it into one or more new files, one
751 for each compilation unit.
752
753 @item
754 @ref{Configuration Pragmas}, describes the configuration pragmas
755 handled by GNAT.
756
757 @item
758 @ref{Handling Arbitrary File Naming Conventions Using gnatname},
759 shows how to override the default GNAT file naming conventions,
760 either for an individual unit or globally.
761
762 @item
763 @ref{GNAT Project Manager}, describes how to use project files
764 to organize large projects.
765
766 @item
767 @ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses
768 @code{gnatxref} and @code{gnatfind}, two tools that provide an easy
769 way to navigate through sources.
770
771 @item
772 @ref{The GNAT Pretty-Printer gnatpp}, shows how to produce a reformatted
773 version of an Ada source file with control over casing, indentation,
774 comment placement, and other elements of program presentation style.
775
776 @item
777 @ref{The GNAT Metric Tool gnatmetric}, shows how to compute various
778 metrics for an Ada source file, such as the number of types and subprograms,
779 and assorted complexity measures.
780
781 @item
782 @ref{File Name Krunching Using gnatkr}, describes the @code{gnatkr}
783 file name krunching utility, used to handle shortened
784 file names on operating systems with a limit on the length of names.
785
786 @item
787 @ref{Preprocessing Using gnatprep}, describes @code{gnatprep}, a
788 preprocessor utility that allows a single source file to be used to
789 generate multiple or parameterized source files by means of macro
790 substitution.
791
792 @item
793 @ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a
794 utility that displays information about compiled units, including dependences
795 on the corresponding sources files, and consistency of compilations.
796
797 @item
798 @ref{Cleaning Up Using gnatclean}, describes @code{gnatclean}, a utility
799 to delete files that are produced by the compiler, binder and linker.
800
801 @ifclear vms
802 @item
803 @ref{GNAT and Libraries}, describes the process of creating and using
804 Libraries with GNAT. It also describes how to recompile the GNAT run-time
805 library.
806
807 @item
808 @ref{Using the GNU make Utility}, describes some techniques for using
809 the GNAT toolset in Makefiles.
810 @end ifclear
811
812 @item
813 @ref{Memory Management Issues}, describes some useful predefined storage pools
814 and in particular the GNAT Debug Pool facility, which helps detect incorrect
815 memory references.
816 @ifclear vms
817 It also describes @command{gnatmem}, a utility that monitors dynamic
818 allocation and deallocation and helps detect ``memory leaks''.
819 @end ifclear
820
821 @item
822 @ref{Stack Related Facilities}, describes some useful tools associated with
823 stack checking and analysis.
824
825 @item
826 @ref{Verifying Properties Using gnatcheck}, discusses @code{gnatcheck},
827 a utility that checks Ada code against a set of rules.
828
829 @item
830 @ref{Creating Sample Bodies Using gnatstub}, discusses @code{gnatstub},
831 a utility that generates empty but compilable bodies for library units.
832
833 @item
834 @ref{Creating Unit Tests Using gnattest}, discusses @code{gnattest},
835 a utility that generates unit testing templates for library units.
836
837 @item
838 @ref{Generating Ada Bindings for C and C++ headers}, describes how to
839 generate automatically Ada bindings from C and C++ headers.
840
841 @item
842 @ref{Other Utility Programs}, discusses several other GNAT utilities,
843 including @code{gnathtml}.
844
845 @ifclear vms
846 @item
847 @ref{Code Coverage and Profiling}, describes how to perform a structural
848 coverage and profile the execution of Ada programs.
849 @end ifclear
850
851 @item
852 @ref{Running and Debugging Ada Programs}, describes how to run and debug
853 Ada programs.
854
855 @ifset vms
856 @item
857 @ref{Compatibility with HP Ada}, details the compatibility of GNAT with
858 HP Ada 83 @footnote{``HP Ada'' refers to the legacy product originally
859 developed by Digital Equipment Corporation and currently supported by HP.}
860 for OpenVMS Alpha. This product was formerly known as DEC Ada,
861 @cindex DEC Ada
862 and for
863 historical compatibility reasons, the relevant libraries still use the
864 DEC prefix.
865 @end ifset
866
867 @item
868 @ref{Platform-Specific Information for the Run-Time Libraries},
869 describes the various run-time
870 libraries supported by GNAT on various platforms and explains how to
871 choose a particular library.
872
873 @item
874 @ref{Example of Binder Output File}, shows the source code for the binder
875 output file for a sample program.
876
877 @item
878 @ref{Elaboration Order Handling in GNAT}, describes how GNAT helps
879 you deal with elaboration order issues.
880
881 @item
882 @ref{Conditional Compilation}, describes how to model conditional compilation,
883 both with Ada in general and with GNAT facilities in particular.
884
885 @item
886 @ref{Inline Assembler}, shows how to use the inline assembly facility
887 in an Ada program.
888
889 @item
890 @ref{Compatibility and Porting Guide}, contains sections on compatibility
891 of GNAT with other Ada development environments (including Ada 83 systems),
892 to assist in porting code from those environments.
893
894 @ifset unw
895 @item
896 @ref{Microsoft Windows Topics}, presents information relevant to the
897 Microsoft Windows platform.
898 @end ifset
899 @end itemize
900
901 @c *************************************************
902 @node What You Should Know before Reading This Guide
903 @c *************************************************
904 @unnumberedsec What You Should Know before Reading This Guide
905
906 @cindex Ada 95 Language Reference Manual
907 @cindex Ada 2005 Language Reference Manual
908 @noindent
909 This guide assumes a basic familiarity with the Ada 95 language, as
910 described in the International Standard ANSI/ISO/IEC-8652:1995, January
911 1995.
912 It does not require knowledge of the new features introduced by Ada 2005,
913 (officially known as ISO/IEC 8652:1995 with Technical Corrigendum 1
914 and Amendment 1).
915 Both reference manuals are included in the GNAT documentation
916 package.
917
918 @node Related Information
919 @unnumberedsec Related Information
920
921 @noindent
922 For further information about related tools, refer to the following
923 documents:
924
925 @itemize @bullet
926 @item
927 @xref{Top, GNAT Reference Manual, About This Guide, gnat_rm, GNAT
928 Reference Manual}, which contains all reference material for the GNAT
929 implementation of Ada.
930
931 @ifset unw
932 @item
933 @cite{Using the GNAT Programming Studio}, which describes the GPS
934 Integrated Development Environment.
935
936 @item
937 @cite{GNAT Programming Studio Tutorial}, which introduces the
938 main GPS features through examples.
939 @end ifset
940
941 @item
942 @cite{Ada 95 Reference Manual}, which contains reference
943 material for the Ada 95 programming language.
944
945 @item
946 @cite{Ada 2005 Reference Manual}, which contains reference
947 material for the Ada 2005 programming language.
948
949 @item
950 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
951 @ifset vms
952 in the GNU:[DOCS] directory,
953 @end ifset
954 for all details on the use of the GNU source-level debugger.
955
956 @item
957 @xref{Top,, The extensible self-documenting text editor, emacs,
958 GNU Emacs Manual},
959 @ifset vms
960 located in the GNU:[DOCS] directory if the EMACS kit is installed,
961 @end ifset
962 for full information on the extensible editor and programming
963 environment Emacs.
964
965 @end itemize
966
967 @c **************
968 @node Conventions
969 @unnumberedsec Conventions
970 @cindex Conventions
971 @cindex Typographical conventions
972
973 @noindent
974 Following are examples of the typographical and graphic conventions used
975 in this guide:
976
977 @itemize @bullet
978 @item
979 @code{Functions}, @command{utility program names}, @code{standard names},
980 and @code{classes}.
981
982 @item
983 @option{Option flags}
984
985 @item
986 @file{File names}, @samp{button names}, and @samp{field names}.
987
988 @item
989 @code{Variables}, @env{environment variables}, and @var{metasyntactic
990 variables}.
991
992 @item
993 @emph{Emphasis}.
994
995 @item
996 @r{[}optional information or parameters@r{]}
997
998 @item
999 Examples are described by text
1000 @smallexample
1001 and then shown this way.
1002 @end smallexample
1003 @end itemize
1004
1005 @noindent
1006 Commands that are entered by the user are preceded in this manual by the
1007 characters @w{``@code{$ }''} (dollar sign followed by space). If your system
1008 uses this sequence as a prompt, then the commands will appear exactly as
1009 you see them in the manual. If your system uses some other prompt, then
1010 the command will appear with the @code{$} replaced by whatever prompt
1011 character you are using.
1012
1013 @ifset unw
1014 Full file names are shown with the ``@code{/}'' character
1015 as the directory separator; e.g., @file{parent-dir/subdir/myfile.adb}.
1016 If you are using GNAT on a Windows platform, please note that
1017 the ``@code{\}'' character should be used instead.
1018 @end ifset
1019
1020 @c ****************************
1021 @node Getting Started with GNAT
1022 @chapter Getting Started with GNAT
1023
1024 @noindent
1025 This chapter describes some simple ways of using GNAT to build
1026 executable Ada programs.
1027 @ifset unw
1028 @ref{Running GNAT}, through @ref{Using the gnatmake Utility},
1029 show how to use the command line environment.
1030 @ref{Introduction to GPS}, provides a brief
1031 introduction to the GNAT Programming Studio, a visually-oriented
1032 Integrated Development Environment for GNAT.
1033 GPS offers a graphical ``look and feel'', support for development in
1034 other programming languages, comprehensive browsing features, and
1035 many other capabilities.
1036 For information on GPS please refer to
1037 @cite{Using the GNAT Programming Studio}.
1038 @end ifset
1039
1040 @menu
1041 * Running GNAT::
1042 * Running a Simple Ada Program::
1043 * Running a Program with Multiple Units::
1044 * Using the gnatmake Utility::
1045 @ifset vms
1046 * Editing with Emacs::
1047 @end ifset
1048 @ifclear vms
1049 * Introduction to GPS::
1050 @end ifclear
1051 @end menu
1052
1053 @node Running GNAT
1054 @section Running GNAT
1055
1056 @noindent
1057 Three steps are needed to create an executable file from an Ada source
1058 file:
1059
1060 @enumerate
1061 @item
1062 The source file(s) must be compiled.
1063 @item
1064 The file(s) must be bound using the GNAT binder.
1065 @item
1066 All appropriate object files must be linked to produce an executable.
1067 @end enumerate
1068
1069 @noindent
1070 All three steps are most commonly handled by using the @command{gnatmake}
1071 utility program that, given the name of the main program, automatically
1072 performs the necessary compilation, binding and linking steps.
1073
1074 @node Running a Simple Ada Program
1075 @section Running a Simple Ada Program
1076
1077 @noindent
1078 Any text editor may be used to prepare an Ada program.
1079 (If @code{Emacs} is
1080 used, the optional Ada mode may be helpful in laying out the program.)
1081 The
1082 program text is a normal text file. We will assume in our initial
1083 example that you have used your editor to prepare the following
1084 standard format text file:
1085
1086 @smallexample @c ada
1087 @cartouche
1088 with Ada.Text_IO; use Ada.Text_IO;
1089 procedure Hello is
1090 begin
1091    Put_Line ("Hello WORLD!");
1092 end Hello;
1093 @end cartouche
1094 @end smallexample
1095
1096 @noindent
1097 This file should be named @file{hello.adb}.
1098 With the normal default file naming conventions, GNAT requires
1099 that each file
1100 contain a single compilation unit whose file name is the
1101 unit name,
1102 with periods replaced by hyphens; the
1103 extension is @file{ads} for a
1104 spec and @file{adb} for a body.
1105 You can override this default file naming convention by use of the
1106 special pragma @code{Source_File_Name} (@pxref{Using Other File Names}).
1107 Alternatively, if you want to rename your files according to this default
1108 convention, which is probably more convenient if you will be using GNAT
1109 for all your compilations, then the @code{gnatchop} utility
1110 can be used to generate correctly-named source files
1111 (@pxref{Renaming Files Using gnatchop}).
1112
1113 You can compile the program using the following command (@code{$} is used
1114 as the command prompt in the examples in this document):
1115
1116 @smallexample
1117 $ gcc -c hello.adb
1118 @end smallexample
1119
1120 @noindent
1121 @command{gcc} is the command used to run the compiler. This compiler is
1122 capable of compiling programs in several languages, including Ada and
1123 C. It assumes that you have given it an Ada program if the file extension is
1124 either @file{.ads} or @file{.adb}, and it will then call
1125 the GNAT compiler to compile the specified file.
1126
1127 @ifclear vms
1128 The @option{-c} switch is required. It tells @command{gcc} to only do a
1129 compilation. (For C programs, @command{gcc} can also do linking, but this
1130 capability is not used directly for Ada programs, so the @option{-c}
1131 switch must always be present.)
1132 @end ifclear
1133
1134 This compile command generates a file
1135 @file{hello.o}, which is the object
1136 file corresponding to your Ada program. It also generates
1137 an ``Ada Library Information'' file @file{hello.ali},
1138 which contains additional information used to check
1139 that an Ada program is consistent.
1140 To build an executable file,
1141 use @code{gnatbind} to bind the program
1142 and @command{gnatlink} to link it. The
1143 argument to both @code{gnatbind} and @command{gnatlink} is the name of the
1144 @file{ALI} file, but the default extension of @file{.ali} can
1145 be omitted. This means that in the most common case, the argument
1146 is simply the name of the main program:
1147
1148 @smallexample
1149 $ gnatbind hello
1150 $ gnatlink hello
1151 @end smallexample
1152
1153 @noindent
1154 A simpler method of carrying out these steps is to use
1155 @command{gnatmake},
1156 a master program that invokes all the required
1157 compilation, binding and linking tools in the correct order. In particular,
1158 @command{gnatmake} automatically recompiles any sources that have been
1159 modified since they were last compiled, or sources that depend
1160 on such modified sources, so that ``version skew'' is avoided.
1161 @cindex Version skew (avoided by @command{gnatmake})
1162
1163 @smallexample
1164 $ gnatmake hello.adb
1165 @end smallexample
1166
1167 @noindent
1168 The result is an executable program called @file{hello}, which can be
1169 run by entering:
1170
1171 @smallexample
1172 $ ^hello^RUN HELLO^
1173 @end smallexample
1174
1175 @noindent
1176 assuming that the current directory is on the search path
1177 for executable programs.
1178
1179 @noindent
1180 and, if all has gone well, you will see
1181
1182 @smallexample
1183 Hello WORLD!
1184 @end smallexample
1185
1186 @noindent
1187 appear in response to this command.
1188
1189 @c ****************************************
1190 @node Running a Program with Multiple Units
1191 @section Running a Program with Multiple Units
1192
1193 @noindent
1194 Consider a slightly more complicated example that has three files: a
1195 main program, and the spec and body of a package:
1196
1197 @smallexample @c ada
1198 @cartouche
1199 @group
1200 package Greetings is
1201    procedure Hello;
1202    procedure Goodbye;
1203 end Greetings;
1204
1205 with Ada.Text_IO; use Ada.Text_IO;
1206 package body Greetings is
1207    procedure Hello is
1208    begin
1209       Put_Line ("Hello WORLD!");
1210    end Hello;
1211
1212    procedure Goodbye is
1213    begin
1214       Put_Line ("Goodbye WORLD!");
1215    end Goodbye;
1216 end Greetings;
1217 @end group
1218
1219 @group
1220 with Greetings;
1221 procedure Gmain is
1222 begin
1223    Greetings.Hello;
1224    Greetings.Goodbye;
1225 end Gmain;
1226 @end group
1227 @end cartouche
1228 @end smallexample
1229
1230 @noindent
1231 Following the one-unit-per-file rule, place this program in the
1232 following three separate files:
1233
1234 @table @file
1235 @item greetings.ads
1236 spec of package @code{Greetings}
1237
1238 @item greetings.adb
1239 body of package @code{Greetings}
1240
1241 @item gmain.adb
1242 body of main program
1243 @end table
1244
1245 @noindent
1246 To build an executable version of
1247 this program, we could use four separate steps to compile, bind, and link
1248 the program, as follows:
1249
1250 @smallexample
1251 $ gcc -c gmain.adb
1252 $ gcc -c greetings.adb
1253 $ gnatbind gmain
1254 $ gnatlink gmain
1255 @end smallexample
1256
1257 @noindent
1258 Note that there is no required order of compilation when using GNAT.
1259 In particular it is perfectly fine to compile the main program first.
1260 Also, it is not necessary to compile package specs in the case where
1261 there is an accompanying body; you only need to compile the body. If you want
1262 to submit these files to the compiler for semantic checking and not code
1263 generation, then use the
1264 @option{-gnatc} switch:
1265
1266 @smallexample
1267 $ gcc -c greetings.ads -gnatc
1268 @end smallexample
1269
1270 @noindent
1271 Although the compilation can be done in separate steps as in the
1272 above example, in practice it is almost always more convenient
1273 to use the @command{gnatmake} tool. All you need to know in this case
1274 is the name of the main program's source file. The effect of the above four
1275 commands can be achieved with a single one:
1276
1277 @smallexample
1278 $ gnatmake gmain.adb
1279 @end smallexample
1280
1281 @noindent
1282 In the next section we discuss the advantages of using @command{gnatmake} in
1283 more detail.
1284
1285 @c *****************************
1286 @node Using the gnatmake Utility
1287 @section Using the @command{gnatmake} Utility
1288
1289 @noindent
1290 If you work on a program by compiling single components at a time using
1291 @command{gcc}, you typically keep track of the units you modify. In order to
1292 build a consistent system, you compile not only these units, but also any
1293 units that depend on the units you have modified.
1294 For example, in the preceding case,
1295 if you edit @file{gmain.adb}, you only need to recompile that file. But if
1296 you edit @file{greetings.ads}, you must recompile both
1297 @file{greetings.adb} and @file{gmain.adb}, because both files contain
1298 units that depend on @file{greetings.ads}.
1299
1300 @code{gnatbind} will warn you if you forget one of these compilation
1301 steps, so that it is impossible to generate an inconsistent program as a
1302 result of forgetting to do a compilation. Nevertheless it is tedious and
1303 error-prone to keep track of dependencies among units.
1304 One approach to handle the dependency-bookkeeping is to use a
1305 makefile. However, makefiles present maintenance problems of their own:
1306 if the dependencies change as you change the program, you must make
1307 sure that the makefile is kept up-to-date manually, which is also an
1308 error-prone process.
1309
1310 The @command{gnatmake} utility takes care of these details automatically.
1311 Invoke it using either one of the following forms:
1312
1313 @smallexample
1314 $ gnatmake gmain.adb
1315 $ gnatmake ^gmain^GMAIN^
1316 @end smallexample
1317
1318 @noindent
1319 The argument is the name of the file containing the main program;
1320 you may omit the extension. @command{gnatmake}
1321 examines the environment, automatically recompiles any files that need
1322 recompiling, and binds and links the resulting set of object files,
1323 generating the executable file, @file{^gmain^GMAIN.EXE^}.
1324 In a large program, it
1325 can be extremely helpful to use @command{gnatmake}, because working out by hand
1326 what needs to be recompiled can be difficult.
1327
1328 Note that @command{gnatmake}
1329 takes into account all the Ada rules that
1330 establish dependencies among units. These include dependencies that result
1331 from inlining subprogram bodies, and from
1332 generic instantiation. Unlike some other
1333 Ada make tools, @command{gnatmake} does not rely on the dependencies that were
1334 found by the compiler on a previous compilation, which may possibly
1335 be wrong when sources change. @command{gnatmake} determines the exact set of
1336 dependencies from scratch each time it is run.
1337
1338 @ifset vms
1339 @node Editing with Emacs
1340 @section Editing with Emacs
1341 @cindex Emacs
1342
1343 @noindent
1344 Emacs is an extensible self-documenting text editor that is available in a
1345 separate VMSINSTAL kit.
1346
1347 Invoke Emacs by typing @kbd{Emacs} at the command prompt. To get started,
1348 click on the Emacs Help menu and run the Emacs Tutorial.
1349 In a character cell terminal, Emacs help is invoked with @kbd{Ctrl-h} (also
1350 written as @kbd{C-h}), and the tutorial by @kbd{C-h t}.
1351
1352 Documentation on Emacs and other tools is available in Emacs under the
1353 pull-down menu button: @code{Help - Info}. After selecting @code{Info},
1354 use the middle mouse button to select a topic (e.g.@: Emacs).
1355
1356 In a character cell terminal, do @kbd{C-h i} to invoke info, and then @kbd{m}
1357 (stands for menu) followed by the menu item desired, as in @kbd{m Emacs}, to
1358 get to the Emacs manual.
1359 Help on Emacs is also available by typing @kbd{HELP EMACS} at the DCL command
1360 prompt.
1361
1362 The tutorial is highly recommended in order to learn the intricacies of Emacs,
1363 which is sufficiently extensible to provide for a complete programming
1364 environment and shell for the sophisticated user.
1365 @end ifset
1366
1367 @ifclear vms
1368 @node Introduction to GPS
1369 @section Introduction to GPS
1370 @cindex GPS (GNAT Programming Studio)
1371 @cindex GNAT Programming Studio (GPS)
1372 @noindent
1373 Although the command line interface (@command{gnatmake}, etc.) alone
1374 is sufficient, a graphical Interactive Development
1375 Environment can make it easier for you to compose, navigate, and debug
1376 programs.  This section describes the main features of GPS
1377 (``GNAT Programming Studio''), the GNAT graphical IDE.
1378 You will see how to use GPS to build and debug an executable, and
1379 you will also learn some of the basics of the GNAT ``project'' facility.
1380
1381 GPS enables you to do much more than is presented here;
1382 e.g., you can produce a call graph, interface to a third-party
1383 Version Control System, and inspect the generated assembly language
1384 for a program.
1385 Indeed, GPS also supports languages other than Ada.
1386 Such additional information, and an explanation of all of the GPS menu
1387 items. may be found in the on-line help, which includes
1388 a user's guide and a tutorial (these are also accessible from the GNAT
1389 startup menu).
1390
1391 @menu
1392 * Building a New Program with GPS::
1393 * Simple Debugging with GPS::
1394 @end menu
1395
1396 @node Building a New Program with GPS
1397 @subsection Building a New Program with GPS
1398 @noindent
1399 GPS invokes the GNAT compilation tools using information
1400 contained in a @emph{project} (also known as a @emph{project file}):
1401 a collection of properties such
1402 as source directories, identities of main subprograms, tool switches, etc.,
1403 and their associated values.
1404 See @ref{GNAT Project Manager} for details.
1405 In order to run GPS, you will need to either create a new project
1406 or else open an existing one.
1407
1408 This section will explain how you can use GPS to create a project,
1409 to associate Ada source files with a project, and to build and run
1410 programs.
1411
1412 @enumerate
1413 @item @emph{Creating a project}
1414
1415 Invoke GPS, either from the command line or the platform's IDE.
1416 After it starts, GPS will display a ``Welcome'' screen with three
1417 radio buttons:
1418
1419 @itemize @bullet
1420 @item
1421 @code{Start with default project in directory}
1422
1423 @item
1424 @code{Create new project with wizard}
1425
1426 @item
1427 @code{Open existing project}
1428 @end itemize
1429
1430 @noindent
1431 Select @code{Create new project with wizard} and press @code{OK}.
1432 A new window will appear.  In the text box labeled with
1433 @code{Enter the name of the project to create}, type @file{sample}
1434 as the project name.
1435 In the next box, browse to choose the directory in which you
1436 would like to create the project file.
1437 After selecting an appropriate directory, press @code{Forward}.
1438
1439 A window will appear with the title
1440 @code{Version Control System Configuration}.
1441 Simply press @code{Forward}.
1442
1443 A window will appear with the title
1444 @code{Please select the source directories for this project}.
1445 The directory that you specified for the project file will be selected
1446 by default as the one to use for sources; simply press @code{Forward}.
1447
1448 A window will appear with the title
1449 @code{Please select the build directory for this project}.
1450 The directory that you specified for the project file will be selected
1451 by default for object files and executables;
1452 simply press @code{Forward}.
1453
1454 A window will appear with the title
1455 @code{Please select the main units for this project}.
1456 You will supply this information later, after creating the source file.
1457 Simply press @code{Forward} for now.
1458
1459 A window will appear with the title
1460 @code{Please select the switches to build the project}.
1461 Press @code{Apply}.  This will create a project file named
1462 @file{sample.prj} in the directory that you had specified.
1463
1464 @item @emph{Creating and saving the source file}
1465
1466 After you create the new project, a GPS window will appear, which is
1467 partitioned into two main sections:
1468
1469 @itemize @bullet
1470 @item
1471 A @emph{Workspace area}, initially greyed out, which you will use for
1472 creating and editing source files
1473
1474 @item
1475 Directly below, a @emph{Messages area}, which initially displays a
1476 ``Welcome'' message.
1477 (If the Messages area is not visible, drag its border upward to expand it.)
1478 @end itemize
1479
1480 @noindent
1481 Select @code{File} on the menu bar, and then the @code{New} command.
1482 The Workspace area will become white, and you can now
1483 enter the source program explicitly.
1484 Type the following text
1485
1486 @smallexample @c ada
1487 @group
1488 with Ada.Text_IO; use Ada.Text_IO;
1489 procedure Hello is
1490 begin
1491   Put_Line("Hello from GPS!");
1492 end Hello;
1493 @end group
1494 @end smallexample
1495
1496 @noindent
1497 Select @code{File}, then @code{Save As}, and enter the source file name
1498 @file{hello.adb}.
1499 The file will be saved in the same directory you specified as the
1500 location of the default project file.
1501
1502 @item @emph{Updating the project file}
1503
1504 You need to add the new source file to the project.
1505 To do this, select
1506 the @code{Project} menu and then @code{Edit project properties}.
1507 Click the @code{Main files} tab on the left, and then the
1508 @code{Add} button.
1509 Choose @file{hello.adb} from the list, and press @code{Open}.
1510 The project settings window will reflect this action.
1511 Click @code{OK}.
1512
1513 @item @emph{Building and running the program}
1514
1515 In the main GPS window, now choose the @code{Build} menu, then @code{Make},
1516 and select @file{hello.adb}.
1517 The Messages window will display the resulting invocations of @command{gcc},
1518 @command{gnatbind}, and @command{gnatlink}
1519 (reflecting the default switch settings from the
1520 project file that you created) and then a ``successful compilation/build''
1521 message.
1522
1523 To run the program, choose the @code{Build} menu, then @code{Run}, and
1524 select @command{hello}.
1525 An @emph{Arguments Selection} window will appear.
1526 There are no command line arguments, so just click @code{OK}.
1527
1528 The Messages window will now display the program's output (the string
1529 @code{Hello from GPS}), and at the bottom of the GPS window a status
1530 update is displayed (@code{Run: hello}).
1531 Close the GPS window (or select @code{File}, then @code{Exit}) to
1532 terminate this GPS session.
1533 @end enumerate
1534
1535 @node Simple Debugging with GPS
1536 @subsection Simple Debugging with GPS
1537 @noindent
1538 This section illustrates basic debugging techniques (setting breakpoints,
1539 examining/modifying variables, single stepping).
1540
1541 @enumerate
1542 @item @emph{Opening a project}
1543
1544 Start GPS and select @code{Open existing project}; browse to
1545 specify the project file @file{sample.prj} that you had created in the
1546 earlier example.
1547
1548 @item @emph{Creating a source file}
1549
1550 Select @code{File}, then @code{New}, and type in the following program:
1551
1552 @smallexample @c ada
1553 @group
1554 with Ada.Text_IO; use Ada.Text_IO;
1555 procedure Example is
1556    Line : String (1..80);
1557    N    : Natural;
1558 begin
1559    Put_Line("Type a line of text at each prompt; an empty line to exit");
1560    loop
1561       Put(": ");
1562       Get_Line (Line, N);
1563       Put_Line (Line (1..N) );
1564       exit when N=0;
1565    end loop;
1566 end Example;
1567 @end group
1568 @end smallexample
1569
1570 @noindent
1571 Select @code{File}, then @code{Save as}, and enter the file name
1572 @file{example.adb}.
1573
1574 @item @emph{Updating the project file}
1575
1576 Add @code{Example} as a new main unit for the project:
1577 @enumerate a
1578 @item
1579 Select @code{Project}, then @code{Edit Project Properties}.
1580
1581 @item
1582 Select the @code{Main files} tab, click @code{Add}, then
1583 select the file @file{example.adb} from the list, and
1584 click @code{Open}.
1585 You will see the file name appear in the list of main units
1586
1587 @item
1588 Click @code{OK}
1589 @end enumerate
1590
1591 @item @emph{Building/running the executable}
1592
1593 To build the executable
1594 select @code{Build}, then @code{Make}, and then choose @file{example.adb}.
1595
1596 Run the program to see its effect (in the Messages area).
1597 Each line that you enter is displayed; an empty line will
1598 cause the loop to exit and the program to terminate.
1599
1600 @item @emph{Debugging the program}
1601
1602 Note that the @option{-g} switches to @command{gcc} and @command{gnatlink},
1603 which are required for debugging, are on by default when you create
1604 a new project.
1605 Thus unless you intentionally remove these settings, you will be able
1606 to debug any program that you develop using GPS.
1607
1608 @enumerate a
1609 @item @emph{Initializing}
1610
1611 Select @code{Debug}, then @code{Initialize}, then @file{example}
1612
1613 @item @emph{Setting a breakpoint}
1614
1615 After performing the initialization step, you will observe a small
1616 icon to the right of each line number.
1617 This serves as a toggle for breakpoints; clicking the icon will
1618 set a breakpoint at the corresponding line (the icon will change to
1619 a red circle with an ``x''), and clicking it again
1620 will remove the breakpoint / reset the icon.
1621
1622 For purposes of this example, set a breakpoint at line 10 (the
1623 statement @code{Put_Line@ (Line@ (1..N));}
1624
1625 @item @emph{Starting program execution}
1626
1627 Select @code{Debug}, then @code{Run}.  When the
1628 @code{Program Arguments} window appears, click @code{OK}.
1629 A console window will appear; enter some line of text,
1630 e.g.@: @code{abcde}, at the prompt.
1631 The program will pause execution when it gets to the
1632 breakpoint, and the corresponding line is highlighted.
1633
1634 @item @emph{Examining a variable}
1635
1636 Move the mouse over one of the occurrences of the variable @code{N}.
1637 You will see the value (5) displayed, in ``tool tip'' fashion.
1638 Right click on @code{N}, select @code{Debug}, then select @code{Display N}.
1639 You will see information about @code{N} appear in the @code{Debugger Data}
1640 pane, showing the value as 5.
1641
1642 @item @emph{Assigning a new value to a variable}
1643
1644 Right click on the @code{N} in the @code{Debugger Data} pane, and
1645 select @code{Set value of N}.
1646 When the input window appears, enter the value @code{4} and click
1647 @code{OK}.
1648 This value does not automatically appear in the @code{Debugger Data}
1649 pane; to see it, right click again on the @code{N} in the
1650 @code{Debugger Data} pane and select @code{Update value}.
1651 The new value, 4, will appear in red.
1652
1653 @item @emph{Single stepping}
1654
1655 Select @code{Debug}, then @code{Next}.
1656 This will cause the next statement to be executed, in this case the
1657 call of @code{Put_Line} with the string slice.
1658 Notice in the console window that the displayed string is simply
1659 @code{abcd} and not @code{abcde} which you had entered.
1660 This is because the upper bound of the slice is now 4 rather than 5.
1661
1662 @item @emph{Removing a breakpoint}
1663
1664 Toggle the breakpoint icon at line 10.
1665
1666 @item @emph{Resuming execution from a breakpoint}
1667
1668 Select @code{Debug}, then @code{Continue}.
1669 The program will reach the next iteration of the loop, and
1670 wait for input after displaying the prompt.
1671 This time, just hit the @kbd{Enter} key.
1672 The value of @code{N} will be 0, and the program will terminate.
1673 The console window will disappear.
1674 @end enumerate
1675 @end enumerate
1676 @end ifclear
1677
1678 @node The GNAT Compilation Model
1679 @chapter The GNAT Compilation Model
1680 @cindex GNAT compilation model
1681 @cindex Compilation model
1682
1683 @menu
1684 * Source Representation::
1685 * Foreign Language Representation::
1686 * File Naming Rules::
1687 * Using Other File Names::
1688 * Alternative File Naming Schemes::
1689 * Generating Object Files::
1690 * Source Dependencies::
1691 * The Ada Library Information Files::
1692 * Binding an Ada Program::
1693 * Mixed Language Programming::
1694 @ifclear vms
1695 * Building Mixed Ada & C++ Programs::
1696 * Comparison between GNAT and C/C++ Compilation Models::
1697 @end ifclear
1698 * Comparison between GNAT and Conventional Ada Library Models::
1699 @ifset vms
1700 * Placement of temporary files::
1701 @end ifset
1702 @end menu
1703
1704 @noindent
1705 This chapter describes the compilation model used by GNAT. Although
1706 similar to that used by other languages, such as C and C++, this model
1707 is substantially different from the traditional Ada compilation models,
1708 which are based on a library. The model is initially described without
1709 reference to the library-based model. If you have not previously used an
1710 Ada compiler, you need only read the first part of this chapter. The
1711 last section describes and discusses the differences between the GNAT
1712 model and the traditional Ada compiler models. If you have used other
1713 Ada compilers, this section will help you to understand those
1714 differences, and the advantages of the GNAT model.
1715
1716 @node Source Representation
1717 @section Source Representation
1718 @cindex Latin-1
1719
1720 @noindent
1721 Ada source programs are represented in standard text files, using
1722 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1723 7-bit ASCII set, plus additional characters used for
1724 representing foreign languages (@pxref{Foreign Language Representation}
1725 for support of non-USA character sets). The format effector characters
1726 are represented using their standard ASCII encodings, as follows:
1727
1728 @table @code
1729 @item VT
1730 @findex VT
1731 Vertical tab, @code{16#0B#}
1732
1733 @item HT
1734 @findex HT
1735 Horizontal tab, @code{16#09#}
1736
1737 @item CR
1738 @findex CR
1739 Carriage return, @code{16#0D#}
1740
1741 @item LF
1742 @findex LF
1743 Line feed, @code{16#0A#}
1744
1745 @item FF
1746 @findex FF
1747 Form feed, @code{16#0C#}
1748 @end table
1749
1750 @noindent
1751 Source files are in standard text file format. In addition, GNAT will
1752 recognize a wide variety of stream formats, in which the end of
1753 physical lines is marked by any of the following sequences:
1754 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1755 in accommodating files that are imported from other operating systems.
1756
1757 @cindex End of source file
1758 @cindex Source file, end
1759 @findex SUB
1760 The end of a source file is normally represented by the physical end of
1761 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1762 recognized as signalling the end of the source file. Again, this is
1763 provided for compatibility with other operating systems where this
1764 code is used to represent the end of file.
1765
1766 Each file contains a single Ada compilation unit, including any pragmas
1767 associated with the unit. For example, this means you must place a
1768 package declaration (a package @dfn{spec}) and the corresponding body in
1769 separate files. An Ada @dfn{compilation} (which is a sequence of
1770 compilation units) is represented using a sequence of files. Similarly,
1771 you will place each subunit or child unit in a separate file.
1772
1773 @node Foreign Language Representation
1774 @section Foreign Language Representation
1775
1776 @noindent
1777 GNAT supports the standard character sets defined in Ada as well as
1778 several other non-standard character sets for use in localized versions
1779 of the compiler (@pxref{Character Set Control}).
1780 @menu
1781 * Latin-1::
1782 * Other 8-Bit Codes::
1783 * Wide Character Encodings::
1784 @end menu
1785
1786 @node Latin-1
1787 @subsection Latin-1
1788 @cindex Latin-1
1789
1790 @noindent
1791 The basic character set is Latin-1. This character set is defined by ISO
1792 standard 8859, part 1. The lower half (character codes @code{16#00#}
1793 @dots{} @code{16#7F#)} is identical to standard ASCII coding, but the upper
1794 half is used to represent additional characters. These include extended letters
1795 used by European languages, such as French accents, the vowels with umlauts
1796 used in German, and the extra letter A-ring used in Swedish.
1797
1798 @findex Ada.Characters.Latin_1
1799 For a complete list of Latin-1 codes and their encodings, see the source
1800 file of library unit @code{Ada.Characters.Latin_1} in file
1801 @file{a-chlat1.ads}.
1802 You may use any of these extended characters freely in character or
1803 string literals. In addition, the extended characters that represent
1804 letters can be used in identifiers.
1805
1806 @node Other 8-Bit Codes
1807 @subsection Other 8-Bit Codes
1808
1809 @noindent
1810 GNAT also supports several other 8-bit coding schemes:
1811
1812 @table @asis
1813 @item ISO 8859-2 (Latin-2)
1814 @cindex Latin-2
1815 @cindex ISO 8859-2
1816 Latin-2 letters allowed in identifiers, with uppercase and lowercase
1817 equivalence.
1818
1819 @item ISO 8859-3 (Latin-3)
1820 @cindex Latin-3
1821 @cindex ISO 8859-3
1822 Latin-3 letters allowed in identifiers, with uppercase and lowercase
1823 equivalence.
1824
1825 @item ISO 8859-4 (Latin-4)
1826 @cindex Latin-4
1827 @cindex ISO 8859-4
1828 Latin-4 letters allowed in identifiers, with uppercase and lowercase
1829 equivalence.
1830
1831 @item ISO 8859-5 (Cyrillic)
1832 @cindex ISO 8859-5
1833 @cindex Cyrillic
1834 ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
1835 lowercase equivalence.
1836
1837 @item ISO 8859-15 (Latin-9)
1838 @cindex ISO 8859-15
1839 @cindex Latin-9
1840 ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
1841 lowercase equivalence
1842
1843 @item IBM PC (code page 437)
1844 @cindex code page 437
1845 This code page is the normal default for PCs in the U.S. It corresponds
1846 to the original IBM PC character set. This set has some, but not all, of
1847 the extended Latin-1 letters, but these letters do not have the same
1848 encoding as Latin-1. In this mode, these letters are allowed in
1849 identifiers with uppercase and lowercase equivalence.
1850
1851 @item IBM PC (code page 850)
1852 @cindex code page 850
1853 This code page is a modification of 437 extended to include all the
1854 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
1855 mode, all these letters are allowed in identifiers with uppercase and
1856 lowercase equivalence.
1857
1858 @item Full Upper 8-bit
1859 Any character in the range 80-FF allowed in identifiers, and all are
1860 considered distinct. In other words, there are no uppercase and lowercase
1861 equivalences in this range. This is useful in conjunction with
1862 certain encoding schemes used for some foreign character sets (e.g.,
1863 the typical method of representing Chinese characters on the PC).
1864
1865 @item No Upper-Half
1866 No upper-half characters in the range 80-FF are allowed in identifiers.
1867 This gives Ada 83 compatibility for identifier names.
1868 @end table
1869
1870 @noindent
1871 For precise data on the encodings permitted, and the uppercase and lowercase
1872 equivalences that are recognized, see the file @file{csets.adb} in
1873 the GNAT compiler sources. You will need to obtain a full source release
1874 of GNAT to obtain this file.
1875
1876 @node Wide Character Encodings
1877 @subsection Wide Character Encodings
1878
1879 @noindent
1880 GNAT allows wide character codes to appear in character and string
1881 literals, and also optionally in identifiers, by means of the following
1882 possible encoding schemes:
1883
1884 @table @asis
1885
1886 @item Hex Coding
1887 In this encoding, a wide character is represented by the following five
1888 character sequence:
1889
1890 @smallexample
1891 ESC a b c d
1892 @end smallexample
1893
1894 @noindent
1895 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1896 characters (using uppercase letters) of the wide character code. For
1897 example, ESC A345 is used to represent the wide character with code
1898 @code{16#A345#}.
1899 This scheme is compatible with use of the full Wide_Character set.
1900
1901 @item Upper-Half Coding
1902 @cindex Upper-Half Coding
1903 The wide character with encoding @code{16#abcd#} where the upper bit is on
1904 (in other words, ``a'' is in the range 8-F) is represented as two bytes,
1905 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
1906 character, but is not required to be in the upper half. This method can
1907 be also used for shift-JIS or EUC, where the internal coding matches the
1908 external coding.
1909
1910 @item Shift JIS Coding
1911 @cindex Shift JIS Coding
1912 A wide character is represented by a two-character sequence,
1913 @code{16#ab#} and
1914 @code{16#cd#}, with the restrictions described for upper-half encoding as
1915 described above. The internal character code is the corresponding JIS
1916 character according to the standard algorithm for Shift-JIS
1917 conversion. Only characters defined in the JIS code set table can be
1918 used with this encoding method.
1919
1920 @item EUC Coding
1921 @cindex EUC Coding
1922 A wide character is represented by a two-character sequence
1923 @code{16#ab#} and
1924 @code{16#cd#}, with both characters being in the upper half. The internal
1925 character code is the corresponding JIS character according to the EUC
1926 encoding algorithm. Only characters defined in the JIS code set table
1927 can be used with this encoding method.
1928
1929 @item UTF-8 Coding
1930 A wide character is represented using
1931 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1932 10646-1/Am.2. Depending on the character value, the representation
1933 is a one, two, or three byte sequence:
1934 @smallexample
1935 @iftex
1936 @leftskip=.7cm
1937 @end iftex
1938 16#0000#-16#007f#: 2#0@var{xxxxxxx}#
1939 16#0080#-16#07ff#: 2#110@var{xxxxx}# 2#10@var{xxxxxx}#
1940 16#0800#-16#ffff#: 2#1110@var{xxxx}# 2#10@var{xxxxxx}# 2#10@var{xxxxxx}#
1941
1942 @end smallexample
1943
1944 @noindent
1945 where the @var{xxx} bits correspond to the left-padded bits of the
1946 16-bit character value. Note that all lower half ASCII characters
1947 are represented as ASCII bytes and all upper half characters and
1948 other wide characters are represented as sequences of upper-half
1949 (The full UTF-8 scheme allows for encoding 31-bit characters as
1950 6-byte sequences, but in this implementation, all UTF-8 sequences
1951 of four or more bytes length will be treated as illegal).
1952 @item Brackets Coding
1953 In this encoding, a wide character is represented by the following eight
1954 character sequence:
1955
1956 @smallexample
1957 [ " a b c d " ]
1958 @end smallexample
1959
1960 @noindent
1961 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1962 characters (using uppercase letters) of the wide character code. For
1963 example, [``A345''] is used to represent the wide character with code
1964 @code{16#A345#}. It is also possible (though not required) to use the
1965 Brackets coding for upper half characters. For example, the code
1966 @code{16#A3#} can be represented as @code{[``A3'']}.
1967
1968 This scheme is compatible with use of the full Wide_Character set,
1969 and is also the method used for wide character encoding in the standard
1970 ACVC (Ada Compiler Validation Capability) test suite distributions.
1971
1972 @end table
1973
1974 @noindent
1975 Note: Some of these coding schemes do not permit the full use of the
1976 Ada character set. For example, neither Shift JIS, nor EUC allow the
1977 use of the upper half of the Latin-1 set.
1978
1979 @node File Naming Rules
1980 @section File Naming Rules
1981
1982 @noindent
1983 The default file name is determined by the name of the unit that the
1984 file contains. The name is formed by taking the full expanded name of
1985 the unit and replacing the separating dots with hyphens and using
1986 ^lowercase^uppercase^ for all letters.
1987
1988 An exception arises if the file name generated by the above rules starts
1989 with one of the characters
1990 @ifset vms
1991 @samp{A}, @samp{G}, @samp{I}, or @samp{S},
1992 @end ifset
1993 @ifclear vms
1994 @samp{a}, @samp{g}, @samp{i}, or @samp{s},
1995 @end ifclear
1996 and the second character is a
1997 minus. In this case, the character ^tilde^dollar sign^ is used in place
1998 of the minus. The reason for this special rule is to avoid clashes with
1999 the standard names for child units of the packages System, Ada,
2000 Interfaces, and GNAT, which use the prefixes
2001 @ifset vms
2002 @samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},
2003 @end ifset
2004 @ifclear vms
2005 @samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},
2006 @end ifclear
2007 respectively.
2008
2009 The file extension is @file{.ads} for a spec and
2010 @file{.adb} for a body. The following list shows some
2011 examples of these rules.
2012
2013 @table @file
2014 @item main.ads
2015 Main (spec)
2016 @item main.adb
2017 Main (body)
2018 @item arith_functions.ads
2019 Arith_Functions (package spec)
2020 @item arith_functions.adb
2021 Arith_Functions (package body)
2022 @item func-spec.ads
2023 Func.Spec (child package spec)
2024 @item func-spec.adb
2025 Func.Spec (child package body)
2026 @item main-sub.adb
2027 Sub (subunit of Main)
2028 @item ^a~bad.adb^A$BAD.ADB^
2029 A.Bad (child package body)
2030 @end table
2031
2032 @noindent
2033 Following these rules can result in excessively long
2034 file names if corresponding
2035 unit names are long (for example, if child units or subunits are
2036 heavily nested). An option is available to shorten such long file names
2037 (called file name ``krunching''). This may be particularly useful when
2038 programs being developed with GNAT are to be used on operating systems
2039 with limited file name lengths. @xref{Using gnatkr}.
2040
2041 Of course, no file shortening algorithm can guarantee uniqueness over
2042 all possible unit names; if file name krunching is used, it is your
2043 responsibility to ensure no name clashes occur. Alternatively you
2044 can specify the exact file names that you want used, as described
2045 in the next section. Finally, if your Ada programs are migrating from a
2046 compiler with a different naming convention, you can use the gnatchop
2047 utility to produce source files that follow the GNAT naming conventions.
2048 (For details @pxref{Renaming Files Using gnatchop}.)
2049
2050 Note: in the case of @code{Windows NT/XP} or @code{OpenVMS} operating
2051 systems, case is not significant. So for example on @code{Windows XP}
2052 if the canonical name is @code{main-sub.adb}, you can use the file name
2053 @code{Main-Sub.adb} instead. However, case is significant for other
2054 operating systems, so for example, if you want to use other than
2055 canonically cased file names on a Unix system, you need to follow
2056 the procedures described in the next section.
2057
2058 @node Using Other File Names
2059 @section Using Other File Names
2060 @cindex File names
2061
2062 @noindent
2063 In the previous section, we have described the default rules used by
2064 GNAT to determine the file name in which a given unit resides. It is
2065 often convenient to follow these default rules, and if you follow them,
2066 the compiler knows without being explicitly told where to find all
2067 the files it needs.
2068
2069 However, in some cases, particularly when a program is imported from
2070 another Ada compiler environment, it may be more convenient for the
2071 programmer to specify which file names contain which units. GNAT allows
2072 arbitrary file names to be used by means of the Source_File_Name pragma.
2073 The form of this pragma is as shown in the following examples:
2074 @cindex Source_File_Name pragma
2075
2076 @smallexample @c ada
2077 @cartouche
2078 pragma Source_File_Name (My_Utilities.Stacks,
2079   Spec_File_Name => "myutilst_a.ada");
2080 pragma Source_File_name (My_Utilities.Stacks,
2081   Body_File_Name => "myutilst.ada");
2082 @end cartouche
2083 @end smallexample
2084
2085 @noindent
2086 As shown in this example, the first argument for the pragma is the unit
2087 name (in this example a child unit). The second argument has the form
2088 of a named association. The identifier
2089 indicates whether the file name is for a spec or a body;
2090 the file name itself is given by a string literal.
2091
2092 The source file name pragma is a configuration pragma, which means that
2093 normally it will be placed in the @file{gnat.adc}
2094 file used to hold configuration
2095 pragmas that apply to a complete compilation environment.
2096 For more details on how the @file{gnat.adc} file is created and used
2097 see @ref{Handling of Configuration Pragmas}.
2098 @cindex @file{gnat.adc}
2099
2100 @ifclear vms
2101 GNAT allows completely arbitrary file names to be specified using the
2102 source file name pragma. However, if the file name specified has an
2103 extension other than @file{.ads} or @file{.adb} it is necessary to use
2104 a special syntax when compiling the file. The name in this case must be
2105 preceded by the special sequence @option{-x} followed by a space and the name
2106 of the language, here @code{ada}, as in:
2107
2108 @smallexample
2109 $ gcc -c -x ada peculiar_file_name.sim
2110 @end smallexample
2111 @end ifclear
2112
2113 @noindent
2114 @command{gnatmake} handles non-standard file names in the usual manner (the
2115 non-standard file name for the main program is simply used as the
2116 argument to gnatmake). Note that if the extension is also non-standard,
2117 then it must be included in the @command{gnatmake} command, it may not
2118 be omitted.
2119
2120 @node Alternative File Naming Schemes
2121 @section Alternative File Naming Schemes
2122 @cindex File naming schemes, alternative
2123 @cindex File names
2124
2125 In the previous section, we described the use of the @code{Source_File_Name}
2126 pragma to allow arbitrary names to be assigned to individual source files.
2127 However, this approach requires one pragma for each file, and especially in
2128 large systems can result in very long @file{gnat.adc} files, and also create
2129 a maintenance problem.
2130
2131 GNAT also provides a facility for specifying systematic file naming schemes
2132 other than the standard default naming scheme previously described. An
2133 alternative scheme for naming is specified by the use of
2134 @code{Source_File_Name} pragmas having the following format:
2135 @cindex Source_File_Name pragma
2136
2137 @smallexample @c ada
2138 pragma Source_File_Name (
2139    Spec_File_Name  => FILE_NAME_PATTERN
2140  @r{[},Casing          => CASING_SPEC@r{]}
2141  @r{[},Dot_Replacement => STRING_LITERAL@r{]});
2142
2143 pragma Source_File_Name (
2144    Body_File_Name  => FILE_NAME_PATTERN
2145  @r{[},Casing          => CASING_SPEC@r{]}
2146  @r{[},Dot_Replacement => STRING_LITERAL@r{]});
2147
2148 pragma Source_File_Name (
2149    Subunit_File_Name  => FILE_NAME_PATTERN
2150  @r{[},Casing             => CASING_SPEC@r{]}
2151  @r{[},Dot_Replacement    => STRING_LITERAL@r{]});
2152
2153 FILE_NAME_PATTERN ::= STRING_LITERAL
2154 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
2155 @end smallexample
2156
2157 @noindent
2158 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
2159 It contains a single asterisk character, and the unit name is substituted
2160 systematically for this asterisk. The optional parameter
2161 @code{Casing} indicates
2162 whether the unit name is to be all upper-case letters, all lower-case letters,
2163 or mixed-case. If no
2164 @code{Casing} parameter is used, then the default is all
2165 ^lower-case^upper-case^.
2166
2167 The optional @code{Dot_Replacement} string is used to replace any periods
2168 that occur in subunit or child unit names. If no @code{Dot_Replacement}
2169 argument is used then separating dots appear unchanged in the resulting
2170 file name.
2171 Although the above syntax indicates that the
2172 @code{Casing} argument must appear
2173 before the @code{Dot_Replacement} argument, but it
2174 is also permissible to write these arguments in the opposite order.
2175
2176 As indicated, it is possible to specify different naming schemes for
2177 bodies, specs, and subunits. Quite often the rule for subunits is the
2178 same as the rule for bodies, in which case, there is no need to give
2179 a separate @code{Subunit_File_Name} rule, and in this case the
2180 @code{Body_File_name} rule is used for subunits as well.
2181
2182 The separate rule for subunits can also be used to implement the rather
2183 unusual case of a compilation environment (e.g.@: a single directory) which
2184 contains a subunit and a child unit with the same unit name. Although
2185 both units cannot appear in the same partition, the Ada Reference Manual
2186 allows (but does not require) the possibility of the two units coexisting
2187 in the same environment.
2188
2189 The file name translation works in the following steps:
2190
2191 @itemize @bullet
2192
2193 @item
2194 If there is a specific @code{Source_File_Name} pragma for the given unit,
2195 then this is always used, and any general pattern rules are ignored.
2196
2197 @item
2198 If there is a pattern type @code{Source_File_Name} pragma that applies to
2199 the unit, then the resulting file name will be used if the file exists. If
2200 more than one pattern matches, the latest one will be tried first, and the
2201 first attempt resulting in a reference to a file that exists will be used.
2202
2203 @item
2204 If no pattern type @code{Source_File_Name} pragma that applies to the unit
2205 for which the corresponding file exists, then the standard GNAT default
2206 naming rules are used.
2207
2208 @end itemize
2209
2210 @noindent
2211 As an example of the use of this mechanism, consider a commonly used scheme
2212 in which file names are all lower case, with separating periods copied
2213 unchanged to the resulting file name, and specs end with @file{.1.ada}, and
2214 bodies end with @file{.2.ada}. GNAT will follow this scheme if the following
2215 two pragmas appear:
2216
2217 @smallexample @c ada
2218 pragma Source_File_Name
2219   (Spec_File_Name => "*.1.ada");
2220 pragma Source_File_Name
2221   (Body_File_Name => "*.2.ada");
2222 @end smallexample
2223
2224 @noindent
2225 The default GNAT scheme is actually implemented by providing the following
2226 default pragmas internally:
2227
2228 @smallexample @c ada
2229 pragma Source_File_Name
2230   (Spec_File_Name => "*.ads", Dot_Replacement => "-");
2231 pragma Source_File_Name
2232   (Body_File_Name => "*.adb", Dot_Replacement => "-");
2233 @end smallexample
2234
2235 @noindent
2236 Our final example implements a scheme typically used with one of the
2237 Ada 83 compilers, where the separator character for subunits was ``__''
2238 (two underscores), specs were identified by adding @file{_.ADA}, bodies
2239 by adding @file{.ADA}, and subunits by
2240 adding @file{.SEP}. All file names were
2241 upper case. Child units were not present of course since this was an
2242 Ada 83 compiler, but it seems reasonable to extend this scheme to use
2243 the same double underscore separator for child units.
2244
2245 @smallexample @c ada
2246 pragma Source_File_Name
2247   (Spec_File_Name => "*_.ADA",
2248    Dot_Replacement => "__",
2249    Casing = Uppercase);
2250 pragma Source_File_Name
2251   (Body_File_Name => "*.ADA",
2252    Dot_Replacement => "__",
2253    Casing = Uppercase);
2254 pragma Source_File_Name
2255   (Subunit_File_Name => "*.SEP",
2256    Dot_Replacement => "__",
2257    Casing = Uppercase);
2258 @end smallexample
2259
2260 @node Generating Object Files
2261 @section Generating Object Files
2262
2263 @noindent
2264 An Ada program consists of a set of source files, and the first step in
2265 compiling the program is to generate the corresponding object files.
2266 These are generated by compiling a subset of these source files.
2267 The files you need to compile are the following:
2268
2269 @itemize @bullet
2270 @item
2271 If a package spec has no body, compile the package spec to produce the
2272 object file for the package.
2273
2274 @item
2275 If a package has both a spec and a body, compile the body to produce the
2276 object file for the package. The source file for the package spec need
2277 not be compiled in this case because there is only one object file, which
2278 contains the code for both the spec and body of the package.
2279
2280 @item
2281 For a subprogram, compile the subprogram body to produce the object file
2282 for the subprogram. The spec, if one is present, is as usual in a
2283 separate file, and need not be compiled.
2284
2285 @item
2286 @cindex Subunits
2287 In the case of subunits, only compile the parent unit. A single object
2288 file is generated for the entire subunit tree, which includes all the
2289 subunits.
2290
2291 @item
2292 Compile child units independently of their parent units
2293 (though, of course, the spec of all the ancestor unit must be present in order
2294 to compile a child unit).
2295
2296 @item
2297 @cindex Generics
2298 Compile generic units in the same manner as any other units. The object
2299 files in this case are small dummy files that contain at most the
2300 flag used for elaboration checking. This is because GNAT always handles generic
2301 instantiation by means of macro expansion. However, it is still necessary to
2302 compile generic units, for dependency checking and elaboration purposes.
2303 @end itemize
2304
2305 @noindent
2306 The preceding rules describe the set of files that must be compiled to
2307 generate the object files for a program. Each object file has the same
2308 name as the corresponding source file, except that the extension is
2309 @file{.o} as usual.
2310
2311 You may wish to compile other files for the purpose of checking their
2312 syntactic and semantic correctness. For example, in the case where a
2313 package has a separate spec and body, you would not normally compile the
2314 spec. However, it is convenient in practice to compile the spec to make
2315 sure it is error-free before compiling clients of this spec, because such
2316 compilations will fail if there is an error in the spec.
2317
2318 GNAT provides an option for compiling such files purely for the
2319 purposes of checking correctness; such compilations are not required as
2320 part of the process of building a program. To compile a file in this
2321 checking mode, use the @option{-gnatc} switch.
2322
2323 @node Source Dependencies
2324 @section Source Dependencies
2325
2326 @noindent
2327 A given object file clearly depends on the source file which is compiled
2328 to produce it. Here we are using @dfn{depends} in the sense of a typical
2329 @code{make} utility; in other words, an object file depends on a source
2330 file if changes to the source file require the object file to be
2331 recompiled.
2332 In addition to this basic dependency, a given object may depend on
2333 additional source files as follows:
2334
2335 @itemize @bullet
2336 @item
2337 If a file being compiled @code{with}'s a unit @var{X}, the object file
2338 depends on the file containing the spec of unit @var{X}. This includes
2339 files that are @code{with}'ed implicitly either because they are parents
2340 of @code{with}'ed child units or they are run-time units required by the
2341 language constructs used in a particular unit.
2342
2343 @item
2344 If a file being compiled instantiates a library level generic unit, the
2345 object file depends on both the spec and body files for this generic
2346 unit.
2347
2348 @item
2349 If a file being compiled instantiates a generic unit defined within a
2350 package, the object file depends on the body file for the package as
2351 well as the spec file.
2352
2353 @item
2354 @findex Inline
2355 @cindex @option{-gnatn} switch
2356 If a file being compiled contains a call to a subprogram for which
2357 pragma @code{Inline} applies and inlining is activated with the
2358 @option{-gnatn} switch, the object file depends on the file containing the
2359 body of this subprogram as well as on the file containing the spec. Note
2360 that for inlining to actually occur as a result of the use of this switch,
2361 it is necessary to compile in optimizing mode.
2362
2363 @cindex @option{-gnatN} switch
2364 The use of @option{-gnatN} activates  inlining optimization
2365 that is performed by the front end of the compiler. This inlining does
2366 not require that the code generation be optimized. Like @option{-gnatn},
2367 the use of this switch generates additional dependencies.
2368
2369 When using a gcc-based back end (in practice this means using any version
2370 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
2371 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
2372 Historically front end inlining was more extensive than the gcc back end
2373 inlining, but that is no longer the case.
2374
2375 @item
2376 If an object file @file{O} depends on the proper body of a subunit through
2377 inlining or instantiation, it depends on the parent unit of the subunit.
2378 This means that any modification of the parent unit or one of its subunits
2379 affects the compilation of @file{O}.
2380
2381 @item
2382 The object file for a parent unit depends on all its subunit body files.
2383
2384 @item
2385 The previous two rules meant that for purposes of computing dependencies and
2386 recompilation, a body and all its subunits are treated as an indivisible whole.
2387
2388 @noindent
2389 These rules are applied transitively: if unit @code{A} @code{with}'s
2390 unit @code{B}, whose elaboration calls an inlined procedure in package
2391 @code{C}, the object file for unit @code{A} will depend on the body of
2392 @code{C}, in file @file{c.adb}.
2393
2394 The set of dependent files described by these rules includes all the
2395 files on which the unit is semantically dependent, as dictated by the
2396 Ada language standard. However, it is a superset of what the
2397 standard describes, because it includes generic, inline, and subunit
2398 dependencies.
2399
2400 An object file must be recreated by recompiling the corresponding source
2401 file if any of the source files on which it depends are modified. For
2402 example, if the @code{make} utility is used to control compilation,
2403 the rule for an Ada object file must mention all the source files on
2404 which the object file depends, according to the above definition.
2405 The determination of the necessary
2406 recompilations is done automatically when one uses @command{gnatmake}.
2407 @end itemize
2408
2409 @node The Ada Library Information Files
2410 @section The Ada Library Information Files
2411 @cindex Ada Library Information files
2412 @cindex @file{ALI} files
2413
2414 @noindent
2415 Each compilation actually generates two output files. The first of these
2416 is the normal object file that has a @file{.o} extension. The second is a
2417 text file containing full dependency information. It has the same
2418 name as the source file, but an @file{.ali} extension.
2419 This file is known as the Ada Library Information (@file{ALI}) file.
2420 The following information is contained in the @file{ALI} file.
2421
2422 @itemize @bullet
2423 @item
2424 Version information (indicates which version of GNAT was used to compile
2425 the unit(s) in question)
2426
2427 @item
2428 Main program information (including priority and time slice settings,
2429 as well as the wide character encoding used during compilation).
2430
2431 @item
2432 List of arguments used in the @command{gcc} command for the compilation
2433
2434 @item
2435 Attributes of the unit, including configuration pragmas used, an indication
2436 of whether the compilation was successful, exception model used etc.
2437
2438 @item
2439 A list of relevant restrictions applying to the unit (used for consistency)
2440 checking.
2441
2442 @item
2443 Categorization information (e.g.@: use of pragma @code{Pure}).
2444
2445 @item
2446 Information on all @code{with}'ed units, including presence of
2447 @code{Elaborate} or @code{Elaborate_All} pragmas.
2448
2449 @item
2450 Information from any @code{Linker_Options} pragmas used in the unit
2451
2452 @item
2453 Information on the use of @code{Body_Version} or @code{Version}
2454 attributes in the unit.
2455
2456 @item
2457 Dependency information. This is a list of files, together with
2458 time stamp and checksum information. These are files on which
2459 the unit depends in the sense that recompilation is required
2460 if any of these units are modified.
2461
2462 @item
2463 Cross-reference data. Contains information on all entities referenced
2464 in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
2465 provide cross-reference information.
2466
2467 @end itemize
2468
2469 @noindent
2470 For a full detailed description of the format of the @file{ALI} file,
2471 see the source of the body of unit @code{Lib.Writ}, contained in file
2472 @file{lib-writ.adb} in the GNAT compiler sources.
2473
2474 @node Binding an Ada Program
2475 @section Binding an Ada Program
2476
2477 @noindent
2478 When using languages such as C and C++, once the source files have been
2479 compiled the only remaining step in building an executable program
2480 is linking the object modules together. This means that it is possible to
2481 link an inconsistent version of a program, in which two units have
2482 included different versions of the same header.
2483
2484 The rules of Ada do not permit such an inconsistent program to be built.
2485 For example, if two clients have different versions of the same package,
2486 it is illegal to build a program containing these two clients.
2487 These rules are enforced by the GNAT binder, which also determines an
2488 elaboration order consistent with the Ada rules.
2489
2490 The GNAT binder is run after all the object files for a program have
2491 been created. It is given the name of the main program unit, and from
2492 this it determines the set of units required by the program, by reading the
2493 corresponding ALI files. It generates error messages if the program is
2494 inconsistent or if no valid order of elaboration exists.
2495
2496 If no errors are detected, the binder produces a main program, in Ada by
2497 default, that contains calls to the elaboration procedures of those
2498 compilation unit that require them, followed by
2499 a call to the main program. This Ada program is compiled to generate the
2500 object file for the main program. The name of
2501 the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec
2502 @file{b~@var{xxx}.ads}) where @var{xxx} is the name of the
2503 main program unit.
2504
2505 Finally, the linker is used to build the resulting executable program,
2506 using the object from the main program from the bind step as well as the
2507 object files for the Ada units of the program.
2508
2509 @node Mixed Language Programming
2510 @section Mixed Language Programming
2511 @cindex Mixed Language Programming
2512
2513 @noindent
2514 This section describes how to develop a mixed-language program,
2515 specifically one that comprises units in both Ada and C.
2516
2517 @menu
2518 * Interfacing to C::
2519 * Calling Conventions::
2520 @end menu
2521
2522 @node Interfacing to C
2523 @subsection Interfacing to C
2524 @noindent
2525 Interfacing Ada with a foreign language such as C involves using
2526 compiler directives to import and/or export entity definitions in each
2527 language---using @code{extern} statements in C, for instance, and the
2528 @code{Import}, @code{Export}, and @code{Convention} pragmas in Ada.
2529 A full treatment of these topics is provided in Appendix B, section 1
2530 of the Ada Reference Manual.
2531
2532 There are two ways to build a program using GNAT that contains some Ada
2533 sources and some foreign language sources, depending on whether or not
2534 the main subprogram is written in Ada.  Here is a source example with
2535 the main subprogram in Ada:
2536
2537 @smallexample
2538 /* file1.c */
2539 #include <stdio.h>
2540
2541 void print_num (int num)
2542 @{
2543   printf ("num is %d.\n", num);
2544   return;
2545 @}
2546
2547 /* file2.c */
2548
2549 /* num_from_Ada is declared in my_main.adb */
2550 extern int num_from_Ada;
2551
2552 int get_num (void)
2553 @{
2554   return num_from_Ada;
2555 @}
2556 @end smallexample
2557
2558 @smallexample @c ada
2559 --  my_main.adb
2560 procedure My_Main is
2561
2562    --  Declare then export an Integer entity called num_from_Ada
2563    My_Num : Integer := 10;
2564    pragma Export (C, My_Num, "num_from_Ada");
2565
2566    --  Declare an Ada function spec for Get_Num, then use
2567    --  C function get_num for the implementation.
2568    function Get_Num return Integer;
2569    pragma Import (C, Get_Num, "get_num");
2570
2571    --  Declare an Ada procedure spec for Print_Num, then use
2572    --  C function print_num for the implementation.
2573    procedure Print_Num (Num : Integer);
2574    pragma Import (C, Print_Num, "print_num");
2575
2576 begin
2577    Print_Num (Get_Num);
2578 end My_Main;
2579 @end smallexample
2580
2581 @enumerate
2582 @item
2583 To build this example, first compile the foreign language files to
2584 generate object files:
2585 @smallexample
2586 ^gcc -c file1.c^gcc -c FILE1.C^
2587 ^gcc -c file2.c^gcc -c FILE2.C^
2588 @end smallexample
2589
2590 @item
2591 Then, compile the Ada units to produce a set of object files and ALI
2592 files:
2593 @smallexample
2594 gnatmake ^-c^/ACTIONS=COMPILE^ my_main.adb
2595 @end smallexample
2596
2597 @item
2598 Run the Ada binder on the Ada main program:
2599 @smallexample
2600 gnatbind my_main.ali
2601 @end smallexample
2602
2603 @item
2604 Link the Ada main program, the Ada objects and the other language
2605 objects:
2606 @smallexample
2607 gnatlink my_main.ali file1.o file2.o
2608 @end smallexample
2609 @end enumerate
2610
2611 The last three steps can be grouped in a single command:
2612 @smallexample
2613 gnatmake my_main.adb -largs file1.o file2.o
2614 @end smallexample
2615
2616 @cindex Binder output file
2617 @noindent
2618 If the main program is in a language other than Ada, then you may have
2619 more than one entry point into the Ada subsystem. You must use a special
2620 binder option to generate callable routines that initialize and
2621 finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}).
2622 Calls to the initialization and finalization routines must be inserted
2623 in the main program, or some other appropriate point in the code. The
2624 call to initialize the Ada units must occur before the first Ada
2625 subprogram is called, and the call to finalize the Ada units must occur
2626 after the last Ada subprogram returns. The binder will place the
2627 initialization and finalization subprograms into the
2628 @file{b~@var{xxx}.adb} file where they can be accessed by your C
2629 sources.  To illustrate, we have the following example:
2630
2631 @smallexample
2632 /* main.c */
2633 extern void adainit (void);
2634 extern void adafinal (void);
2635 extern int add (int, int);
2636 extern int sub (int, int);
2637
2638 int main (int argc, char *argv[])
2639 @{
2640   int a = 21, b = 7;
2641
2642   adainit();
2643
2644   /* Should print "21 + 7 = 28" */
2645   printf ("%d + %d = %d\n", a, b, add (a, b));
2646   /* Should print "21 - 7 = 14" */
2647   printf ("%d - %d = %d\n", a, b, sub (a, b));
2648
2649   adafinal();
2650 @}
2651 @end smallexample
2652
2653 @smallexample @c ada
2654 --  unit1.ads
2655 package Unit1 is
2656    function Add (A, B : Integer) return Integer;
2657    pragma Export (C, Add, "add");
2658 end Unit1;
2659
2660 --  unit1.adb
2661 package body Unit1 is
2662    function Add (A, B : Integer) return Integer is
2663    begin
2664       return A + B;
2665    end Add;
2666 end Unit1;
2667
2668 --  unit2.ads
2669 package Unit2 is
2670    function Sub (A, B : Integer) return Integer;
2671    pragma Export (C, Sub, "sub");
2672 end Unit2;
2673
2674 --  unit2.adb
2675 package body Unit2 is
2676    function Sub (A, B : Integer) return Integer is
2677    begin
2678       return A - B;
2679    end Sub;
2680 end Unit2;
2681 @end smallexample
2682
2683 @enumerate
2684 @item
2685 The build procedure for this application is similar to the last
2686 example's.  First, compile the foreign language files to generate object
2687 files:
2688 @smallexample
2689 ^gcc -c main.c^gcc -c main.c^
2690 @end smallexample
2691
2692 @item
2693 Next, compile the Ada units to produce a set of object files and ALI
2694 files:
2695 @smallexample
2696 gnatmake ^-c^/ACTIONS=COMPILE^ unit1.adb
2697 gnatmake ^-c^/ACTIONS=COMPILE^ unit2.adb
2698 @end smallexample
2699
2700 @item
2701 Run the Ada binder on every generated ALI file.  Make sure to use the
2702 @option{-n} option to specify a foreign main program:
2703 @smallexample
2704 gnatbind ^-n^/NOMAIN^ unit1.ali unit2.ali
2705 @end smallexample
2706
2707 @item
2708 Link the Ada main program, the Ada objects and the foreign language
2709 objects. You need only list the last ALI file here:
2710 @smallexample
2711 gnatlink unit2.ali main.o -o exec_file
2712 @end smallexample
2713
2714 This procedure yields a binary executable called @file{exec_file}.
2715 @end enumerate
2716
2717 @noindent
2718 Depending on the circumstances (for example when your non-Ada main object
2719 does not provide symbol @code{main}), you may also need to instruct the
2720 GNAT linker not to include the standard startup objects by passing the
2721 @option{^-nostartfiles^/NOSTART_FILES^} switch to @command{gnatlink}.
2722
2723 @node Calling Conventions
2724 @subsection Calling Conventions
2725 @cindex Foreign Languages
2726 @cindex Calling Conventions
2727 GNAT follows standard calling sequence conventions and will thus interface
2728 to any other language that also follows these conventions. The following
2729 Convention identifiers are recognized by GNAT:
2730
2731 @table @code
2732 @cindex Interfacing to Ada
2733 @cindex Other Ada compilers
2734 @cindex Convention Ada
2735 @item Ada
2736 This indicates that the standard Ada calling sequence will be
2737 used and all Ada data items may be passed without any limitations in the
2738 case where GNAT is used to generate both the caller and callee. It is also
2739 possible to mix GNAT generated code and code generated by another Ada
2740 compiler. In this case, the data types should be restricted to simple
2741 cases, including primitive types. Whether complex data types can be passed
2742 depends on the situation. Probably it is safe to pass simple arrays, such
2743 as arrays of integers or floats. Records may or may not work, depending
2744 on whether both compilers lay them out identically. Complex structures
2745 involving variant records, access parameters, tasks, or protected types,
2746 are unlikely to be able to be passed.
2747
2748 Note that in the case of GNAT running
2749 on a platform that supports HP Ada 83, a higher degree of compatibility
2750 can be guaranteed, and in particular records are layed out in an identical
2751 manner in the two compilers. Note also that if output from two different
2752 compilers is mixed, the program is responsible for dealing with elaboration
2753 issues. Probably the safest approach is to write the main program in the
2754 version of Ada other than GNAT, so that it takes care of its own elaboration
2755 requirements, and then call the GNAT-generated adainit procedure to ensure
2756 elaboration of the GNAT components. Consult the documentation of the other
2757 Ada compiler for further details on elaboration.
2758
2759 However, it is not possible to mix the tasking run time of GNAT and
2760 HP Ada 83, All the tasking operations must either be entirely within
2761 GNAT compiled sections of the program, or entirely within HP Ada 83
2762 compiled sections of the program.
2763
2764 @cindex Interfacing to Assembly
2765 @cindex Convention Assembler
2766 @item Assembler
2767 Specifies assembler as the convention. In practice this has the
2768 same effect as convention Ada (but is not equivalent in the sense of being
2769 considered the same convention).
2770
2771 @cindex Convention Asm
2772 @findex Asm
2773 @item Asm
2774 Equivalent to Assembler.
2775
2776 @cindex Interfacing to COBOL
2777 @cindex Convention COBOL
2778 @findex COBOL
2779 @item COBOL
2780 Data will be passed according to the conventions described
2781 in section B.4 of the Ada Reference Manual.
2782
2783 @findex C
2784 @cindex Interfacing to C
2785 @cindex Convention C
2786 @item C
2787 Data will be passed according to the conventions described
2788 in section B.3 of the Ada Reference Manual.
2789
2790 A note on interfacing to a C ``varargs'' function:
2791 @findex C varargs function
2792 @cindex Interfacing to C varargs function
2793 @cindex varargs function interfaces
2794
2795 @itemize @bullet
2796 @item
2797 In C, @code{varargs} allows a function to take a variable number of
2798 arguments. There is no direct equivalent in this to Ada. One
2799 approach that can be used is to create a C wrapper for each
2800 different profile and then interface to this C wrapper. For
2801 example, to print an @code{int} value using @code{printf},
2802 create a C function @code{printfi} that takes two arguments, a
2803 pointer to a string and an int, and calls @code{printf}.
2804 Then in the Ada program, use pragma @code{Import} to
2805 interface to @code{printfi}.
2806
2807 @item
2808 It may work on some platforms to directly interface to
2809 a @code{varargs} function by providing a specific Ada profile
2810 for a particular call. However, this does not work on
2811 all platforms, since there is no guarantee that the
2812 calling sequence for a two argument normal C function
2813 is the same as for calling a @code{varargs} C function with
2814 the same two arguments.
2815 @end itemize
2816
2817 @cindex Convention Default
2818 @findex Default
2819 @item Default
2820 Equivalent to C.
2821
2822 @cindex Convention External
2823 @findex External
2824 @item External
2825 Equivalent to C.
2826
2827 @ifclear vms
2828 @findex C++
2829 @cindex Interfacing to C++
2830 @cindex Convention C++
2831 @item C_Plus_Plus (or CPP)
2832 This stands for C++. For most purposes this is identical to C.
2833 See the separate description of the specialized GNAT pragmas relating to
2834 C++ interfacing for further details.
2835 @end ifclear
2836
2837 @findex Fortran
2838 @cindex Interfacing to Fortran
2839 @cindex Convention Fortran
2840 @item Fortran
2841 Data will be passed according to the conventions described
2842 in section B.5 of the Ada Reference Manual.
2843
2844 @item Intrinsic
2845 This applies to an intrinsic operation, as defined in the Ada
2846 Reference Manual. If a pragma Import (Intrinsic) applies to a subprogram,
2847 this means that the body of the subprogram is provided by the compiler itself,
2848 usually by means of an efficient code sequence, and that the user does not
2849 supply an explicit body for it. In an application program, the pragma may
2850 be applied to the following sets of names:
2851
2852 @itemize @bullet
2853 @item
2854 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right,
2855 Shift_Right_Arithmetic.  The corresponding subprogram declaration must have
2856 two formal parameters. The
2857 first one must be a signed integer type or a modular type with a binary
2858 modulus, and the second parameter must be of type Natural.
2859 The return type must be the same as the type of the first argument. The size
2860 of this type can only be 8, 16, 32, or 64.
2861
2862 @item
2863 Binary arithmetic operators: ``+'', ``-'', ``*'', ``/''
2864 The corresponding operator declaration must have parameters and result type
2865 that have the same root numeric type (for example, all three are long_float
2866 types). This simplifies the definition of operations that use type checking
2867 to perform dimensional checks:
2868
2869 @smallexample @c ada
2870 type Distance is new Long_Float;
2871 type Time     is new Long_Float;
2872 type Velocity is new Long_Float;
2873 function "/" (D : Distance; T : Time)
2874   return Velocity;
2875 pragma Import (Intrinsic, "/");
2876 @end smallexample
2877
2878 @noindent
2879 This common idiom is often programmed with a generic definition and an
2880 explicit body. The pragma makes it simpler to introduce such declarations.
2881 It incurs no overhead in compilation time or code size, because it is
2882 implemented as a single machine instruction.
2883
2884 @item
2885 General subprogram entities, to bind an Ada subprogram declaration to
2886 a compiler builtin by name with back-ends where such interfaces are
2887 available. A typical example is the set of ``__builtin'' functions
2888 exposed by the GCC back-end, as in the following example:
2889
2890 @smallexample @c ada
2891    function builtin_sqrt (F : Float) return Float;
2892    pragma Import (Intrinsic, builtin_sqrt, "__builtin_sqrtf");
2893 @end smallexample
2894
2895 Most of the GCC builtins are accessible this way, and as for other
2896 import conventions (e.g. C), it is the user's responsibility to ensure
2897 that the Ada subprogram profile matches the underlying builtin
2898 expectations.
2899 @end itemize
2900
2901 @noindent
2902
2903 @ifset unw
2904 @findex Stdcall
2905 @cindex Convention Stdcall
2906 @item Stdcall
2907 This is relevant only to Windows XP/2000/NT implementations of GNAT,
2908 and specifies that the @code{Stdcall} calling sequence will be used,
2909 as defined by the NT API. Nevertheless, to ease building
2910 cross-platform bindings this convention will be handled as a @code{C} calling
2911 convention on non-Windows platforms.
2912
2913 @findex DLL
2914 @cindex Convention DLL
2915 @item DLL
2916 This is equivalent to @code{Stdcall}.
2917
2918 @findex Win32
2919 @cindex Convention Win32
2920 @item Win32
2921 This is equivalent to @code{Stdcall}.
2922 @end ifset
2923
2924 @findex Stubbed
2925 @cindex Convention Stubbed
2926 @item Stubbed
2927 This is a special convention that indicates that the compiler
2928 should provide a stub body that raises @code{Program_Error}.
2929 @end table
2930
2931 @noindent
2932 GNAT additionally provides a useful pragma @code{Convention_Identifier}
2933 that can be used to parameterize conventions and allow additional synonyms
2934 to be specified. For example if you have legacy code in which the convention
2935 identifier Fortran77 was used for Fortran, you can use the configuration
2936 pragma:
2937
2938 @smallexample @c ada
2939 pragma Convention_Identifier (Fortran77, Fortran);
2940 @end smallexample
2941
2942 @noindent
2943 And from now on the identifier Fortran77 may be used as a convention
2944 identifier (for example in an @code{Import} pragma) with the same
2945 meaning as Fortran.
2946
2947 @ifclear vms
2948 @node Building Mixed Ada & C++ Programs
2949 @section Building Mixed Ada and C++ Programs
2950
2951 @noindent
2952 A programmer inexperienced with mixed-language development may find that
2953 building an application containing both Ada and C++ code can be a
2954 challenge.  This section gives a few
2955 hints that should make this task easier. The first section addresses
2956 the differences between interfacing with C and interfacing with C++.
2957 The second section
2958 looks into the delicate problem of linking the complete application from
2959 its Ada and C++ parts. The last section gives some hints on how the GNAT
2960 run-time library can be adapted in order to allow inter-language dispatching
2961 with a new C++ compiler.
2962
2963 @menu
2964 * Interfacing to C++::
2965 * Linking a Mixed C++ & Ada Program::
2966 * A Simple Example::
2967 * Interfacing with C++ constructors::
2968 * Interfacing with C++ at the Class Level::
2969 @end menu
2970
2971 @node Interfacing to C++
2972 @subsection Interfacing to C++
2973
2974 @noindent
2975 GNAT supports interfacing with the G++ compiler (or any C++ compiler
2976 generating code that is compatible with the G++ Application Binary
2977 Interface ---see http://www.codesourcery.com/archives/cxx-abi).
2978
2979 @noindent
2980 Interfacing can be done at 3 levels: simple data, subprograms, and
2981 classes. In the first two cases, GNAT offers a specific @code{Convention
2982 C_Plus_Plus} (or @code{CPP}) that behaves exactly like @code{Convention C}.
2983 Usually, C++ mangles the names of subprograms. To generate proper mangled
2984 names automatically, see @ref{Generating Ada Bindings for C and C++ headers}).
2985 This problem can also be addressed manually in two ways:
2986
2987 @itemize @bullet
2988 @item
2989 by modifying the C++ code in order to force a C convention using
2990 the @code{extern "C"} syntax.
2991
2992 @item
2993 by figuring out the mangled name (using e.g. @command{nm}) and using it as the
2994 Link_Name argument of the pragma import.
2995 @end itemize
2996
2997 @noindent
2998 Interfacing at the class level can be achieved by using the GNAT specific
2999 pragmas such as @code{CPP_Constructor}.  @xref{Interfacing to C++,,,
3000 gnat_rm, GNAT Reference Manual}, for additional information.
3001
3002 @node Linking a Mixed C++ & Ada Program
3003 @subsection Linking a Mixed C++ & Ada Program
3004
3005 @noindent
3006 Usually the linker of the C++ development system must be used to link
3007 mixed applications because most C++ systems will resolve elaboration
3008 issues (such as calling constructors on global class instances)
3009 transparently during the link phase. GNAT has been adapted to ease the
3010 use of a foreign linker for the last phase. Three cases can be
3011 considered:
3012 @enumerate
3013
3014 @item
3015 Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
3016 The C++ linker can simply be called by using the C++ specific driver
3017 called @code{g++}.
3018
3019 Note that if the C++ code uses inline functions, you will need to
3020 compile your C++ code with the @code{-fkeep-inline-functions} switch in
3021 order to provide an existing function implementation that the Ada code can
3022 link with.
3023
3024 @smallexample
3025 $ g++ -c -fkeep-inline-functions file1.C
3026 $ g++ -c -fkeep-inline-functions file2.C
3027 $ gnatmake ada_unit -largs file1.o file2.o --LINK=g++
3028 @end smallexample
3029
3030 @item
3031 Using GNAT and G++ from two different GCC installations: If both
3032 compilers are on the @env{PATH}, the previous method may be used. It is
3033 important to note that environment variables such as
3034 @env{C_INCLUDE_PATH}, @env{GCC_EXEC_PREFIX}, @env{BINUTILS_ROOT}, and
3035 @env{GCC_ROOT} will affect both compilers
3036 at the same time and may make one of the two compilers operate
3037 improperly if set during invocation of the wrong compiler.  It is also
3038 very important that the linker uses the proper @file{libgcc.a} GCC
3039 library -- that is, the one from the C++ compiler installation. The
3040 implicit link command as suggested in the @command{gnatmake} command
3041 from the former example can be replaced by an explicit link command with
3042 the full-verbosity option in order to verify which library is used:
3043 @smallexample
3044 $ gnatbind ada_unit
3045 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
3046 @end smallexample
3047 If there is a problem due to interfering environment variables, it can
3048 be worked around by using an intermediate script. The following example
3049 shows the proper script to use when GNAT has not been installed at its
3050 default location and g++ has been installed at its default location:
3051
3052 @smallexample
3053 $ cat ./my_script
3054 #!/bin/sh
3055 unset BINUTILS_ROOT
3056 unset GCC_ROOT
3057 c++ $*
3058 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
3059 @end smallexample
3060
3061 @item
3062 Using a non-GNU C++ compiler: The commands previously described can be
3063 used to insure that the C++ linker is used. Nonetheless, you need to add
3064 a few more parameters to the link command line, depending on the exception
3065 mechanism used.
3066
3067 If the @code{setjmp/longjmp} exception mechanism is used, only the paths
3068 to the libgcc libraries are required:
3069
3070 @smallexample
3071 $ cat ./my_script
3072 #!/bin/sh
3073 CC $* `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a`
3074 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3075 @end smallexample
3076
3077 Where CC is the name of the non-GNU C++ compiler.
3078
3079 If the @code{zero cost} exception mechanism is used, and the platform
3080 supports automatic registration of exception tables (e.g.@: Solaris or IRIX),
3081 paths to more objects are required:
3082
3083 @smallexample
3084 $ cat ./my_script
3085 #!/bin/sh
3086 CC `gcc -print-file-name=crtbegin.o` $* \
3087 `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a` \
3088 `gcc -print-file-name=crtend.o`
3089 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3090 @end smallexample
3091
3092 If the @code{zero cost} exception mechanism is used, and the platform
3093 doesn't support automatic registration of exception tables (e.g.@: HP-UX,
3094 Tru64 or AIX), the simple approach described above will not work and
3095 a pre-linking phase using GNAT will be necessary.
3096
3097 @end enumerate
3098
3099 Another alternative is to use the @command{gprbuild} multi-language builder
3100 which has a large knowledge base and knows how to link Ada and C++ code
3101 together automatically in most cases.
3102
3103 @node A Simple Example
3104 @subsection  A Simple Example
3105 @noindent
3106 The following example, provided as part of the GNAT examples, shows how
3107 to achieve procedural interfacing between Ada and C++ in both
3108 directions. The C++ class A has two methods. The first method is exported
3109 to Ada by the means of an extern C wrapper function. The second method
3110 calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
3111 a limited record with a layout comparable to the C++ class. The Ada
3112 subprogram, in turn, calls the C++ method. So, starting from the C++
3113 main program, the process passes back and forth between the two
3114 languages.
3115
3116 @noindent
3117 Here are the compilation commands:
3118 @smallexample
3119 $ gnatmake -c simple_cpp_interface
3120 $ g++ -c cpp_main.C
3121 $ g++ -c ex7.C
3122 $ gnatbind -n simple_cpp_interface
3123 $ gnatlink simple_cpp_interface -o cpp_main --LINK=g++
3124       -lstdc++ ex7.o cpp_main.o
3125 @end smallexample
3126
3127 @noindent
3128 Here are the corresponding sources:
3129 @smallexample
3130
3131 //cpp_main.C
3132
3133 #include "ex7.h"
3134
3135 extern "C" @{
3136   void adainit (void);
3137   void adafinal (void);
3138   void method1 (A *t);
3139 @}
3140
3141 void method1 (A *t)
3142 @{
3143   t->method1 ();
3144 @}
3145
3146 int main ()
3147 @{
3148   A obj;
3149   adainit ();
3150   obj.method2 (3030);
3151   adafinal ();
3152 @}
3153
3154 //ex7.h
3155
3156 class Origin @{
3157  public:
3158   int o_value;
3159 @};
3160 class A : public Origin @{
3161  public:
3162   void method1 (void);
3163   void method2 (int v);
3164   A();
3165   int   a_value;
3166 @};
3167
3168 //ex7.C
3169
3170 #include "ex7.h"
3171 #include <stdio.h>
3172
3173 extern "C" @{ void ada_method2 (A *t, int v);@}
3174
3175 void A::method1 (void)
3176 @{
3177   a_value = 2020;
3178   printf ("in A::method1, a_value = %d \n",a_value);
3179
3180 @}
3181
3182 void A::method2 (int v)
3183 @{
3184    ada_method2 (this, v);
3185    printf ("in A::method2, a_value = %d \n",a_value);
3186
3187 @}
3188
3189 A::A(void)
3190 @{
3191    a_value = 1010;
3192   printf ("in A::A, a_value = %d \n",a_value);
3193 @}
3194 @end smallexample
3195
3196 @smallexample @c ada
3197 -- Ada sources
3198 package body Simple_Cpp_Interface is
3199
3200    procedure Ada_Method2 (This : in out A; V : Integer) is
3201    begin
3202       Method1 (This);
3203       This.A_Value := V;
3204    end Ada_Method2;
3205
3206 end Simple_Cpp_Interface;
3207
3208 with System;
3209 package Simple_Cpp_Interface is
3210    type A is limited
3211       record
3212          Vptr    : System.Address;
3213          O_Value : Integer;
3214          A_Value : Integer;
3215       end record;
3216    pragma Convention (C, A);
3217
3218    procedure Method1 (This : in out A);
3219    pragma Import (C, Method1);
3220
3221    procedure Ada_Method2 (This : in out A; V : Integer);
3222    pragma Export (C, Ada_Method2);
3223
3224 end Simple_Cpp_Interface;
3225 @end smallexample
3226
3227 @node Interfacing with C++ constructors
3228 @subsection Interfacing with C++ constructors
3229 @noindent
3230
3231 In order to interface with C++ constructors GNAT provides the
3232 @code{pragma CPP_Constructor} (@xref{Interfacing to C++,,,
3233 gnat_rm, GNAT Reference Manual}, for additional information).
3234 In this section we present some common uses of C++ constructors
3235 in mixed-languages programs in GNAT.
3236
3237 Let us assume that we need to interface with the following
3238 C++ class:
3239
3240 @smallexample
3241 @b{class} Root @{
3242 @b{public}:
3243   int  a_value;
3244   int  b_value;
3245   @b{virtual} int Get_Value ();
3246   Root();              // Default constructor
3247   Root(int v);         // 1st non-default constructor
3248   Root(int v, int w);  // 2nd non-default constructor
3249 @};
3250 @end smallexample
3251
3252 For this purpose we can write the following package spec (further
3253 information on how to build this spec is available in
3254 @ref{Interfacing with C++ at the Class Level} and
3255 @ref{Generating Ada Bindings for C and C++ headers}).
3256
3257 @smallexample @c ada
3258 with Interfaces.C; use Interfaces.C;
3259 package Pkg_Root is
3260   type Root is tagged limited record
3261      A_Value : int;
3262      B_Value : int;
3263   end record;
3264   pragma Import (CPP, Root);
3265
3266   function Get_Value (Obj : Root) return int;
3267   pragma Import (CPP, Get_Value);
3268
3269   function Constructor return Root;
3270   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ev");
3271
3272   function Constructor (v : Integer) return Root;
3273   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ei");
3274
3275   function Constructor (v, w : Integer) return Root;
3276   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Eii");
3277 end Pkg_Root;
3278 @end smallexample
3279
3280 On the Ada side the constructor is represented by a function (whose
3281 name is arbitrary) that returns the classwide type corresponding to
3282 the imported C++ class. Although the constructor is described as a
3283 function, it is typically a procedure with an extra implicit argument
3284 (the object being initialized) at the implementation level. GNAT
3285 issues the appropriate call, whatever it is, to get the object
3286 properly initialized.
3287
3288 Constructors can only appear in the following contexts:
3289
3290 @itemize @bullet
3291 @item
3292 On the right side of an initialization of an object of type @var{T}.
3293 @item
3294 On the right side of an initialization of a record component of type @var{T}.
3295 @item
3296 In an Ada 2005 limited aggregate.
3297 @item
3298 In an Ada 2005 nested limited aggregate.
3299 @item
3300 In an Ada 2005 limited aggregate that initializes an object built in
3301 place by an extended return statement.
3302 @end itemize
3303
3304 @noindent
3305 In a declaration of an object whose type is a class imported from C++,
3306 either the default C++ constructor is implicitly called by GNAT, or
3307 else the required C++ constructor must be explicitly called in the
3308 expression that initializes the object. For example:
3309
3310 @smallexample @c ada
3311   Obj1 : Root;
3312   Obj2 : Root := Constructor;
3313   Obj3 : Root := Constructor (v => 10);
3314   Obj4 : Root := Constructor (30, 40);
3315 @end smallexample
3316
3317 The first two declarations are equivalent: in both cases the default C++
3318 constructor is invoked (in the former case the call to the constructor is
3319 implicit, and in the latter case the call is explicit in the object
3320 declaration). @code{Obj3} is initialized by the C++ non-default constructor
3321 that takes an integer argument, and @code{Obj4} is initialized by the
3322 non-default C++ constructor that takes two integers.
3323
3324 Let us derive the imported C++ class in the Ada side. For example:
3325
3326 @smallexample @c ada
3327   type DT is new Root with record
3328      C_Value : Natural := 2009;
3329   end record;
3330 @end smallexample
3331
3332 In this case the components DT inherited from the C++ side must be
3333 initialized by a C++ constructor, and the additional Ada components
3334 of type DT are initialized by GNAT. The initialization of such an
3335 object is done either by default, or by means of a function returning
3336 an aggregate of type DT, or by means of an extension aggregate.
3337
3338 @smallexample @c ada
3339   Obj5 : DT;
3340   Obj6 : DT := Function_Returning_DT (50);
3341   Obj7 : DT := (Constructor (30,40) with C_Value => 50);
3342 @end smallexample
3343
3344 The declaration of @code{Obj5} invokes the default constructors: the
3345 C++ default constructor of the parent type takes care of the initialization
3346 of the components inherited from Root, and GNAT takes care of the default
3347 initialization of the additional Ada components of type DT (that is,
3348 @code{C_Value} is initialized to value 2009). The order of invocation of
3349 the constructors is consistent with the order of elaboration required by
3350 Ada and C++. That is, the constructor of the parent type is always called
3351 before the constructor of the derived type.
3352
3353 Let us now consider a record that has components whose type is imported
3354 from C++. For example:
3355
3356 @smallexample @c ada
3357   type Rec1 is limited record
3358      Data1 : Root := Constructor (10);
3359      Value : Natural := 1000;
3360   end record;
3361
3362   type Rec2 (D : Integer := 20) is limited record
3363      Rec   : Rec1;
3364      Data2 : Root := Constructor (D, 30);
3365   end record;
3366 @end smallexample
3367
3368 The initialization of an object of type @code{Rec2} will call the
3369 non-default C++ constructors specified for the imported components.
3370 For example:
3371
3372 @smallexample @c ada
3373   Obj8 : Rec2 (40);
3374 @end smallexample
3375
3376 Using Ada 2005 we can use limited aggregates to initialize an object
3377 invoking C++ constructors that differ from those specified in the type
3378 declarations. For example:
3379
3380 @smallexample @c ada
3381   Obj9 : Rec2 := (Rec => (Data1 => Constructor (15, 16),
3382                           others => <>),
3383                   others => <>);
3384 @end smallexample
3385
3386 The above declaration uses an Ada 2005 limited aggregate to
3387 initialize @code{Obj9}, and the C++ constructor that has two integer
3388 arguments is invoked to initialize the @code{Data1} component instead
3389 of the constructor specified in the declaration of type @code{Rec1}. In
3390 Ada 2005 the box in the aggregate indicates that unspecified components
3391 are initialized using the expression (if any) available in the component
3392 declaration. That is, in this case discriminant @code{D} is initialized
3393 to value @code{20}, @code{Value} is initialized to value 1000, and the
3394 non-default C++ constructor that handles two integers takes care of
3395 initializing component @code{Data2} with values @code{20,30}.
3396
3397 In Ada 2005 we can use the extended return statement to build the Ada
3398 equivalent to C++ non-default constructors. For example:
3399
3400 @smallexample @c ada
3401   function Constructor (V : Integer) return Rec2 is
3402   begin
3403      return Obj : Rec2 := (Rec => (Data1  => Constructor (V, 20),
3404                                    others => <>),
3405                            others => <>) do
3406         --  Further actions required for construction of
3407         --  objects of type Rec2
3408         ...
3409      end record;
3410   end Constructor;
3411 @end smallexample
3412
3413 In this example the extended return statement construct is used to
3414 build in place the returned object whose components are initialized
3415 by means of a limited aggregate. Any further action associated with
3416 the constructor can be placed inside the construct.
3417
3418 @node Interfacing with C++ at the Class Level
3419 @subsection Interfacing with C++ at the Class Level
3420 @noindent
3421 In this section we demonstrate the GNAT features for interfacing with
3422 C++ by means of an example making use of Ada 2005 abstract interface
3423 types. This example consists of a classification of animals; classes
3424 have been used to model our main classification of animals, and
3425 interfaces provide support for the management of secondary
3426 classifications. We first demonstrate a case in which the types and
3427 constructors are defined on the C++ side and imported from the Ada
3428 side, and latter the reverse case.
3429
3430 The root of our derivation will be the @code{Animal} class, with a
3431 single private attribute (the @code{Age} of the animal) and two public
3432 primitives to set and get the value of this attribute.
3433
3434 @smallexample
3435 @b{class} Animal @{
3436  @b{public}:
3437    @b{virtual} void Set_Age (int New_Age);
3438    @b{virtual} int Age ();
3439  @b{private}:
3440    int Age_Count;
3441 @};
3442 @end smallexample
3443
3444 Abstract interface types are defined in C++ by means of classes with pure
3445 virtual functions and no data members. In our example we will use two
3446 interfaces that provide support for the common management of @code{Carnivore}
3447 and @code{Domestic} animals:
3448
3449 @smallexample
3450 @b{class} Carnivore @{
3451 @b{public}:
3452    @b{virtual} int Number_Of_Teeth () = 0;
3453 @};
3454
3455 @b{class} Domestic @{
3456 @b{public}:
3457    @b{virtual void} Set_Owner (char* Name) = 0;
3458 @};
3459 @end smallexample
3460
3461 Using these declarations, we can now say that a @code{Dog} is an animal that is
3462 both Carnivore and Domestic, that is:
3463
3464 @smallexample
3465 @b{class} Dog : Animal, Carnivore, Domestic @{
3466  @b{public}:
3467    @b{virtual} int  Number_Of_Teeth ();
3468    @b{virtual} void Set_Owner (char* Name);
3469
3470    Dog(); // Constructor
3471  @b{private}:
3472    int  Tooth_Count;
3473    char *Owner;
3474 @};
3475 @end smallexample
3476
3477 In the following examples we will assume that the previous declarations are
3478 located in a file named @code{animals.h}. The following package demonstrates
3479 how to import these C++ declarations from the Ada side:
3480
3481 @smallexample @c ada
3482 with Interfaces.C.Strings; use Interfaces.C.Strings;
3483 package Animals is
3484   type Carnivore is interface;
3485   pragma Convention (C_Plus_Plus, Carnivore);
3486   function Number_Of_Teeth (X : Carnivore)
3487      return Natural is abstract;
3488
3489   type Domestic is interface;
3490   pragma Convention (C_Plus_Plus, Set_Owner);
3491   procedure Set_Owner
3492     (X    : in out Domestic;
3493      Name : Chars_Ptr) is abstract;
3494
3495   type Animal is tagged record
3496     Age : Natural := 0;
3497   end record;
3498   pragma Import (C_Plus_Plus, Animal);
3499
3500   procedure Set_Age (X : in out Animal; Age : Integer);
3501   pragma Import (C_Plus_Plus, Set_Age);
3502
3503   function Age (X : Animal) return Integer;
3504   pragma Import (C_Plus_Plus, Age);
3505
3506   type Dog is new Animal and Carnivore and Domestic with record
3507     Tooth_Count : Natural;
3508     Owner       : String (1 .. 30);
3509   end record;
3510   pragma Import (C_Plus_Plus, Dog);
3511
3512   function Number_Of_Teeth (A : Dog) return Integer;
3513   pragma Import (C_Plus_Plus, Number_Of_Teeth);
3514
3515   procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3516   pragma Import (C_Plus_Plus, Set_Owner);
3517
3518   function New_Dog return Dog;
3519   pragma CPP_Constructor (New_Dog);
3520   pragma Import (CPP, New_Dog, "_ZN3DogC2Ev");
3521 end Animals;
3522 @end smallexample
3523
3524 Thanks to the compatibility between GNAT run-time structures and the C++ ABI,
3525 interfacing with these C++ classes is easy. The only requirement is that all
3526 the primitives and components must be declared exactly in the same order in
3527 the two languages.
3528
3529 Regarding the abstract interfaces, we must indicate to the GNAT compiler by
3530 means of a @code{pragma Convention (C_Plus_Plus)}, the convention used to pass
3531 the arguments to the called primitives will be the same as for C++. For the
3532 imported classes we use @code{pragma Import} with convention @code{C_Plus_Plus}
3533 to indicate that they have been defined on the C++ side; this is required
3534 because the dispatch table associated with these tagged types will be built
3535 in the C++ side and therefore will not contain the predefined Ada primitives
3536 which Ada would otherwise expect.
3537
3538 As the reader can see there is no need to indicate the C++ mangled names
3539 associated with each subprogram because it is assumed that all the calls to
3540 these primitives will be dispatching calls. The only exception is the
3541 constructor, which must be registered with the compiler by means of
3542 @code{pragma CPP_Constructor} and needs to provide its associated C++
3543 mangled name because the Ada compiler generates direct calls to it.
3544
3545 With the above packages we can now declare objects of type Dog on the Ada side
3546 and dispatch calls to the corresponding subprograms on the C++ side. We can
3547 also extend the tagged type Dog with further fields and primitives, and
3548 override some of its C++ primitives on the Ada side. For example, here we have
3549 a type derivation defined on the Ada side that inherits all the dispatching
3550 primitives of the ancestor from the C++ side.
3551
3552 @smallexample
3553 @b{with} Animals; @b{use} Animals;
3554 @b{package} Vaccinated_Animals @b{is}
3555   @b{type} Vaccinated_Dog @b{is new} Dog @b{with null record};
3556   @b{function} Vaccination_Expired (A : Vaccinated_Dog) @b{return} Boolean;
3557 @b{end} Vaccinated_Animals;
3558 @end smallexample
3559
3560 It is important to note that, because of the ABI compatibility, the programmer
3561 does not need to add any further information to indicate either the object
3562 layout or the dispatch table entry associated with each dispatching operation.
3563
3564 Now let us define all the types and constructors on the Ada side and export
3565 them to C++, using the same hierarchy of our previous example:
3566
3567 @smallexample @c ada
3568 with Interfaces.C.Strings;
3569 use Interfaces.C.Strings;
3570 package Animals is
3571   type Carnivore is interface;
3572   pragma Convention (C_Plus_Plus, Carnivore);
3573   function Number_Of_Teeth (X : Carnivore)
3574      return Natural is abstract;
3575
3576   type Domestic is interface;
3577   pragma Convention (C_Plus_Plus, Set_Owner);
3578   procedure Set_Owner
3579     (X    : in out Domestic;
3580      Name : Chars_Ptr) is abstract;
3581
3582   type Animal is tagged record
3583     Age : Natural := 0;
3584   end record;
3585   pragma Convention (C_Plus_Plus, Animal);
3586
3587   procedure Set_Age (X : in out Animal; Age : Integer);
3588   pragma Export (C_Plus_Plus, Set_Age);
3589
3590   function Age (X : Animal) return Integer;
3591   pragma Export (C_Plus_Plus, Age);
3592
3593   type Dog is new Animal and Carnivore and Domestic with record
3594     Tooth_Count : Natural;
3595     Owner       : String (1 .. 30);
3596   end record;
3597   pragma Convention (C_Plus_Plus, Dog);
3598
3599   function Number_Of_Teeth (A : Dog) return Integer;
3600   pragma Export (C_Plus_Plus, Number_Of_Teeth);
3601
3602   procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3603   pragma Export (C_Plus_Plus, Set_Owner);
3604
3605   function New_Dog return Dog'Class;
3606   pragma Export (C_Plus_Plus, New_Dog);
3607 end Animals;
3608 @end smallexample
3609
3610 Compared with our previous example the only difference is the use of
3611 @code{pragma Export} to indicate to the GNAT compiler that the primitives will
3612 be available to C++. Thanks to the ABI compatibility, on the C++ side there is
3613 nothing else to be done; as explained above, the only requirement is that all
3614 the primitives and components are declared in exactly the same order.
3615
3616 For completeness, let us see a brief C++ main program that uses the
3617 declarations available in @code{animals.h} (presented in our first example) to
3618 import and use the declarations from the Ada side, properly initializing and
3619 finalizing the Ada run-time system along the way:
3620
3621 @smallexample
3622 @b{#include} "animals.h"
3623 @b{#include} <iostream>
3624 @b{using namespace} std;
3625
3626 void Check_Carnivore (Carnivore *obj) @{@dots{}@}
3627 void Check_Domestic (Domestic *obj)   @{@dots{}@}
3628 void Check_Animal (Animal *obj)       @{@dots{}@}
3629 void Check_Dog (Dog *obj)             @{@dots{}@}
3630
3631 @b{extern} "C" @{
3632   void adainit (void);
3633   void adafinal (void);
3634   Dog* new_dog ();
3635 @}
3636
3637 void test ()
3638 @{
3639   Dog *obj = new_dog();  // Ada constructor
3640   Check_Carnivore (obj); // Check secondary DT
3641   Check_Domestic (obj);  // Check secondary DT
3642   Check_Animal (obj);    // Check primary DT
3643   Check_Dog (obj);       // Check primary DT
3644 @}
3645
3646 int main ()
3647 @{
3648   adainit ();  test();  adafinal ();
3649   return 0;
3650 @}
3651 @end smallexample
3652
3653 @node Comparison between GNAT and C/C++ Compilation Models
3654 @section Comparison between GNAT and C/C++ Compilation Models
3655
3656 @noindent
3657 The GNAT model of compilation is close to the C and C++ models. You can
3658 think of Ada specs as corresponding to header files in C. As in C, you
3659 don't need to compile specs; they are compiled when they are used. The
3660 Ada @code{with} is similar in effect to the @code{#include} of a C
3661 header.
3662
3663 One notable difference is that, in Ada, you may compile specs separately
3664 to check them for semantic and syntactic accuracy. This is not always
3665 possible with C headers because they are fragments of programs that have
3666 less specific syntactic or semantic rules.
3667
3668 The other major difference is the requirement for running the binder,
3669 which performs two important functions. First, it checks for
3670 consistency. In C or C++, the only defense against assembling
3671 inconsistent programs lies outside the compiler, in a makefile, for
3672 example. The binder satisfies the Ada requirement that it be impossible
3673 to construct an inconsistent program when the compiler is used in normal
3674 mode.
3675
3676 @cindex Elaboration order control
3677 The other important function of the binder is to deal with elaboration
3678 issues. There are also elaboration issues in C++ that are handled
3679 automatically. This automatic handling has the advantage of being
3680 simpler to use, but the C++ programmer has no control over elaboration.
3681 Where @code{gnatbind} might complain there was no valid order of
3682 elaboration, a C++ compiler would simply construct a program that
3683 malfunctioned at run time.
3684 @end ifclear
3685
3686 @node Comparison between GNAT and Conventional Ada Library Models
3687 @section Comparison between GNAT and Conventional Ada Library Models
3688
3689 @noindent
3690 This section is intended for Ada programmers who have
3691 used an Ada compiler implementing the traditional Ada library
3692 model, as described in the Ada Reference Manual.
3693
3694 @cindex GNAT library
3695 In GNAT, there is no ``library'' in the normal sense. Instead, the set of
3696 source files themselves acts as the library. Compiling Ada programs does
3697 not generate any centralized information, but rather an object file and
3698 a ALI file, which are of interest only to the binder and linker.
3699 In a traditional system, the compiler reads information not only from
3700 the source file being compiled, but also from the centralized library.
3701 This means that the effect of a compilation depends on what has been
3702 previously compiled. In particular:
3703
3704 @itemize @bullet
3705 @item
3706 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3707 to the version of the unit most recently compiled into the library.
3708
3709 @item
3710 Inlining is effective only if the necessary body has already been
3711 compiled into the library.
3712
3713 @item
3714 Compiling a unit may obsolete other units in the library.
3715 @end itemize
3716
3717 @noindent
3718 In GNAT, compiling one unit never affects the compilation of any other
3719 units because the compiler reads only source files. Only changes to source
3720 files can affect the results of a compilation. In particular:
3721
3722 @itemize @bullet
3723 @item
3724 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3725 to the source version of the unit that is currently accessible to the
3726 compiler.
3727
3728 @item
3729 @cindex Inlining
3730 Inlining requires the appropriate source files for the package or
3731 subprogram bodies to be available to the compiler. Inlining is always
3732 effective, independent of the order in which units are complied.
3733
3734 @item
3735 Compiling a unit never affects any other compilations. The editing of
3736 sources may cause previous compilations to be out of date if they
3737 depended on the source file being modified.
3738 @end itemize
3739
3740 @noindent
3741 The most important result of these differences is that order of compilation
3742 is never significant in GNAT. There is no situation in which one is
3743 required to do one compilation before another. What shows up as order of
3744 compilation requirements in the traditional Ada library becomes, in
3745 GNAT, simple source dependencies; in other words, there is only a set
3746 of rules saying what source files must be present when a file is
3747 compiled.
3748
3749 @ifset vms
3750 @node Placement of temporary files
3751 @section Placement of temporary files
3752 @cindex Temporary files (user control over placement)
3753
3754 @noindent
3755 GNAT creates temporary files in the directory designated by the environment
3756 variable @env{TMPDIR}.
3757 (See the HP @emph{C RTL Reference Manual} on the function @code{getenv()}
3758 for detailed information on how environment variables are resolved.
3759 For most users the easiest way to make use of this feature is to simply
3760 define @env{TMPDIR} as a job level logical name).
3761 For example, if you wish to use a Ramdisk (assuming DECRAM is installed)
3762 for compiler temporary files, then you can include something like the
3763 following command in your @file{LOGIN.COM} file:
3764
3765 @smallexample
3766 $ define/job TMPDIR "/disk$scratchram/000000/temp/"
3767 @end smallexample
3768
3769 @noindent
3770 If @env{TMPDIR} is not defined, then GNAT uses the directory designated by
3771 @env{TMP}; if @env{TMP} is not defined, then GNAT uses the directory
3772 designated by @env{TEMP}.
3773 If none of these environment variables are defined then GNAT uses the
3774 directory designated by the logical name @code{SYS$SCRATCH:}
3775 (by default the user's home directory). If all else fails
3776 GNAT uses the current directory for temporary files.
3777 @end ifset
3778
3779 @c *************************
3780 @node Compiling Using gcc
3781 @chapter Compiling Using @command{gcc}
3782
3783 @noindent
3784 This chapter discusses how to compile Ada programs using the @command{gcc}
3785 command. It also describes the set of switches
3786 that can be used to control the behavior of the compiler.
3787 @menu
3788 * Compiling Programs::
3789 * Switches for gcc::
3790 * Search Paths and the Run-Time Library (RTL)::
3791 * Order of Compilation Issues::
3792 * Examples::
3793 @end menu
3794
3795 @node Compiling Programs
3796 @section Compiling Programs
3797
3798 @noindent
3799 The first step in creating an executable program is to compile the units
3800 of the program using the @command{gcc} command. You must compile the
3801 following files:
3802
3803 @itemize @bullet
3804 @item
3805 the body file (@file{.adb}) for a library level subprogram or generic
3806 subprogram
3807
3808 @item
3809 the spec file (@file{.ads}) for a library level package or generic
3810 package that has no body
3811
3812 @item
3813 the body file (@file{.adb}) for a library level package
3814 or generic package that has a body
3815
3816 @end itemize
3817
3818 @noindent
3819 You need @emph{not} compile the following files
3820
3821 @itemize @bullet
3822
3823 @item
3824 the spec of a library unit which has a body
3825
3826 @item
3827 subunits
3828 @end itemize
3829
3830 @noindent
3831 because they are compiled as part of compiling related units. GNAT
3832 package specs
3833 when the corresponding body is compiled, and subunits when the parent is
3834 compiled.
3835
3836 @cindex cannot generate code
3837 If you attempt to compile any of these files, you will get one of the
3838 following error messages (where @var{fff} is the name of the file you
3839 compiled):
3840
3841 @smallexample
3842 cannot generate code for file @var{fff} (package spec)
3843 to check package spec, use -gnatc
3844
3845 cannot generate code for file @var{fff} (missing subunits)
3846 to check parent unit, use -gnatc
3847
3848 cannot generate code for file @var{fff} (subprogram spec)
3849 to check subprogram spec, use -gnatc
3850
3851 cannot generate code for file @var{fff} (subunit)
3852 to check subunit, use -gnatc
3853 @end smallexample
3854
3855 @noindent
3856 As indicated by the above error messages, if you want to submit
3857 one of these files to the compiler to check for correct semantics
3858 without generating code, then use the @option{-gnatc} switch.
3859
3860 The basic command for compiling a file containing an Ada unit is
3861
3862 @smallexample
3863 @c $ gcc -c @ovar{switches} @file{file name}
3864 @c Expanding @ovar macro inline (explanation in macro def comments)
3865 $ gcc -c @r{[}@var{switches}@r{]} @file{file name}
3866 @end smallexample
3867
3868 @noindent
3869 where @var{file name} is the name of the Ada file (usually
3870 having an extension
3871 @file{.ads} for a spec or @file{.adb} for a body).
3872 @ifclear vms
3873 You specify the
3874 @option{-c} switch to tell @command{gcc} to compile, but not link, the file.
3875 @end ifclear
3876 The result of a successful compilation is an object file, which has the
3877 same name as the source file but an extension of @file{.o} and an Ada
3878 Library Information (ALI) file, which also has the same name as the
3879 source file, but with @file{.ali} as the extension. GNAT creates these
3880 two output files in the current directory, but you may specify a source
3881 file in any directory using an absolute or relative path specification
3882 containing the directory information.
3883
3884 @findex gnat1
3885 @command{gcc} is actually a driver program that looks at the extensions of
3886 the file arguments and loads the appropriate compiler. For example, the
3887 GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}.
3888 These programs are in directories known to the driver program (in some
3889 configurations via environment variables you set), but need not be in
3890 your path. The @command{gcc} driver also calls the assembler and any other
3891 utilities needed to complete the generation of the required object
3892 files.
3893
3894 It is possible to supply several file names on the same @command{gcc}
3895 command. This causes @command{gcc} to call the appropriate compiler for
3896 each file. For example, the following command lists three separate
3897 files to be compiled:
3898
3899 @smallexample
3900 $ gcc -c x.adb y.adb z.c
3901 @end smallexample
3902
3903 @noindent
3904 calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and
3905 @file{y.adb}, and @code{cc1} (the C compiler) once to compile @file{z.c}.
3906 The compiler generates three object files @file{x.o}, @file{y.o} and
3907 @file{z.o} and the two ALI files @file{x.ali} and @file{y.ali} from the
3908 Ada compilations. Any switches apply to all the files ^listed,^listed.^
3909 @ifclear vms
3910 except for
3911 @option{-gnat@var{x}} switches, which apply only to Ada compilations.
3912 @end ifclear
3913
3914 @node Switches for gcc
3915 @section Switches for @command{gcc}
3916
3917 @noindent
3918 The @command{gcc} command accepts switches that control the
3919 compilation process. These switches are fully described in this section.
3920 First we briefly list all the switches, in alphabetical order, then we
3921 describe the switches in more detail in functionally grouped sections.
3922
3923 More switches exist for GCC than those documented here, especially
3924 for specific targets. However, their use is not recommended as
3925 they may change code generation in ways that are incompatible with
3926 the Ada run-time library, or can cause inconsistencies between
3927 compilation units.
3928
3929 @menu
3930 * Output and Error Message Control::
3931 * Warning Message Control::
3932 * Debugging and Assertion Control::
3933 * Validity Checking::
3934 * Style Checking::
3935 * Run-Time Checks::
3936 * Using gcc for Syntax Checking::
3937 * Using gcc for Semantic Checking::
3938 * Compiling Different Versions of Ada::
3939 * Character Set Control::
3940 * File Naming Control::
3941 * Subprogram Inlining Control::
3942 * Auxiliary Output Control::
3943 * Debugging Control::
3944 * Exception Handling Control::
3945 * Units to Sources Mapping Files::
3946 * Integrated Preprocessing::
3947 * Code Generation Control::
3948 @ifset vms
3949 * Return Codes::
3950 @end ifset
3951 @end menu
3952
3953 @table @option
3954 @c !sort!
3955 @ifclear vms
3956 @cindex @option{-b} (@command{gcc})
3957 @item -b @var{target}
3958 Compile your program to run on @var{target}, which is the name of a
3959 system configuration. You must have a GNAT cross-compiler built if
3960 @var{target} is not the same as your host system.
3961
3962 @item -B@var{dir}
3963 @cindex @option{-B} (@command{gcc})
3964 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
3965 from @var{dir} instead of the default location. Only use this switch
3966 when multiple versions of the GNAT compiler are available.
3967 @xref{Directory Options,, Options for Directory Search, gcc, Using the
3968 GNU Compiler Collection (GCC)}, for further details. You would normally
3969 use the @option{-b} or @option{-V} switch instead.
3970
3971 @item -c
3972 @cindex @option{-c} (@command{gcc})
3973 Compile. Always use this switch when compiling Ada programs.
3974
3975 Note: for some other languages when using @command{gcc}, notably in
3976 the case of C and C++, it is possible to use
3977 use @command{gcc} without a @option{-c} switch to
3978 compile and link in one step. In the case of GNAT, you
3979 cannot use this approach, because the binder must be run
3980 and @command{gcc} cannot be used to run the GNAT binder.
3981 @end ifclear
3982
3983 @item -fno-inline
3984 @cindex @option{-fno-inline} (@command{gcc})
3985 Suppresses all inlining, even if other optimization or inlining
3986 switches are set.  This includes suppression of inlining that
3987 results from the use of the pragma @code{Inline_Always}.
3988 Any occurrences of pragma @code{Inline} or @code{Inline_Always}
3989 are ignored, and @option{-gnatn} and @option{-gnatN} have no
3990 effect if this switch is present.
3991
3992 @item -fno-inline-functions
3993 @cindex @option{-fno-inline-functions} (@command{gcc})
3994 Suppresses automatic inlining of subprograms, which is enabled
3995 if @option{-O3} is used.
3996
3997 @item -fno-inline-small-functions
3998 @cindex @option{-fno-inline-small-functions} (@command{gcc})
3999 Suppresses automatic inlining of small subprograms, which is enabled
4000 if @option{-O2} is used.
4001
4002 @item -fno-inline-functions-called-once
4003 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
4004 Suppresses inlining of subprograms local to the unit and called once
4005 from within it, which is enabled if @option{-O1} is used.
4006
4007 @item -fno-ivopts
4008 @cindex @option{-fno-ivopts} (@command{gcc})
4009 Suppresses high-level loop induction variable optimizations, which are
4010 enabled if @option{-O1} is used. These optimizations are generally
4011 profitable but, for some specific cases of loops with numerous uses
4012 of the iteration variable that follow a common pattern, they may end
4013 up destroying the regularity that could be exploited at a lower level
4014 and thus producing inferior code.
4015
4016 @item -fno-strict-aliasing
4017 @cindex @option{-fno-strict-aliasing} (@command{gcc})
4018 Causes the compiler to avoid assumptions regarding non-aliasing
4019 of objects of different types. See
4020 @ref{Optimization and Strict Aliasing} for details.
4021
4022 @item -fstack-check
4023 @cindex @option{-fstack-check} (@command{gcc})
4024 Activates stack checking.
4025 See @ref{Stack Overflow Checking} for details.
4026
4027 @item -fstack-usage
4028 @cindex @option{-fstack-usage} (@command{gcc})
4029 Makes the compiler output stack usage information for the program, on a
4030 per-subprogram basis. See @ref{Static Stack Usage Analysis} for details.
4031
4032 @item -fcallgraph-info@r{[}=su@r{]}
4033 @cindex @option{-fcallgraph-info} (@command{gcc})
4034 Makes the compiler output callgraph information for the program, on a
4035 per-file basis.  The information is generated in the VCG format.  It can
4036 be decorated with stack-usage per-node information.
4037
4038 @item ^-g^/DEBUG^
4039 @cindex @option{^-g^/DEBUG^} (@command{gcc})
4040 Generate debugging information. This information is stored in the object
4041 file and copied from there to the final executable file by the linker,
4042 where it can be read by the debugger. You must use the
4043 @option{^-g^/DEBUG^} switch if you plan on using the debugger.
4044
4045 @item -gnat83
4046 @cindex @option{-gnat83} (@command{gcc})
4047 Enforce Ada 83 restrictions.
4048
4049 @item -gnat95
4050 @cindex @option{-gnat95} (@command{gcc})
4051 Enforce Ada 95 restrictions.
4052
4053 @item -gnat05
4054 @cindex @option{-gnat05} (@command{gcc})
4055 Allow full Ada 2005 features.
4056
4057 @item -gnat2005
4058 @cindex @option{-gnat2005} (@command{gcc})
4059 Allow full Ada 2005 features (same as @option{-gnat05})
4060
4061 @item -gnat12
4062 @cindex @option{-gnat12} (@command{gcc})
4063
4064 @item -gnat2012
4065 @cindex @option{-gnat2012} (@command{gcc})
4066 Allow full Ada 2012 features (same as @option{-gnat12})
4067
4068 @item -gnata
4069 @cindex @option{-gnata} (@command{gcc})
4070 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
4071 activated. Note that these pragmas can also be controlled using the
4072 configuration pragmas @code{Assertion_Policy} and @code{Debug_Policy}.
4073 It also activates pragmas @code{Check}, @code{Precondition}, and
4074 @code{Postcondition}. Note that these pragmas can also be controlled
4075 using the configuration pragma @code{Check_Policy}.
4076
4077 @item -gnatA
4078 @cindex @option{-gnatA} (@command{gcc})
4079 Avoid processing @file{gnat.adc}. If a @file{gnat.adc} file is present,
4080 it will be ignored.
4081
4082 @item -gnatb
4083 @cindex @option{-gnatb} (@command{gcc})
4084 Generate brief messages to @file{stderr} even if verbose mode set.
4085
4086 @item -gnatB
4087 @cindex @option{-gnatB} (@command{gcc})
4088 Assume no invalid (bad) values except for 'Valid attribute use
4089 (@pxref{Validity Checking}).
4090
4091 @item -gnatc
4092 @cindex @option{-gnatc} (@command{gcc})
4093 Check syntax and semantics only (no code generation attempted).
4094
4095 @item -gnatC
4096 @cindex @option{-gnatC} (@command{gcc})
4097 Generate CodePeer information (no code generation attempted).
4098 This switch will generate an intermediate representation suitable for
4099 use by CodePeer (@file{.scil} files). This switch is not compatible with
4100 code generation (it will, among other things, disable some switches such
4101 as -gnatn, and enable others such as -gnata).
4102
4103 @item -gnatd
4104 @cindex @option{-gnatd} (@command{gcc})
4105 Specify debug options for the compiler. The string of characters after
4106 the @option{-gnatd} specify the specific debug options. The possible
4107 characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
4108 compiler source file @file{debug.adb} for details of the implemented
4109 debug options. Certain debug options are relevant to applications
4110 programmers, and these are documented at appropriate points in this
4111 users guide.
4112
4113 @ifclear vms
4114 @item -gnatD
4115 @cindex @option{-gnatD[nn]} (@command{gcc})
4116 @end ifclear
4117 @ifset vms
4118 @item /XDEBUG /LXDEBUG=nnn
4119 @end ifset
4120 Create expanded source files for source level debugging. This switch
4121 also suppress generation of cross-reference information
4122 (see @option{-gnatx}).
4123
4124 @item -gnatec=@var{path}
4125 @cindex @option{-gnatec} (@command{gcc})
4126 Specify a configuration pragma file
4127 @ifclear vms
4128 (the equal sign is optional)
4129 @end ifclear
4130 (@pxref{The Configuration Pragmas Files}).
4131
4132 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=@var{value}@r{]}
4133 @cindex @option{-gnateD} (@command{gcc})
4134 Defines a symbol, associated with @var{value}, for preprocessing.
4135 (@pxref{Integrated Preprocessing}).
4136
4137 @item -gnateE
4138 @cindex @option{-gnateE} (@command{gcc})
4139 Generate extra information in exception messages. In particular, display
4140 extra column information and the value and range associated with index and
4141 range check failures, and extra column information for access checks.
4142 In cases where the compiler is able to determine at compile time that
4143 a check will fail, it gives a warning, and the extra information is not
4144 produced at run time.
4145
4146 @item -gnatef
4147 @cindex @option{-gnatef} (@command{gcc})
4148 Display full source path name in brief error messages.
4149
4150 @item -gnateG
4151 @cindex @option{-gnateG} (@command{gcc})
4152 Save result of preprocessing in a text file.
4153
4154 @item ^-gnateI^/MULTI_UNIT_INDEX=^@var{nnn}
4155 @cindex @option{-gnateI} (@command{gcc})
4156 Indicates that the source is a multi-unit source and that the index of the
4157 unit to compile is @var{nnn}. @var{nnn} needs to be a positive number and need
4158 to be a valid index in the multi-unit source.
4159
4160 @item -gnatem=@var{path}
4161 @cindex @option{-gnatem} (@command{gcc})
4162 Specify a mapping file
4163 @ifclear vms
4164 (the equal sign is optional)
4165 @end ifclear
4166 (@pxref{Units to Sources Mapping Files}).
4167
4168 @item -gnatep=@var{file}
4169 @cindex @option{-gnatep} (@command{gcc})
4170 Specify a preprocessing data file
4171 @ifclear vms
4172 (the equal sign is optional)
4173 @end ifclear
4174 (@pxref{Integrated Preprocessing}).
4175
4176 @item -gnateP
4177 @cindex @option{-gnateP} (@command{gcc})
4178 Turn categorization dependency errors into warnings.
4179 Ada requires that units that WITH one another have compatible categories, for
4180 example a Pure unit cannot WITH a Preelaborate unit. If this switch is used,
4181 these errors become warnings (which can be ignored, or suppressed in the usual
4182 manner). This can be useful in some specialized circumstances such as the
4183 temporary use of special test software.
4184 @item -gnateS
4185 @cindex @option{-gnateS} (@command{gcc})
4186 Generate SCO (Source Coverage Obligation) information in the ALI
4187 file. This information is used by advanced coverage tools. See
4188 unit @file{SCOs} in the compiler sources for details in files
4189 @file{scos.ads} and @file{scos.adb}.
4190
4191 @item -gnatE
4192 @cindex @option{-gnatE} (@command{gcc})
4193 Full dynamic elaboration checks.
4194
4195 @item -gnatf
4196 @cindex @option{-gnatf} (@command{gcc})
4197 Full errors. Multiple errors per line, all undefined references, do not
4198 attempt to suppress cascaded errors.
4199
4200 @item -gnatF
4201 @cindex @option{-gnatF} (@command{gcc})
4202 Externals names are folded to all uppercase.
4203
4204 @item ^-gnatg^/GNAT_INTERNAL^
4205 @cindex @option{^-gnatg^/GNAT_INTERNAL^} (@command{gcc})
4206 Internal GNAT implementation mode. This should not be used for
4207 applications programs, it is intended only for use by the compiler
4208 and its run-time library. For documentation, see the GNAT sources.
4209 Note that @option{^-gnatg^/GNAT_INTERNAL^} implies
4210 @option{^-gnatwae^/WARNINGS=ALL,ERRORS^} and
4211 @option{^-gnatyg^/STYLE_CHECKS=GNAT^}
4212 so that all standard warnings and all standard style options are turned on.
4213 All warnings and style messages are treated as errors.
4214
4215 @ifclear vms
4216 @item -gnatG=nn
4217 @cindex @option{-gnatG[nn]} (@command{gcc})
4218 @end ifclear
4219 @ifset vms
4220 @item /EXPAND_SOURCE, /LEXPAND_SOURCE=nnn
4221 @end ifset
4222 List generated expanded code in source form.
4223
4224 @item ^-gnath^/HELP^
4225 @cindex @option{^-gnath^/HELP^} (@command{gcc})
4226 Output usage information. The output is written to @file{stdout}.
4227
4228 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
4229 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
4230 Identifier character set
4231 @ifclear vms
4232 (@var{c}=1/2/3/4/8/9/p/f/n/w).
4233 @end ifclear
4234 For details of the possible selections for @var{c},
4235 see @ref{Character Set Control}.
4236
4237 @item ^-gnatI^/IGNORE_REP_CLAUSES^
4238 @cindex @option{^-gnatI^IGNORE_REP_CLAUSES^} (@command{gcc})
4239 Ignore representation clauses. When this switch is used,
4240 representation clauses are treated as comments. This is useful
4241 when initially porting code where you want to ignore rep clause
4242 problems, and also for compiling foreign code (particularly
4243 for use with ASIS). The representation clauses that are ignored
4244 are: enumeration_representation_clause, record_representation_clause,
4245 and attribute_definition_clause for the following attributes:
4246 Address, Alignment, Bit_Order, Component_Size, Machine_Radix,
4247 Object_Size, Size, Small, Stream_Size, and Value_Size.
4248 Note that this option should be used only for compiling -- the
4249 code is likely to malfunction at run time.
4250
4251 @item -gnatjnn
4252 @cindex @option{-gnatjnn} (@command{gcc})
4253 Reformat error messages to fit on nn character lines
4254
4255 @item -gnatk=@var{n}
4256 @cindex @option{-gnatk} (@command{gcc})
4257 Limit file names to @var{n} (1-999) characters ^(@code{k} = krunch)^^.
4258
4259 @item -gnatl
4260 @cindex @option{-gnatl} (@command{gcc})
4261 Output full source listing with embedded error messages.
4262
4263 @item -gnatL
4264 @cindex @option{-gnatL} (@command{gcc})
4265 Used in conjunction with -gnatG or -gnatD to intersperse original
4266 source lines (as comment lines with line numbers) in the expanded
4267 source output.
4268
4269 @item -gnatm=@var{n}
4270 @cindex @option{-gnatm} (@command{gcc})
4271 Limit number of detected error or warning messages to @var{n}
4272 where @var{n} is in the range 1..999999. The default setting if
4273 no switch is given is 9999. If the number of warnings reaches this
4274 limit, then a message is output and further warnings are suppressed,
4275 but the compilation is continued. If the number of error messages
4276 reaches this limit, then a message is output and the compilation
4277 is abandoned. The equal sign here is optional. A value of zero
4278 means that no limit applies.
4279
4280 @item -gnatn
4281 @cindex @option{-gnatn} (@command{gcc})
4282 Activate inlining for subprograms for which
4283 pragma @code{Inline} is specified. This inlining is performed
4284 by the GCC back-end.
4285
4286 @item -gnatN
4287 @cindex @option{-gnatN} (@command{gcc})
4288 Activate front end inlining for subprograms for which
4289 pragma @code{Inline} is specified. This inlining is performed
4290 by the front end and will be visible in the
4291 @option{-gnatG} output.
4292
4293 When using a gcc-based back end (in practice this means using any version
4294 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
4295 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
4296 Historically front end inlining was more extensive than the gcc back end
4297 inlining, but that is no longer the case.
4298
4299 @item -gnato
4300 @cindex @option{-gnato} (@command{gcc})
4301 Enable numeric overflow checking (which is not normally enabled by
4302 default). Note that division by zero is a separate check that is not
4303 controlled by this switch (division by zero checking is on by default).
4304
4305 @item -gnatp
4306 @cindex @option{-gnatp} (@command{gcc})
4307 Suppress all checks. See @ref{Run-Time Checks} for details. This switch
4308 has no effect if cancelled by a subsequent @option{-gnat-p} switch.
4309
4310 @item -gnat-p
4311 @cindex @option{-gnat-p} (@command{gcc})
4312 Cancel effect of previous @option{-gnatp} switch.
4313
4314 @item -gnatP
4315 @cindex @option{-gnatP} (@command{gcc})
4316 Enable polling. This is required on some systems (notably Windows NT) to
4317 obtain asynchronous abort and asynchronous transfer of control capability.
4318 @xref{Pragma Polling,,, gnat_rm, GNAT Reference Manual}, for full
4319 details.
4320
4321 @item -gnatq
4322 @cindex @option{-gnatq} (@command{gcc})
4323 Don't quit. Try semantics, even if parse errors.
4324
4325 @item -gnatQ
4326 @cindex @option{-gnatQ} (@command{gcc})
4327 Don't quit. Generate @file{ALI} and tree files even if illegalities.
4328
4329 @item -gnatr
4330 @cindex @option{-gnatr} (@command{gcc})
4331 Treat pragma Restrictions as Restriction_Warnings.
4332
4333 @item ^-gnatR@r{[}0@r{/}1@r{/}2@r{/}3@r{[}s@r{]]}^/REPRESENTATION_INFO^
4334 @cindex @option{-gnatR} (@command{gcc})
4335 Output representation information for declared types and objects.
4336
4337 @item -gnats
4338 @cindex @option{-gnats} (@command{gcc})
4339 Syntax check only.
4340
4341 @item -gnatS
4342 @cindex @option{-gnatS} (@command{gcc})
4343 Print package Standard.
4344
4345 @item -gnatt
4346 @cindex @option{-gnatt} (@command{gcc})
4347 Generate tree output file.
4348
4349 @item ^-gnatT^/TABLE_MULTIPLIER=^@var{nnn}
4350 @cindex @option{^-gnatT^/TABLE_MULTIPLIER^} (@command{gcc})
4351 All compiler tables start at @var{nnn} times usual starting size.
4352
4353 @item -gnatu
4354 @cindex @option{-gnatu} (@command{gcc})
4355 List units for this compilation.
4356
4357 @item -gnatU
4358 @cindex @option{-gnatU} (@command{gcc})
4359 Tag all error messages with the unique string ``error:''
4360
4361 @item -gnatv
4362 @cindex @option{-gnatv} (@command{gcc})
4363 Verbose mode. Full error output with source lines to @file{stdout}.
4364
4365 @item -gnatV
4366 @cindex @option{-gnatV} (@command{gcc})
4367 Control level of validity checking (@pxref{Validity Checking}).
4368
4369 @item ^-gnatw@var{xxx}^/WARNINGS=(@var{option}@r{[},@dots{}@r{]})^
4370 @cindex @option{^-gnatw^/WARNINGS^} (@command{gcc})
4371 Warning mode where
4372 ^@var{xxx} is a string of option letters that^the list of options^ denotes
4373 the exact warnings that
4374 are enabled or disabled (@pxref{Warning Message Control}).
4375
4376 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
4377 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
4378 Wide character encoding method
4379 @ifclear vms
4380 (@var{e}=n/h/u/s/e/8).
4381 @end ifclear
4382 @ifset vms
4383 (@var{e}=@code{BRACKETS, NONE, HEX, UPPER, SHIFT_JIS, EUC, UTF8})
4384 @end ifset
4385
4386 @item -gnatx
4387 @cindex @option{-gnatx} (@command{gcc})
4388 Suppress generation of cross-reference information.
4389
4390 @item -gnatX
4391 @cindex @option{-gnatX} (@command{gcc})
4392 Enable GNAT implementation extensions and latest Ada version.
4393
4394 @item ^-gnaty^/STYLE_CHECKS=(option,option@dots{})^
4395 @cindex @option{^-gnaty^/STYLE_CHECKS^} (@command{gcc})
4396 Enable built-in style checks (@pxref{Style Checking}).
4397
4398 @item ^-gnatz^/DISTRIBUTION_STUBS=^@var{m}
4399 @cindex @option{^-gnatz^/DISTRIBUTION_STUBS^} (@command{gcc})
4400 Distribution stub generation and compilation
4401 @ifclear vms
4402 (@var{m}=r/c for receiver/caller stubs).
4403 @end ifclear
4404 @ifset vms
4405 (@var{m}=@code{RECEIVER} or @code{CALLER} to specify the type of stubs
4406 to be generated and compiled).
4407 @end ifset
4408
4409 @item ^-I^/SEARCH=^@var{dir}
4410 @cindex @option{^-I^/SEARCH^} (@command{gcc})
4411 @cindex RTL
4412 Direct GNAT to search the @var{dir} directory for source files needed by
4413 the current compilation
4414 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4415
4416 @item ^-I-^/NOCURRENT_DIRECTORY^
4417 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gcc})
4418 @cindex RTL
4419 Except for the source file named in the command line, do not look for source
4420 files in the directory containing the source file named in the command line
4421 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4422
4423 @ifclear vms
4424 @item -mbig-switch
4425 @cindex @option{-mbig-switch} (@command{gcc})
4426 @cindex @code{case} statement (effect of @option{-mbig-switch} option)
4427 This standard gcc switch causes the compiler to use larger offsets in its
4428 jump table representation for @code{case} statements.
4429 This may result in less efficient code, but is sometimes necessary
4430 (for example on HP-UX targets)
4431 @cindex HP-UX and @option{-mbig-switch} option
4432 in order to compile large and/or nested @code{case} statements.
4433
4434 @item -o @var{file}
4435 @cindex @option{-o} (@command{gcc})
4436 This switch is used in @command{gcc} to redirect the generated object file
4437 and its associated ALI file. Beware of this switch with GNAT, because it may
4438 cause the object file and ALI file to have different names which in turn
4439 may confuse the binder and the linker.
4440 @end ifclear
4441
4442 @item -nostdinc
4443 @cindex @option{-nostdinc} (@command{gcc})
4444 Inhibit the search of the default location for the GNAT Run Time
4445 Library (RTL) source files.
4446
4447 @item -nostdlib
4448 @cindex @option{-nostdlib} (@command{gcc})
4449 Inhibit the search of the default location for the GNAT Run Time
4450 Library (RTL) ALI files.
4451
4452 @ifclear vms
4453 @c @item -O@ovar{n}
4454 @c Expanding @ovar macro inline (explanation in macro def comments)
4455 @item -O@r{[}@var{n}@r{]}
4456 @cindex @option{-O} (@command{gcc})
4457 @var{n} controls the optimization level.
4458
4459 @table @asis
4460 @item n = 0
4461 No optimization, the default setting if no @option{-O} appears
4462
4463 @item n = 1
4464 Normal optimization, the default if you specify @option{-O} without
4465 an operand. A good compromise between code quality and compilation
4466 time.
4467
4468 @item n = 2
4469 Extensive optimization, may improve execution time, possibly at the cost of
4470 substantially increased compilation time.
4471
4472 @item n = 3
4473 Same as @option{-O2}, and also includes inline expansion for small subprograms
4474 in the same unit.
4475
4476 @item n = s
4477 Optimize space usage
4478 @end table
4479
4480 @noindent
4481 See also @ref{Optimization Levels}.
4482 @end ifclear
4483
4484 @ifset vms
4485 @item  /NOOPTIMIZE
4486 @cindex @option{/NOOPTIMIZE} (@code{GNAT COMPILE})
4487 Equivalent to @option{/OPTIMIZE=NONE}.
4488 This is the default behavior in the absence of an @option{/OPTIMIZE}
4489 qualifier.
4490
4491 @item /OPTIMIZE@r{[}=(keyword@r{[},@dots{}@r{]})@r{]}
4492 @cindex @option{/OPTIMIZE} (@code{GNAT COMPILE})
4493 Selects the level of optimization for your program. The supported
4494 keywords are as follows:
4495 @table @code
4496 @item   ALL
4497 Perform most optimizations, including those that
4498 are expensive.
4499 This is the default if the @option{/OPTIMIZE} qualifier is supplied
4500 without keyword options.
4501
4502 @item   NONE
4503 Do not do any optimizations. Same as @code{/NOOPTIMIZE}.
4504
4505 @item SOME
4506 Perform some optimizations, but omit ones that are costly.
4507
4508 @item   DEVELOPMENT
4509 Same as @code{SOME}.
4510
4511 @item INLINING
4512 Full optimization as in @option{/OPTIMIZE=ALL}, and also attempts
4513 automatic inlining of small subprograms within a unit
4514
4515 @item   UNROLL_LOOPS
4516 Try to unroll loops. This keyword may be specified together with
4517 any keyword above other than @code{NONE}. Loop unrolling
4518 usually, but not always, improves the performance of programs.
4519
4520 @item SPACE
4521 Optimize space usage
4522 @end table
4523
4524 @noindent
4525 See also @ref{Optimization Levels}.
4526 @end ifset
4527
4528 @ifclear vms
4529 @item -pass-exit-codes
4530 @cindex @option{-pass-exit-codes} (@command{gcc})
4531 Catch exit codes from the compiler and use the most meaningful as
4532 exit status.
4533 @end ifclear
4534
4535 @item --RTS=@var{rts-path}
4536 @cindex @option{--RTS} (@command{gcc})
4537 Specifies the default location of the runtime library. Same meaning as the
4538 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
4539
4540 @item ^-S^/ASM^
4541 @cindex @option{^-S^/ASM^} (@command{gcc})
4542 ^Used in place of @option{-c} to^Used to^
4543 cause the assembler source file to be
4544 generated, using @file{^.s^.S^} as the extension,
4545 instead of the object file.
4546 This may be useful if you need to examine the generated assembly code.
4547
4548 @item ^-fverbose-asm^/VERBOSE_ASM^
4549 @cindex @option{^-fverbose-asm^/VERBOSE_ASM^} (@command{gcc})
4550 ^Used in conjunction with @option{-S}^Used in place of @option{/ASM}^
4551 to cause the generated assembly code file to be annotated with variable
4552 names, making it significantly easier to follow.
4553
4554 @item ^-v^/VERBOSE^
4555 @cindex @option{^-v^/VERBOSE^} (@command{gcc})
4556 Show commands generated by the @command{gcc} driver. Normally used only for
4557 debugging purposes or if you need to be sure what version of the
4558 compiler you are executing.
4559
4560 @ifclear vms
4561 @item -V @var{ver}
4562 @cindex @option{-V} (@command{gcc})
4563 Execute @var{ver} version of the compiler. This is the @command{gcc}
4564 version, not the GNAT version.
4565 @end ifclear
4566
4567 @item ^-w^/NO_BACK_END_WARNINGS^
4568 @cindex @option{-w} (@command{gcc})
4569 Turn off warnings generated by the back end of the compiler. Use of
4570 this switch also causes the default for front end warnings to be set
4571 to suppress (as though @option{-gnatws} had appeared at the start of
4572 the options).
4573
4574 @end table
4575
4576 @ifclear vms
4577 @c Combining qualifiers does not work on VMS
4578 You may combine a sequence of GNAT switches into a single switch. For
4579 example, the combined switch
4580
4581 @cindex Combining GNAT switches
4582 @smallexample
4583 -gnatofi3
4584 @end smallexample
4585
4586 @noindent
4587 is equivalent to specifying the following sequence of switches:
4588
4589 @smallexample
4590 -gnato -gnatf -gnati3
4591 @end smallexample
4592 @end ifclear
4593
4594 @noindent
4595 The following restrictions apply to the combination of switches
4596 in this manner:
4597
4598 @itemize @bullet
4599 @item
4600 The switch @option{-gnatc} if combined with other switches must come
4601 first in the string.
4602
4603 @item
4604 The switch @option{-gnats} if combined with other switches must come
4605 first in the string.
4606
4607 @item
4608 The switches
4609 ^^@option{/DISTRIBUTION_STUBS=},^
4610 @option{-gnatzc} and @option{-gnatzr} may not be combined with any other
4611 switches, and only one of them may appear in the command line.
4612
4613 @item
4614 The switch @option{-gnat-p} may not be combined with any other switch.
4615
4616 @ifclear vms
4617 @item
4618 Once a ``y'' appears in the string (that is a use of the @option{-gnaty}
4619 switch), then all further characters in the switch are interpreted
4620 as style modifiers (see description of @option{-gnaty}).
4621
4622 @item
4623 Once a ``d'' appears in the string (that is a use of the @option{-gnatd}
4624 switch), then all further characters in the switch are interpreted
4625 as debug flags (see description of @option{-gnatd}).
4626
4627 @item
4628 Once a ``w'' appears in the string (that is a use of the @option{-gnatw}
4629 switch), then all further characters in the switch are interpreted
4630 as warning mode modifiers (see description of @option{-gnatw}).
4631
4632 @item
4633 Once a ``V'' appears in the string (that is a use of the @option{-gnatV}
4634 switch), then all further characters in the switch are interpreted
4635 as validity checking options (@pxref{Validity Checking}).
4636
4637 @item
4638 Option ``em'', ``ec'', ``ep'', ``l='' and ``R'' must be the last options in
4639 a combined list of options.
4640 @end ifclear
4641 @end itemize
4642
4643 @node Output and Error Message Control
4644 @subsection Output and Error Message Control
4645 @findex stderr
4646
4647 @noindent
4648 The standard default format for error messages is called ``brief format''.
4649 Brief format messages are written to @file{stderr} (the standard error
4650 file) and have the following form:
4651
4652 @smallexample
4653 e.adb:3:04: Incorrect spelling of keyword "function"
4654 e.adb:4:20: ";" should be "is"
4655 @end smallexample
4656
4657 @noindent
4658 The first integer after the file name is the line number in the file,
4659 and the second integer is the column number within the line.
4660 @ifclear vms
4661 @code{GPS} can parse the error messages
4662 and point to the referenced character.
4663 @end ifclear
4664 The following switches provide control over the error message
4665 format:
4666
4667 @table @option
4668 @c !sort!
4669 @item -gnatv
4670 @cindex @option{-gnatv} (@command{gcc})
4671 @findex stdout
4672 @ifclear vms
4673 The v stands for verbose.
4674 @end ifclear
4675 The effect of this setting is to write long-format error
4676 messages to @file{stdout} (the standard output file.
4677 The same program compiled with the
4678 @option{-gnatv} switch would generate:
4679
4680 @smallexample
4681 @cartouche
4682 3. funcion X (Q : Integer)
4683    |
4684 >>> Incorrect spelling of keyword "function"
4685 4. return Integer;
4686                  |
4687 >>> ";" should be "is"
4688 @end cartouche
4689 @end smallexample
4690
4691 @noindent
4692 The vertical bar indicates the location of the error, and the @samp{>>>}
4693 prefix can be used to search for error messages. When this switch is
4694 used the only source lines output are those with errors.
4695
4696 @item -gnatl
4697 @cindex @option{-gnatl} (@command{gcc})
4698 @ifclear vms
4699 The @code{l} stands for list.
4700 @end ifclear
4701 This switch causes a full listing of
4702 the file to be generated. In the case where a body is
4703 compiled, the corresponding spec is also listed, along
4704 with any subunits. Typical output from compiling a package
4705 body @file{p.adb} might look like:
4706
4707 @smallexample @c ada
4708 @cartouche
4709  Compiling: p.adb
4710
4711      1. package body p is
4712      2.    procedure a;
4713      3.    procedure a is separate;
4714      4. begin
4715      5.    null
4716                |
4717         >>> missing ";"
4718
4719      6. end;
4720
4721 Compiling: p.ads
4722
4723      1. package p is
4724      2.    pragma Elaborate_Body
4725                                 |
4726         >>> missing ";"
4727
4728      3. end p;
4729
4730 Compiling: p-a.adb
4731
4732      1. separate p
4733                 |
4734         >>> missing "("
4735
4736      2. procedure a is
4737      3. begin
4738      4.    null
4739                |
4740         >>> missing ";"
4741
4742      5. end;
4743 @end cartouche
4744 @end smallexample
4745
4746 @noindent
4747 @findex stderr
4748 When you specify the @option{-gnatv} or @option{-gnatl} switches and
4749 standard output is redirected, a brief summary is written to
4750 @file{stderr} (standard error) giving the number of error messages and
4751 warning messages generated.
4752
4753 @item ^-gnatl^/OUTPUT_FILE^=file
4754 @cindex @option{^-gnatl^/OUTPUT_FILE^=fname} (@command{gcc})
4755 This has the same effect as @option{-gnatl} except that the output is
4756 written to a file instead of to standard output. If the given name
4757 @file{fname} does not start with a period, then it is the full name
4758 of the file to be written. If @file{fname} is an extension, it is
4759 appended to the name of the file being compiled. For example, if
4760 file @file{xyz.adb} is compiled with @option{^-gnatl^/OUTPUT_FILE^=.lst},
4761 then the output is written to file ^xyz.adb.lst^xyz.adb_lst^.
4762
4763 @item -gnatU
4764 @cindex @option{-gnatU} (@command{gcc})
4765 This switch forces all error messages to be preceded by the unique
4766 string ``error:''. This means that error messages take a few more
4767 characters in space, but allows easy searching for and identification
4768 of error messages.
4769
4770 @item -gnatb
4771 @cindex @option{-gnatb} (@command{gcc})
4772 @ifclear vms
4773 The @code{b} stands for brief.
4774 @end ifclear
4775 This switch causes GNAT to generate the
4776 brief format error messages to @file{stderr} (the standard error
4777 file) as well as the verbose
4778 format message or full listing (which as usual is written to
4779 @file{stdout} (the standard output file).
4780
4781 @item -gnatm=@var{n}
4782 @cindex @option{-gnatm} (@command{gcc})
4783 @ifclear vms
4784 The @code{m} stands for maximum.
4785 @end ifclear
4786 @var{n} is a decimal integer in the
4787 range of 1 to 999999 and limits the number of error or warning
4788 messages to be generated. For example, using
4789 @option{-gnatm2} might yield
4790
4791 @smallexample
4792 e.adb:3:04: Incorrect spelling of keyword "function"
4793 e.adb:5:35: missing ".."
4794 fatal error: maximum number of errors detected
4795 compilation abandoned
4796 @end smallexample
4797
4798 @noindent
4799 The default setting if
4800 no switch is given is 9999. If the number of warnings reaches this
4801 limit, then a message is output and further warnings are suppressed,
4802 but the compilation is continued. If the number of error messages
4803 reaches this limit, then a message is output and the compilation
4804 is abandoned. A value of zero means that no limit applies.
4805
4806 @noindent
4807 Note that the equal sign is optional, so the switches
4808 @option{-gnatm2} and @option{-gnatm=2} are equivalent.
4809
4810 @item -gnatf
4811 @cindex @option{-gnatf} (@command{gcc})
4812 @cindex Error messages, suppressing
4813 @ifclear vms
4814 The @code{f} stands for full.
4815 @end ifclear
4816 Normally, the compiler suppresses error messages that are likely to be
4817 redundant. This switch causes all error
4818 messages to be generated. In particular, in the case of
4819 references to undefined variables. If a given variable is referenced
4820 several times, the normal format of messages is
4821 @smallexample
4822 e.adb:7:07: "V" is undefined (more references follow)
4823 @end smallexample
4824
4825 @noindent
4826 where the parenthetical comment warns that there are additional
4827 references to the variable @code{V}. Compiling the same program with the
4828 @option{-gnatf} switch yields
4829
4830 @smallexample
4831 e.adb:7:07: "V" is undefined
4832 e.adb:8:07: "V" is undefined
4833 e.adb:8:12: "V" is undefined
4834 e.adb:8:16: "V" is undefined
4835 e.adb:9:07: "V" is undefined
4836 e.adb:9:12: "V" is undefined
4837 @end smallexample
4838
4839 @noindent
4840 The @option{-gnatf} switch also generates additional information for
4841 some error messages.  Some examples are:
4842
4843 @itemize @bullet
4844 @item
4845 Details on possibly non-portable unchecked conversion
4846 @item
4847 List possible interpretations for ambiguous calls
4848 @item
4849 Additional details on incorrect parameters
4850 @end itemize
4851
4852 @item -gnatjnn
4853 @cindex @option{-gnatjnn} (@command{gcc})
4854 In normal operation mode (or if @option{-gnatj0} is used, then error messages
4855 with continuation lines are treated as though the continuation lines were
4856 separate messages (and so a warning with two continuation lines counts as
4857 three warnings, and is listed as three separate messages).
4858
4859 If the @option{-gnatjnn} switch is used with a positive value for nn, then
4860 messages are output in a different manner. A message and all its continuation
4861 lines are treated as a unit, and count as only one warning or message in the
4862 statistics totals. Furthermore, the message is reformatted so that no line
4863 is longer than nn characters.
4864
4865 @item -gnatq
4866 @cindex @option{-gnatq} (@command{gcc})
4867 @ifclear vms
4868 The @code{q} stands for quit (really ``don't quit'').
4869 @end ifclear
4870 In normal operation mode, the compiler first parses the program and
4871 determines if there are any syntax errors. If there are, appropriate
4872 error messages are generated and compilation is immediately terminated.
4873 This switch tells
4874 GNAT to continue with semantic analysis even if syntax errors have been
4875 found. This may enable the detection of more errors in a single run. On
4876 the other hand, the semantic analyzer is more likely to encounter some
4877 internal fatal error when given a syntactically invalid tree.
4878
4879 @item -gnatQ
4880 @cindex @option{-gnatQ} (@command{gcc})
4881 In normal operation mode, the @file{ALI} file is not generated if any
4882 illegalities are detected in the program. The use of @option{-gnatQ} forces
4883 generation of the @file{ALI} file. This file is marked as being in
4884 error, so it cannot be used for binding purposes, but it does contain
4885 reasonably complete cross-reference information, and thus may be useful
4886 for use by tools (e.g., semantic browsing tools or integrated development
4887 environments) that are driven from the @file{ALI} file. This switch
4888 implies @option{-gnatq}, since the semantic phase must be run to get a
4889 meaningful ALI file.
4890
4891 In addition, if @option{-gnatt} is also specified, then the tree file is
4892 generated even if there are illegalities. It may be useful in this case
4893 to also specify @option{-gnatq} to ensure that full semantic processing
4894 occurs. The resulting tree file can be processed by ASIS, for the purpose
4895 of providing partial information about illegal units, but if the error
4896 causes the tree to be badly malformed, then ASIS may crash during the
4897 analysis.
4898
4899 When @option{-gnatQ} is used and the generated @file{ALI} file is marked as
4900 being in error, @command{gnatmake} will attempt to recompile the source when it
4901 finds such an @file{ALI} file, including with switch @option{-gnatc}.
4902
4903 Note that @option{-gnatQ} has no effect if @option{-gnats} is specified,
4904 since ALI files are never generated if @option{-gnats} is set.
4905
4906 @end table
4907
4908 @node Warning Message Control
4909 @subsection Warning Message Control
4910 @cindex Warning messages
4911 @noindent
4912 In addition to error messages, which correspond to illegalities as defined
4913 in the Ada Reference Manual, the compiler detects two kinds of warning
4914 situations.
4915
4916 First, the compiler considers some constructs suspicious and generates a
4917 warning message to alert you to a possible error. Second, if the
4918 compiler detects a situation that is sure to raise an exception at
4919 run time, it generates a warning message. The following shows an example
4920 of warning messages:
4921 @smallexample
4922 e.adb:4:24: warning: creation of object may raise Storage_Error
4923 e.adb:10:17: warning: static value out of range
4924 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
4925 @end smallexample
4926
4927 @noindent
4928 GNAT considers a large number of situations as appropriate
4929 for the generation of warning messages. As always, warnings are not
4930 definite indications of errors. For example, if you do an out-of-range
4931 assignment with the deliberate intention of raising a
4932 @code{Constraint_Error} exception, then the warning that may be
4933 issued does not indicate an error. Some of the situations for which GNAT
4934 issues warnings (at least some of the time) are given in the following
4935 list. This list is not complete, and new warnings are often added to
4936 subsequent versions of GNAT. The list is intended to give a general idea
4937 of the kinds of warnings that are generated.
4938
4939 @itemize @bullet
4940 @item
4941 Possible infinitely recursive calls
4942
4943 @item
4944 Out-of-range values being assigned
4945
4946 @item
4947 Possible order of elaboration problems
4948
4949 @item
4950 Assertions (pragma Assert) that are sure to fail
4951
4952 @item
4953 Unreachable code
4954
4955 @item
4956 Address clauses with possibly unaligned values, or where an attempt is
4957 made to overlay a smaller variable with a larger one.
4958
4959 @item
4960 Fixed-point type declarations with a null range
4961
4962 @item
4963 Direct_IO or Sequential_IO instantiated with a type that has access values
4964
4965 @item
4966 Variables that are never assigned a value
4967
4968 @item
4969 Variables that are referenced before being initialized
4970
4971 @item
4972 Task entries with no corresponding @code{accept} statement
4973
4974 @item
4975 Duplicate accepts for the same task entry in a @code{select}
4976
4977 @item
4978 Objects that take too much storage
4979
4980 @item
4981 Unchecked conversion between types of differing sizes
4982
4983 @item
4984 Missing @code{return} statement along some execution path in a function
4985
4986 @item
4987 Incorrect (unrecognized) pragmas
4988
4989 @item
4990 Incorrect external names
4991
4992 @item
4993 Allocation from empty storage pool
4994
4995 @item
4996 Potentially blocking operation in protected type
4997
4998 @item
4999 Suspicious parenthesization of expressions
5000
5001 @item
5002 Mismatching bounds in an aggregate
5003
5004 @item
5005 Attempt to return local value by reference
5006
5007 @item
5008 Premature instantiation of a generic body
5009
5010 @item
5011 Attempt to pack aliased components
5012
5013 @item
5014 Out of bounds array subscripts
5015
5016 @item
5017 Wrong length on string assignment
5018
5019 @item
5020 Violations of style rules if style checking is enabled
5021
5022 @item
5023 Unused @code{with} clauses
5024
5025 @item
5026 @code{Bit_Order} usage that does not have any effect
5027
5028 @item
5029 @code{Standard.Duration} used to resolve universal fixed expression
5030
5031 @item
5032 Dereference of possibly null value
5033
5034 @item
5035 Declaration that is likely to cause storage error
5036
5037 @item
5038 Internal GNAT unit @code{with}'ed by application unit
5039
5040 @item
5041 Values known to be out of range at compile time
5042
5043 @item
5044 Unreferenced labels and variables
5045
5046 @item
5047 Address overlays that could clobber memory
5048
5049 @item
5050 Unexpected initialization when address clause present
5051
5052 @item
5053 Bad alignment for address clause
5054
5055 @item
5056 Useless type conversions
5057
5058 @item
5059 Redundant assignment statements and other redundant constructs
5060
5061 @item
5062 Useless exception handlers
5063
5064 @item
5065 Accidental hiding of name by child unit
5066
5067 @item
5068 Access before elaboration detected at compile time
5069
5070 @item
5071 A range in a @code{for} loop that is known to be null or might be null
5072
5073 @end itemize
5074
5075 @noindent
5076 The following section lists compiler switches that are available
5077 to control the handling of warning messages. It is also possible
5078 to exercise much finer control over what warnings are issued and
5079 suppressed using the GNAT pragma Warnings, @xref{Pragma Warnings,,,
5080 gnat_rm, GNAT Reference manual}.
5081
5082 @table @option
5083 @c !sort!
5084 @item -gnatwa
5085 @emph{Activate most optional warnings.}
5086 @cindex @option{-gnatwa} (@command{gcc})
5087 This switch activates most optional warning messages.  See the remaining list
5088 in this section for details on optional warning messages that can be
5089 individually controlled.  The warnings that are not turned on by this
5090 switch are
5091 @option{-gnatwd} (implicit dereferencing),
5092 @option{-gnatwh} (hiding),
5093 @option{-gnatw.h} (holes (gaps) in record layouts)
5094 @option{-gnatwl} (elaboration warnings),
5095 @option{-gnatw.o} (warn on values set by out parameters ignored)
5096 and @option{-gnatwt} (tracking of deleted conditional code).
5097 All other optional warnings are turned on.
5098
5099 @item -gnatwA
5100 @emph{Suppress all optional errors.}
5101 @cindex @option{-gnatwA} (@command{gcc})
5102 This switch suppresses all optional warning messages, see remaining list
5103 in this section for details on optional warning messages that can be
5104 individually controlled.
5105
5106 @item -gnatw.a
5107 @emph{Activate warnings on failing assertions.}
5108 @cindex @option{-gnatw.a} (@command{gcc})
5109 @cindex Assert failures
5110 This switch activates warnings for assertions where the compiler can tell at
5111 compile time that the assertion will fail. Note that this warning is given
5112 even if assertions are disabled. The default is that such warnings are
5113 generated.
5114
5115 @item -gnatw.A
5116 @emph{Suppress warnings on failing assertions.}
5117 @cindex @option{-gnatw.A} (@command{gcc})
5118 @cindex Assert failures
5119 This switch suppresses warnings for assertions where the compiler can tell at
5120 compile time that the assertion will fail.
5121
5122 @item -gnatwb
5123 @emph{Activate warnings on bad fixed values.}
5124 @cindex @option{-gnatwb} (@command{gcc})
5125 @cindex Bad fixed values
5126 @cindex Fixed-point Small value
5127 @cindex Small value
5128 This switch activates warnings for static fixed-point expressions whose
5129 value is not an exact multiple of Small. Such values are implementation
5130 dependent, since an implementation is free to choose either of the multiples
5131 that surround the value. GNAT always chooses the closer one, but this is not
5132 required behavior, and it is better to specify a value that is an exact
5133 multiple, ensuring predictable execution. The default is that such warnings
5134 are not generated.
5135
5136 @item -gnatwB
5137 @emph{Suppress warnings on bad fixed values.}
5138 @cindex @option{-gnatwB} (@command{gcc})
5139 This switch suppresses warnings for static fixed-point expressions whose
5140 value is not an exact multiple of Small.
5141
5142 @item -gnatw.b
5143 @emph{Activate warnings on biased representation.}
5144 @cindex @option{-gnatw.b} (@command{gcc})
5145 @cindex Biased representation
5146 This switch activates warnings when a size clause, value size clause, component
5147 clause, or component size clause forces the use of biased representation for an
5148 integer type (e.g. representing a range of 10..11 in a single bit by using 0/1
5149 to represent 10/11). The default is that such warnings are generated.
5150
5151 @item -gnatw.B
5152 @emph{Suppress warnings on biased representation.}
5153 @cindex @option{-gnatwB} (@command{gcc})
5154 This switch suppresses warnings for representation clauses that force the use
5155 of biased representation.
5156
5157 @item -gnatwc
5158 @emph{Activate warnings on conditionals.}
5159 @cindex @option{-gnatwc} (@command{gcc})
5160 @cindex Conditionals, constant
5161 This switch activates warnings for conditional expressions used in
5162 tests that are known to be True or False at compile time. The default
5163 is that such warnings are not generated.
5164 Note that this warning does
5165 not get issued for the use of boolean variables or constants whose
5166 values are known at compile time, since this is a standard technique
5167 for conditional compilation in Ada, and this would generate too many
5168 false positive warnings.
5169
5170 This warning option also activates a special test for comparisons using
5171 the operators ``>='' and`` <=''.
5172 If the compiler can tell that only the equality condition is possible,
5173 then it will warn that the ``>'' or ``<'' part of the test
5174 is useless and that the operator could be replaced by ``=''.
5175 An example would be comparing a @code{Natural} variable <= 0.
5176
5177 This warning option also generates warnings if
5178 one or both tests is optimized away in a membership test for integer
5179 values if the result can be determined at compile time. Range tests on
5180 enumeration types are not included, since it is common for such tests
5181 to include an end point.
5182
5183 This warning can also be turned on using @option{-gnatwa}.
5184
5185 @item -gnatwC
5186 @emph{Suppress warnings on conditionals.}
5187 @cindex @option{-gnatwC} (@command{gcc})
5188 This switch suppresses warnings for conditional expressions used in
5189 tests that are known to be True or False at compile time.
5190
5191 @item -gnatw.c
5192 @emph{Activate warnings on missing component clauses.}
5193 @cindex @option{-gnatw.c} (@command{gcc})
5194 @cindex Component clause, missing
5195 This switch activates warnings for record components where a record
5196 representation clause is present and has component clauses for the
5197 majority, but not all, of the components. A warning is given for each
5198 component for which no component clause is present.
5199
5200 This warning can also be turned on using @option{-gnatwa}.
5201
5202 @item -gnatw.C
5203 @emph{Suppress warnings on missing component clauses.}
5204 @cindex @option{-gnatwC} (@command{gcc})
5205 This switch suppresses warnings for record components that are
5206 missing a component clause in the situation described above.
5207
5208 @item -gnatwd
5209 @emph{Activate warnings on implicit dereferencing.}
5210 @cindex @option{-gnatwd} (@command{gcc})
5211 If this switch is set, then the use of a prefix of an access type
5212 in an indexed component, slice, or selected component without an
5213 explicit @code{.all} will generate a warning. With this warning
5214 enabled, access checks occur only at points where an explicit
5215 @code{.all} appears in the source code (assuming no warnings are
5216 generated as a result of this switch). The default is that such
5217 warnings are not generated.
5218 Note that @option{-gnatwa} does not affect the setting of
5219 this warning option.
5220
5221 @item -gnatwD
5222 @emph{Suppress warnings on implicit dereferencing.}
5223 @cindex @option{-gnatwD} (@command{gcc})
5224 @cindex Implicit dereferencing
5225 @cindex Dereferencing, implicit
5226 This switch suppresses warnings for implicit dereferences in
5227 indexed components, slices, and selected components.
5228
5229 @item -gnatwe
5230 @emph{Treat warnings and style checks as errors.}
5231 @cindex @option{-gnatwe} (@command{gcc})
5232 @cindex Warnings, treat as error
5233 This switch causes warning messages and style check messages to be
5234 treated as errors.
5235 The warning string still appears, but the warning messages are counted
5236 as errors, and prevent the generation of an object file. Note that this
5237 is the only -gnatw switch that affects the handling of style check messages.
5238
5239 @item -gnatw.e
5240 @emph{Activate every optional warning}
5241 @cindex @option{-gnatw.e} (@command{gcc})
5242 @cindex Warnings, activate every optional warning
5243 This switch activates all optional warnings, including those which
5244 are not activated by @code{-gnatwa}.
5245
5246 @item -gnatwf
5247 @emph{Activate warnings on unreferenced formals.}
5248 @cindex @option{-gnatwf} (@command{gcc})
5249 @cindex Formals, unreferenced
5250 This switch causes a warning to be generated if a formal parameter
5251 is not referenced in the body of the subprogram. This warning can
5252 also be turned on using @option{-gnatwa} or @option{-gnatwu}. The
5253 default is that these warnings are not generated.
5254
5255 @item -gnatwF
5256 @emph{Suppress warnings on unreferenced formals.}
5257 @cindex @option{-gnatwF} (@command{gcc})
5258 This switch suppresses warnings for unreferenced formal
5259 parameters. Note that the
5260 combination @option{-gnatwu} followed by @option{-gnatwF} has the
5261 effect of warning on unreferenced entities other than subprogram
5262 formals.
5263
5264 @item -gnatwg
5265 @emph{Activate warnings on unrecognized pragmas.}
5266 @cindex @option{-gnatwg} (@command{gcc})
5267 @cindex Pragmas, unrecognized
5268 This switch causes a warning to be generated if an unrecognized
5269 pragma is encountered. Apart from issuing this warning, the
5270 pragma is ignored and has no effect. This warning can
5271 also be turned on using @option{-gnatwa}. The default
5272 is that such warnings are issued (satisfying the Ada Reference
5273 Manual requirement that such warnings appear).
5274
5275 @item -gnatwG
5276 @emph{Suppress warnings on unrecognized pragmas.}
5277 @cindex @option{-gnatwG} (@command{gcc})
5278 This switch suppresses warnings for unrecognized pragmas.
5279
5280 @item -gnatwh
5281 @emph{Activate warnings on hiding.}
5282 @cindex @option{-gnatwh} (@command{gcc})
5283 @cindex Hiding of Declarations
5284 This switch activates warnings on hiding declarations.
5285 A declaration is considered hiding
5286 if it is for a non-overloadable entity, and it declares an entity with the
5287 same name as some other entity that is directly or use-visible. The default
5288 is that such warnings are not generated.
5289 Note that @option{-gnatwa} does not affect the setting of this warning option.
5290
5291 @item -gnatwH
5292 @emph{Suppress warnings on hiding.}
5293 @cindex @option{-gnatwH} (@command{gcc})
5294 This switch suppresses warnings on hiding declarations.
5295
5296 @item -gnatw.h
5297 @emph{Activate warnings on holes/gaps in records.}
5298 @cindex @option{-gnatw.h} (@command{gcc})
5299 @cindex Record Representation (gaps)
5300 This switch activates warnings on component clauses in record
5301 representation clauses that leave holes (gaps) in the record layout.
5302 If this warning option is active, then record representation clauses
5303 should specify a contiguous layout, adding unused fill fields if needed.
5304 Note that @option{-gnatwa} does not affect the setting of this warning option.
5305
5306 @item -gnatw.H
5307 @emph{Suppress warnings on holes/gaps in records.}
5308 @cindex @option{-gnatw.H} (@command{gcc})
5309 This switch suppresses warnings on component clauses in record
5310 representation clauses that leave holes (haps) in the record layout.
5311
5312 @item -gnatwi
5313 @emph{Activate warnings on implementation units.}
5314 @cindex @option{-gnatwi} (@command{gcc})
5315 This switch activates warnings for a @code{with} of an internal GNAT
5316 implementation unit, defined as any unit from the @code{Ada},
5317 @code{Interfaces}, @code{GNAT},
5318 ^^@code{DEC},^ or @code{System}
5319 hierarchies that is not
5320 documented in either the Ada Reference Manual or the GNAT
5321 Programmer's Reference Manual. Such units are intended only
5322 for internal implementation purposes and should not be @code{with}'ed
5323 by user programs. The default is that such warnings are generated
5324 This warning can also be turned on using @option{-gnatwa}.
5325
5326 @item -gnatwI
5327 @emph{Disable warnings on implementation units.}
5328 @cindex @option{-gnatwI} (@command{gcc})
5329 This switch disables warnings for a @code{with} of an internal GNAT
5330 implementation unit.
5331
5332 @item -gnatw.i
5333 @emph{Activate warnings on overlapping actuals.}
5334 @cindex @option{-gnatw.i} (@command{gcc})
5335 This switch enables a warning on statically detectable overlapping actuals in
5336 a subprogram call, when one of the actuals is an in-out parameter, and the
5337 types of the actuals are not by-copy types. The warning is off by default,
5338 and is not included under -gnatwa.
5339
5340 @item -gnatw.I
5341 @emph{Disable warnings on overlapping actuals.}
5342 @cindex @option{-gnatw.I} (@command{gcc})
5343 This switch disables warnings on overlapping actuals in a call..
5344
5345 @item -gnatwj
5346 @emph{Activate warnings on obsolescent features (Annex J).}
5347 @cindex @option{-gnatwj} (@command{gcc})
5348 @cindex Features, obsolescent
5349 @cindex Obsolescent features
5350 If this warning option is activated, then warnings are generated for
5351 calls to subprograms marked with @code{pragma Obsolescent} and
5352 for use of features in Annex J of the Ada Reference Manual. In the
5353 case of Annex J, not all features are flagged. In particular use
5354 of the renamed packages (like @code{Text_IO}) and use of package
5355 @code{ASCII} are not flagged, since these are very common and
5356 would generate many annoying positive warnings. The default is that
5357 such warnings are not generated. This warning is also turned on by
5358 the use of @option{-gnatwa}.
5359
5360 In addition to the above cases, warnings are also generated for
5361 GNAT features that have been provided in past versions but which
5362 have been superseded (typically by features in the new Ada standard).
5363 For example, @code{pragma Ravenscar} will be flagged since its
5364 function is replaced by @code{pragma Profile(Ravenscar)}.
5365
5366 Note that this warning option functions differently from the
5367 restriction @code{No_Obsolescent_Features} in two respects.
5368 First, the restriction applies only to annex J features.
5369 Second, the restriction does flag uses of package @code{ASCII}.
5370
5371 @item -gnatwJ
5372 @emph{Suppress warnings on obsolescent features (Annex J).}
5373 @cindex @option{-gnatwJ} (@command{gcc})
5374 This switch disables warnings on use of obsolescent features.
5375
5376 @item -gnatwk
5377 @emph{Activate warnings on variables that could be constants.}
5378 @cindex @option{-gnatwk} (@command{gcc})
5379 This switch activates warnings for variables that are initialized but
5380 never modified, and then could be declared constants. The default is that
5381 such warnings are not given.
5382 This warning can also be turned on using @option{-gnatwa}.
5383
5384 @item -gnatwK
5385 @emph{Suppress warnings on variables that could be constants.}
5386 @cindex @option{-gnatwK} (@command{gcc})
5387 This switch disables warnings on variables that could be declared constants.
5388
5389 @item -gnatwl
5390 @emph{Activate warnings for elaboration pragmas.}
5391 @cindex @option{-gnatwl} (@command{gcc})
5392 @cindex Elaboration, warnings
5393 This switch activates warnings on missing
5394 @code{Elaborate_All} and @code{Elaborate} pragmas.
5395 See the section in this guide on elaboration checking for details on
5396 when such pragmas should be used. In dynamic elaboration mode, this switch
5397 generations warnings about the need to add elaboration pragmas. Note however,
5398 that if you blindly follow these warnings, and add @code{Elaborate_All}
5399 warnings wherever they are recommended, you basically end up with the
5400 equivalent of the static elaboration model, which may not be what you want for
5401 legacy code for which the static model does not work.
5402
5403 For the static model, the messages generated are labeled "info:" (for
5404 information messages). They are not warnings to add elaboration pragmas,
5405 merely informational messages showing what implicit elaboration pragmas
5406 have been added, for use in analyzing elaboration circularity problems.
5407
5408 Warnings are also generated if you
5409 are using the static mode of elaboration, and a @code{pragma Elaborate}
5410 is encountered. The default is that such warnings
5411 are not generated.
5412 This warning is not automatically turned on by the use of @option{-gnatwa}.
5413
5414 @item -gnatwL
5415 @emph{Suppress warnings for elaboration pragmas.}
5416 @cindex @option{-gnatwL} (@command{gcc})
5417 This switch suppresses warnings on missing Elaborate and Elaborate_All pragmas.
5418 See the section in this guide on elaboration checking for details on
5419 when such pragmas should be used.
5420
5421 @item -gnatwm
5422 @emph{Activate warnings on modified but unreferenced variables.}
5423 @cindex @option{-gnatwm} (@command{gcc})
5424 This switch activates warnings for variables that are assigned (using
5425 an initialization value or with one or more assignment statements) but
5426 whose value is never read. The warning is suppressed for volatile
5427 variables and also for variables that are renamings of other variables
5428 or for which an address clause is given.
5429 This warning can also be turned on using @option{-gnatwa}.
5430 The default is that these warnings are not given.
5431
5432 @item -gnatwM
5433 @emph{Disable warnings on modified but unreferenced variables.}
5434 @cindex @option{-gnatwM} (@command{gcc})
5435 This switch disables warnings for variables that are assigned or
5436 initialized, but never read.
5437
5438 @item -gnatw.m
5439 @emph{Activate warnings on suspicious modulus values.}
5440 @cindex @option{-gnatw.m} (@command{gcc})
5441 This switch activates warnings for modulus values that seem suspicious.
5442 The cases caught are where the size is the same as the modulus (e.g.
5443 a modulus of 7 with a size of 7 bits), and modulus values of 32 or 64
5444 with no size clause. The guess in both cases is that 2**x was intended
5445 rather than x. The default is that these warnings are given.
5446
5447 @item -gnatw.M
5448 @emph{Disable warnings on suspicious modulus values.}
5449 @cindex @option{-gnatw.M} (@command{gcc})
5450 This switch disables warnings for suspicious modulus values.
5451
5452 @item -gnatwn
5453 @emph{Set normal warnings mode.}
5454 @cindex @option{-gnatwn} (@command{gcc})
5455 This switch sets normal warning mode, in which enabled warnings are
5456 issued and treated as warnings rather than errors. This is the default
5457 mode. the switch @option{-gnatwn} can be used to cancel the effect of
5458 an explicit @option{-gnatws} or
5459 @option{-gnatwe}. It also cancels the effect of the
5460 implicit @option{-gnatwe} that is activated by the
5461 use of @option{-gnatg}.
5462
5463 @item -gnatwo
5464 @emph{Activate warnings on address clause overlays.}
5465 @cindex @option{-gnatwo} (@command{gcc})
5466 @cindex Address Clauses, warnings
5467 This switch activates warnings for possibly unintended initialization
5468 effects of defining address clauses that cause one variable to overlap
5469 another. The default is that such warnings are generated.
5470 This warning can also be turned on using @option{-gnatwa}.
5471
5472 @item -gnatwO
5473 @emph{Suppress warnings on address clause overlays.}
5474 @cindex @option{-gnatwO} (@command{gcc})
5475 This switch suppresses warnings on possibly unintended initialization
5476 effects of defining address clauses that cause one variable to overlap
5477 another.
5478
5479 @item -gnatw.o
5480 @emph{Activate warnings on modified but unreferenced out parameters.}
5481 @cindex @option{-gnatw.o} (@command{gcc})
5482 This switch activates warnings for variables that are modified by using
5483 them as actuals for a call to a procedure with an out mode formal, where
5484 the resulting assigned value is never read. It is applicable in the case
5485 where there is more than one out mode formal. If there is only one out
5486 mode formal, the warning is issued by default (controlled by -gnatwu).
5487 The warning is suppressed for volatile
5488 variables and also for variables that are renamings of other variables
5489 or for which an address clause is given.
5490 The default is that these warnings are not given. Note that this warning
5491 is not included in -gnatwa, it must be activated explicitly.
5492
5493 @item -gnatw.O
5494 @emph{Disable warnings on modified but unreferenced out parameters.}
5495 @cindex @option{-gnatw.O} (@command{gcc})
5496 This switch suppresses warnings for variables that are modified by using
5497 them as actuals for a call to a procedure with an out mode formal, where
5498 the resulting assigned value is never read.
5499
5500 @item -gnatwp
5501 @emph{Activate warnings on ineffective pragma Inlines.}
5502 @cindex @option{-gnatwp} (@command{gcc})
5503 @cindex Inlining, warnings
5504 This switch activates warnings for failure of front end inlining
5505 (activated by @option{-gnatN}) to inline a particular call. There are
5506 many reasons for not being able to inline a call, including most
5507 commonly that the call is too complex to inline. The default is
5508 that such warnings are not given.
5509 This warning can also be turned on using @option{-gnatwa}.
5510 Warnings on ineffective inlining by the gcc back-end can be activated
5511 separately, using the gcc switch -Winline.
5512
5513 @item -gnatwP
5514 @emph{Suppress warnings on ineffective pragma Inlines.}
5515 @cindex @option{-gnatwP} (@command{gcc})
5516 This switch suppresses warnings on ineffective pragma Inlines. If the
5517 inlining mechanism cannot inline a call, it will simply ignore the
5518 request silently.
5519
5520 @item -gnatw.p
5521 @emph{Activate warnings on parameter ordering.}
5522 @cindex @option{-gnatw.p} (@command{gcc})
5523 @cindex Parameter order, warnings
5524 This switch activates warnings for cases of suspicious parameter
5525 ordering when the list of arguments are all simple identifiers that
5526 match the names of the formals, but are in a different order. The
5527 warning is suppressed if any use of named parameter notation is used,
5528 so this is the appropriate way to suppress a false positive (and
5529 serves to emphasize that the "misordering" is deliberate). The
5530 default is
5531 that such warnings are not given.
5532 This warning can also be turned on using @option{-gnatwa}.
5533
5534 @item -gnatw.P
5535 @emph{Suppress warnings on parameter ordering.}
5536 @cindex @option{-gnatw.P} (@command{gcc})
5537 This switch suppresses warnings on cases of suspicious parameter
5538 ordering.
5539
5540 @item -gnatwq
5541 @emph{Activate warnings on questionable missing parentheses.}
5542 @cindex @option{-gnatwq} (@command{gcc})
5543 @cindex Parentheses, warnings
5544 This switch activates warnings for cases where parentheses are not used and
5545 the result is potential ambiguity from a readers point of view. For example
5546 (not a > b) when a and b are modular means ((not a) > b) and very likely the
5547 programmer intended (not (a > b)). Similarly (-x mod 5) means (-(x mod 5)) and
5548 quite likely ((-x) mod 5) was intended. In such situations it seems best to
5549 follow the rule of always parenthesizing to make the association clear, and
5550 this warning switch warns if such parentheses are not present. The default
5551 is that these warnings are given.
5552 This warning can also be turned on using @option{-gnatwa}.
5553
5554 @item -gnatwQ
5555 @emph{Suppress warnings on questionable missing parentheses.}
5556 @cindex @option{-gnatwQ} (@command{gcc})
5557 This switch suppresses warnings for cases where the association is not
5558 clear and the use of parentheses is preferred.
5559
5560 @item -gnatwr
5561 @emph{Activate warnings on redundant constructs.}
5562 @cindex @option{-gnatwr} (@command{gcc})
5563 This switch activates warnings for redundant constructs. The following
5564 is the current list of constructs regarded as redundant:
5565
5566 @itemize @bullet
5567 @item
5568 Assignment of an item to itself.
5569 @item
5570 Type conversion that converts an expression to its own type.
5571 @item
5572 Use of the attribute @code{Base} where @code{typ'Base} is the same
5573 as @code{typ}.
5574 @item
5575 Use of pragma @code{Pack} when all components are placed by a record
5576 representation clause.
5577 @item
5578 Exception handler containing only a reraise statement (raise with no
5579 operand) which has no effect.
5580 @item
5581 Use of the operator abs on an operand that is known at compile time
5582 to be non-negative
5583 @item
5584 Comparison of boolean expressions to an explicit True value.
5585 @end itemize
5586
5587 This warning can also be turned on using @option{-gnatwa}.
5588 The default is that warnings for redundant constructs are not given.
5589
5590 @item -gnatwR
5591 @emph{Suppress warnings on redundant constructs.}
5592 @cindex @option{-gnatwR} (@command{gcc})
5593 This switch suppresses warnings for redundant constructs.
5594
5595 @item -gnatw.r
5596 @emph{Activate warnings for object renaming function.}
5597 @cindex @option{-gnatw.r} (@command{gcc})
5598 This switch activates warnings for an object renaming that renames a
5599 function call, which is equivalent to a constant declaration (as
5600 opposed to renaming the function itself).  The default is that these
5601 warnings are given.  This warning can also be turned on using
5602 @option{-gnatwa}.
5603
5604 @item -gnatw.R
5605 @emph{Suppress warnings for object renaming function.}
5606 @cindex @option{-gnatwT} (@command{gcc})
5607 This switch suppresses warnings for object renaming function.
5608
5609 @item -gnatws
5610 @emph{Suppress all warnings.}
5611 @cindex @option{-gnatws} (@command{gcc})
5612 This switch completely suppresses the
5613 output of all warning messages from the GNAT front end.
5614 Note that it does not suppress warnings from the @command{gcc} back end.
5615 To suppress these back end warnings as well, use the switch @option{-w}
5616 in addition to @option{-gnatws}. Also this switch has no effect on the
5617 handling of style check messages.
5618
5619 @item -gnatw.s
5620 @emph{Activate warnings on overridden size clauses.}
5621 @cindex @option{-gnatw.s} (@command{gcc})
5622 @cindex Record Representation (component sizes)
5623 This switch activates warnings on component clauses in record
5624 representation clauses where the length given overrides that
5625 specified by an explicit size clause for the component type. A
5626 warning is similarly given in the array case if a specified
5627 component size overrides an explicit size clause for the array
5628 component type.
5629 Note that @option{-gnatwa} does not affect the setting of this warning option.
5630
5631 @item -gnatw.S
5632 @emph{Suppress warnings on overridden size clauses.}
5633 @cindex @option{-gnatw.S} (@command{gcc})
5634 This switch suppresses warnings on component clauses in record
5635 representation clauses that override size clauses, and similar
5636 warnings when an array component size overrides a size clause.
5637
5638 @item -gnatwt
5639 @emph{Activate warnings for tracking of deleted conditional code.}
5640 @cindex @option{-gnatwt} (@command{gcc})
5641 @cindex Deactivated code, warnings
5642 @cindex Deleted code, warnings
5643 This switch activates warnings for tracking of code in conditionals (IF and
5644 CASE statements) that is detected to be dead code which cannot be executed, and
5645 which is removed by the front end. This warning is off by default, and is not
5646 turned on by @option{-gnatwa}, it has to be turned on explicitly. This may be
5647 useful for detecting deactivated code in certified applications.
5648
5649 @item -gnatwT
5650 @emph{Suppress warnings for tracking of deleted conditional code.}
5651 @cindex @option{-gnatwT} (@command{gcc})
5652 This switch suppresses warnings for tracking of deleted conditional code.
5653
5654 @item -gnatwu
5655 @emph{Activate warnings on unused entities.}
5656 @cindex @option{-gnatwu} (@command{gcc})
5657 This switch activates warnings to be generated for entities that
5658 are declared but not referenced, and for units that are @code{with}'ed
5659 and not
5660 referenced. In the case of packages, a warning is also generated if
5661 no entities in the package are referenced. This means that if the package
5662 is referenced but the only references are in @code{use}
5663 clauses or @code{renames}
5664 declarations, a warning is still generated. A warning is also generated
5665 for a generic package that is @code{with}'ed but never instantiated.
5666 In the case where a package or subprogram body is compiled, and there
5667 is a @code{with} on the corresponding spec
5668 that is only referenced in the body,
5669 a warning is also generated, noting that the
5670 @code{with} can be moved to the body. The default is that
5671 such warnings are not generated.
5672 This switch also activates warnings on unreferenced formals
5673 (it includes the effect of @option{-gnatwf}).
5674 This warning can also be turned on using @option{-gnatwa}.
5675
5676 @item -gnatwU
5677 @emph{Suppress warnings on unused entities.}
5678 @cindex @option{-gnatwU} (@command{gcc})
5679 This switch suppresses warnings for unused entities and packages.
5680 It also turns off warnings on unreferenced formals (and thus includes
5681 the effect of @option{-gnatwF}).
5682
5683 @item -gnatw.u
5684 @emph{Activate warnings on unordered enumeration types.}
5685 @cindex @option{-gnatw.u} (@command{gcc})
5686 This switch causes enumeration types to be considered as conceptually
5687 unordered, unless an explicit pragma @code{Ordered} is given for the type.
5688 The effect is to generate warnings in clients that use explicit comparisons
5689 or subranges, since these constructs both treat objects of the type as
5690 ordered. (A @emph{client} is defined as a unit that is other than the unit in
5691 which the type is declared, or its body or subunits.) Please refer to
5692 the description of pragma @code{Ordered} in the
5693 @cite{@value{EDITION} Reference Manual} for further details.
5694
5695 @item -gnatw.U
5696 @emph{Deactivate warnings on unordered enumeration types.}
5697 @cindex @option{-gnatw.U} (@command{gcc})
5698 This switch causes all enumeration types to be considered as ordered, so
5699 that no warnings are given for comparisons or subranges for any type.
5700
5701 @item -gnatwv
5702 @emph{Activate warnings on unassigned variables.}
5703 @cindex @option{-gnatwv} (@command{gcc})
5704 @cindex Unassigned variable warnings
5705 This switch activates warnings for access to variables which
5706 may not be properly initialized. The default is that
5707 such warnings are generated.
5708 This warning can also be turned on using @option{-gnatwa}.
5709
5710 @item -gnatwV
5711 @emph{Suppress warnings on unassigned variables.}
5712 @cindex @option{-gnatwV} (@command{gcc})
5713 This switch suppresses warnings for access to variables which
5714 may not be properly initialized.
5715 For variables of a composite type, the warning can also be suppressed in
5716 Ada 2005 by using a default initialization with a box. For example, if
5717 Table is an array of records whose components are only partially uninitialized,
5718 then the following code:
5719
5720 @smallexample @c ada
5721    Tab : Table := (others => <>);
5722 @end smallexample
5723
5724 will suppress warnings on subsequent statements that access components
5725 of variable Tab.
5726
5727 @item -gnatww
5728 @emph{Activate warnings on wrong low bound assumption.}
5729 @cindex @option{-gnatww} (@command{gcc})
5730 @cindex String indexing warnings
5731 This switch activates warnings for indexing an unconstrained string parameter
5732 with a literal or S'Length. This is a case where the code is assuming that the
5733 low bound is one, which is in general not true (for example when a slice is
5734 passed). The default is that such warnings are generated.
5735 This warning can also be turned on using @option{-gnatwa}.
5736
5737 @item -gnatwW
5738 @emph{Suppress warnings on wrong low bound assumption.}
5739 @cindex @option{-gnatwW} (@command{gcc})
5740 This switch suppresses warnings for indexing an unconstrained string parameter
5741 with a literal or S'Length. Note that this warning can also be suppressed
5742 in a particular case by adding an
5743 assertion that the lower bound is 1,
5744 as shown in the following example.
5745
5746 @smallexample @c ada
5747    procedure K (S : String) is
5748       pragma Assert (S'First = 1);
5749       @dots{}
5750 @end smallexample
5751
5752 @item -gnatw.w
5753 @emph{Activate warnings on unnecessary Warnings Off pragmas}
5754 @cindex @option{-gnatw.w} (@command{gcc})
5755 @cindex Warnings Off control
5756 This switch activates warnings for use of @code{pragma Warnings (Off, entity)}
5757 where either the pragma is entirely useless (because it suppresses no
5758 warnings), or it could be replaced by @code{pragma Unreferenced} or
5759 @code{pragma Unmodified}. The default is that these warnings are not given.
5760 Note that this warning is not included in -gnatwa, it must be
5761 activated explicitly.
5762
5763 @item -gnatw.W
5764 @emph{Suppress warnings on unnecessary Warnings Off pragmas}
5765 @cindex @option{-gnatw.W} (@command{gcc})
5766 This switch suppresses warnings for use of @code{pragma Warnings (Off, entity)}.
5767
5768 @item -gnatwx
5769 @emph{Activate warnings on Export/Import pragmas.}
5770 @cindex @option{-gnatwx} (@command{gcc})
5771 @cindex Export/Import pragma warnings
5772 This switch activates warnings on Export/Import pragmas when
5773 the compiler detects a possible conflict between the Ada and
5774 foreign language calling sequences. For example, the use of
5775 default parameters in a convention C procedure is dubious
5776 because the C compiler cannot supply the proper default, so
5777 a warning is issued. The default is that such warnings are
5778 generated.
5779 This warning can also be turned on using @option{-gnatwa}.
5780
5781 @item -gnatwX
5782 @emph{Suppress warnings on Export/Import pragmas.}
5783 @cindex @option{-gnatwX} (@command{gcc})
5784 This switch suppresses warnings on Export/Import pragmas.
5785 The sense of this is that you are telling the compiler that
5786 you know what you are doing in writing the pragma, and it
5787 should not complain at you.
5788
5789 @item -gnatw.x
5790 @emph{Activate warnings for No_Exception_Propagation mode.}
5791 @cindex @option{-gnatwm} (@command{gcc})
5792 This switch activates warnings for exception usage when pragma Restrictions
5793 (No_Exception_Propagation) is in effect. Warnings are given for implicit or
5794 explicit exception raises which are not covered by a local handler, and for
5795 exception handlers which do not cover a local raise. The default is that these
5796 warnings are not given.
5797
5798 @item -gnatw.X
5799 @emph{Disable warnings for No_Exception_Propagation mode.}
5800 This switch disables warnings for exception usage when pragma Restrictions
5801 (No_Exception_Propagation) is in effect.
5802
5803 @item -gnatwy
5804 @emph{Activate warnings for Ada compatibility issues.}
5805 @cindex @option{-gnatwy} (@command{gcc})
5806 @cindex Ada compatibility issues warnings
5807 For the most part, newer versions of Ada are upwards compatible
5808 with older versions. For example, Ada 2005 programs will almost
5809 always work when compiled as Ada 2012.
5810 However there are some exceptions (for example the fact that
5811 @code{some} is now a reserved word in Ada 2012). This
5812 switch activates several warnings to help in identifying
5813 and correcting such incompatibilities. The default is that
5814 these warnings are generated. Note that at one point Ada 2005
5815 was called Ada 0Y, hence the choice of character.
5816 This warning can also be turned on using @option{-gnatwa}.
5817
5818 @item -gnatwY
5819 @emph{Disable warnings for Ada compatibility issues.}
5820 @cindex @option{-gnatwY} (@command{gcc})
5821 @cindex Ada compatibility issues warnings
5822 This switch suppresses the warnings intended to help in identifying
5823 incompatibilities between Ada language versions.
5824
5825 @item -gnatwz
5826 @emph{Activate warnings on unchecked conversions.}
5827 @cindex @option{-gnatwz} (@command{gcc})
5828 @cindex Unchecked_Conversion warnings
5829 This switch activates warnings for unchecked conversions
5830 where the types are known at compile time to have different
5831 sizes. The default
5832 is that such warnings are generated. Warnings are also
5833 generated for subprogram pointers with different conventions,
5834 and, on VMS only, for data pointers with different conventions.
5835 This warning can also be turned on using @option{-gnatwa}.
5836
5837 @item -gnatwZ
5838 @emph{Suppress warnings on unchecked conversions.}
5839 @cindex @option{-gnatwZ} (@command{gcc})
5840 This switch suppresses warnings for unchecked conversions
5841 where the types are known at compile time to have different
5842 sizes or conventions.
5843
5844 @item ^-Wunused^WARNINGS=UNUSED^
5845 @cindex @option{-Wunused}
5846 The warnings controlled by the @option{-gnatw} switch are generated by
5847 the front end of the compiler. The @option{GCC} back end can provide
5848 additional warnings and they are controlled by the @option{-W} switch.
5849 For example, @option{^-Wunused^WARNINGS=UNUSED^} activates back end
5850 warnings for entities that are declared but not referenced.
5851
5852 @item ^-Wuninitialized^WARNINGS=UNINITIALIZED^
5853 @cindex @option{-Wuninitialized}
5854 Similarly, @option{^-Wuninitialized^WARNINGS=UNINITIALIZED^} activates
5855 the back end warning for uninitialized variables. This switch must be
5856 used in conjunction with an optimization level greater than zero.
5857
5858 @item -Wstack-usage=@var{len}
5859 @cindex @option{-Wstack-usage}
5860 Warn if the stack usage of a subprogram might be larger than @var{len} bytes.
5861 See @ref{Static Stack Usage Analysis} for details.
5862
5863 @item ^-Wall^/ALL_BACK_END_WARNINGS^
5864 @cindex @option{-Wall}
5865 This switch enables most warnings from the @option{GCC} back end.
5866 The code generator detects a number of warning situations that are missed
5867 by the @option{GNAT} front end, and this switch can be used to activate them.
5868 The use of this switch also sets the default front end warning mode to
5869 @option{-gnatwa}, that is, most front end warnings activated as well.
5870
5871 @item ^-w^/NO_BACK_END_WARNINGS^
5872 @cindex @option{-w}
5873 Conversely, this switch suppresses warnings from the @option{GCC} back end.
5874 The use of this switch also sets the default front end warning mode to
5875 @option{-gnatws}, that is, front end warnings suppressed as well.
5876
5877 @end table
5878
5879 @noindent
5880 @ifclear vms
5881 A string of warning parameters can be used in the same parameter. For example:
5882
5883 @smallexample
5884 -gnatwaLe
5885 @end smallexample
5886
5887 @noindent
5888 will turn on all optional warnings except for elaboration pragma warnings,
5889 and also specify that warnings should be treated as errors.
5890 @end ifclear
5891 When no switch @option{^-gnatw^/WARNINGS^} is used, this is equivalent to:
5892
5893 @table @option
5894 @c !sort!
5895 @item -gnatwC
5896 @item -gnatwD
5897 @item -gnatwF
5898 @item -gnatwg
5899 @item -gnatwH
5900 @item -gnatwi
5901 @item -gnatwJ
5902 @item -gnatwK
5903 @item -gnatwL
5904 @item -gnatwM
5905 @item -gnatwn
5906 @item -gnatwo
5907 @item -gnatwP
5908 @item -gnatwR
5909 @item -gnatwU
5910 @item -gnatwv
5911 @item -gnatwz
5912 @item -gnatwx
5913
5914 @end table
5915
5916 @node Debugging and Assertion Control
5917 @subsection Debugging and Assertion Control
5918
5919 @table @option
5920 @item -gnata
5921 @cindex @option{-gnata} (@command{gcc})
5922 @findex Assert
5923 @findex Debug
5924 @cindex Assertions
5925
5926 @noindent
5927 The pragmas @code{Assert} and @code{Debug} normally have no effect and
5928 are ignored. This switch, where @samp{a} stands for assert, causes
5929 @code{Assert} and @code{Debug} pragmas to be activated.
5930
5931 The pragmas have the form:
5932
5933 @smallexample
5934 @cartouche
5935    @b{pragma} Assert (@var{Boolean-expression} @r{[},
5936                       @var{static-string-expression}@r{]})
5937    @b{pragma} Debug (@var{procedure call})
5938 @end cartouche
5939 @end smallexample
5940
5941 @noindent
5942 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
5943 If the result is @code{True}, the pragma has no effect (other than
5944 possible side effects from evaluating the expression). If the result is
5945 @code{False}, the exception @code{Assert_Failure} declared in the package
5946 @code{System.Assertions} is
5947 raised (passing @var{static-string-expression}, if present, as the
5948 message associated with the exception). If no string expression is
5949 given the default is a string giving the file name and line number
5950 of the pragma.
5951
5952 The @code{Debug} pragma causes @var{procedure} to be called. Note that
5953 @code{pragma Debug} may appear within a declaration sequence, allowing
5954 debugging procedures to be called between declarations.
5955
5956 @ifset vms
5957 @item /DEBUG@r{[}=debug-level@r{]}
5958 @itemx  /NODEBUG
5959 Specifies how much debugging information is to be included in
5960 the resulting object file where 'debug-level' is one of the following:
5961 @table @code
5962 @item   TRACEBACK
5963 Include both debugger symbol records and traceback
5964 the object file.
5965 This is the default setting.
5966 @item   ALL
5967 Include both debugger symbol records and traceback in
5968 object file.
5969 @item   NONE
5970 Excludes both debugger symbol records and traceback
5971 the object file. Same as /NODEBUG.
5972 @item   SYMBOLS
5973 Includes only debugger symbol records in the object
5974 file. Note that this doesn't include traceback information.
5975 @end table
5976 @end ifset
5977 @end table
5978
5979 @node Validity Checking
5980 @subsection Validity Checking
5981 @findex Validity Checking
5982
5983 @noindent
5984 The Ada Reference Manual defines the concept of invalid values (see
5985 RM 13.9.1). The primary source of invalid values is uninitialized
5986 variables. A scalar variable that is left uninitialized may contain
5987 an invalid value; the concept of invalid does not apply to access or
5988 composite types.
5989
5990 It is an error to read an invalid value, but the RM does not require
5991 run-time checks to detect such errors, except for some minimal
5992 checking to prevent erroneous execution (i.e. unpredictable
5993 behavior). This corresponds to the @option{-gnatVd} switch below,
5994 which is the default. For example, by default, if the expression of a
5995 case statement is invalid, it will raise Constraint_Error rather than
5996 causing a wild jump, and if an array index on the left-hand side of an
5997 assignment is invalid, it will raise Constraint_Error rather than
5998 overwriting an arbitrary memory location.
5999
6000 The @option{-gnatVa} may be used to enable additional validity checks,
6001 which are not required by the RM. These checks are often very
6002 expensive (which is why the RM does not require them). These checks
6003 are useful in tracking down uninitialized variables, but they are
6004 not usually recommended for production builds.
6005
6006 The other @option{-gnatV^@var{x}^^} switches below allow finer-grained
6007 control; you can enable whichever validity checks you desire. However,
6008 for most debugging purposes, @option{-gnatVa} is sufficient, and the
6009 default @option{-gnatVd} (i.e. standard Ada behavior) is usually
6010 sufficient for non-debugging use.
6011
6012 The @option{-gnatB} switch tells the compiler to assume that all
6013 values are valid (that is, within their declared subtype range)
6014 except in the context of a use of the Valid attribute. This means
6015 the compiler can generate more efficient code, since the range
6016 of values is better known at compile time. However, an uninitialized
6017 variable can cause wild jumps and memory corruption in this mode.
6018
6019 The @option{-gnatV^@var{x}^^} switch allows control over the validity
6020 checking mode as described below.
6021 @ifclear vms
6022 The @code{x} argument is a string of letters that
6023 indicate validity checks that are performed or not performed in addition
6024 to the default checks required by Ada as described above.
6025 @end ifclear
6026 @ifset vms
6027 The options allowed for this qualifier
6028 indicate validity checks that are performed or not performed in addition
6029 to the default checks required by Ada as described above.
6030 @end ifset
6031
6032 @table @option
6033 @c !sort!
6034 @item -gnatVa
6035 @emph{All validity checks.}
6036 @cindex @option{-gnatVa} (@command{gcc})
6037 All validity checks are turned on.
6038 @ifclear vms
6039 That is, @option{-gnatVa} is
6040 equivalent to @option{gnatVcdfimorst}.
6041 @end ifclear
6042
6043 @item -gnatVc
6044 @emph{Validity checks for copies.}
6045 @cindex @option{-gnatVc} (@command{gcc})
6046 The right hand side of assignments, and the initializing values of
6047 object declarations are validity checked.
6048
6049 @item -gnatVd
6050 @emph{Default (RM) validity checks.}
6051 @cindex @option{-gnatVd} (@command{gcc})
6052 Some validity checks are done by default following normal Ada semantics
6053 (RM 13.9.1 (9-11)).
6054 A check is done in case statements that the expression is within the range
6055 of the subtype. If it is not, Constraint_Error is raised.
6056 For assignments to array components, a check is done that the expression used
6057 as index is within the range. If it is not, Constraint_Error is raised.
6058 Both these validity checks may be turned off using switch @option{-gnatVD}.
6059 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
6060 switch @option{-gnatVd} will leave the checks turned on.
6061 Switch @option{-gnatVD} should be used only if you are sure that all such
6062 expressions have valid values. If you use this switch and invalid values
6063 are present, then the program is erroneous, and wild jumps or memory
6064 overwriting may occur.
6065
6066 @item -gnatVe
6067 @emph{Validity checks for elementary components.}
6068 @cindex @option{-gnatVe} (@command{gcc})
6069 In the absence of this switch, assignments to record or array components are
6070 not validity checked, even if validity checks for assignments generally
6071 (@option{-gnatVc}) are turned on. In Ada, assignment of composite values do not
6072 require valid data, but assignment of individual components does. So for
6073 example, there is a difference between copying the elements of an array with a
6074 slice assignment, compared to assigning element by element in a loop. This
6075 switch allows you to turn off validity checking for components, even when they
6076 are assigned component by component.
6077
6078 @item -gnatVf
6079 @emph{Validity checks for floating-point values.}
6080 @cindex @option{-gnatVf} (@command{gcc})
6081 In the absence of this switch, validity checking occurs only for discrete
6082 values. If @option{-gnatVf} is specified, then validity checking also applies
6083 for floating-point values, and NaNs and infinities are considered invalid,
6084 as well as out of range values for constrained types. Note that this means
6085 that standard IEEE infinity mode is not allowed. The exact contexts
6086 in which floating-point values are checked depends on the setting of other
6087 options. For example,
6088 @option{^-gnatVif^VALIDITY_CHECKING=(IN_PARAMS,FLOATS)^} or
6089 @option{^-gnatVfi^VALIDITY_CHECKING=(FLOATS,IN_PARAMS)^}
6090 (the order does not matter) specifies that floating-point parameters of mode
6091 @code{in} should be validity checked.
6092
6093 @item -gnatVi
6094 @emph{Validity checks for @code{in} mode parameters}
6095 @cindex @option{-gnatVi} (@command{gcc})
6096 Arguments for parameters of mode @code{in} are validity checked in function
6097 and procedure calls at the point of call.
6098
6099 @item -gnatVm
6100 @emph{Validity checks for @code{in out} mode parameters.}
6101 @cindex @option{-gnatVm} (@command{gcc})
6102 Arguments for parameters of mode @code{in out} are validity checked in
6103 procedure calls at the point of call. The @code{'m'} here stands for
6104 modify, since this concerns parameters that can be modified by the call.
6105 Note that there is no specific option to test @code{out} parameters,
6106 but any reference within the subprogram will be tested in the usual
6107 manner, and if an invalid value is copied back, any reference to it
6108 will be subject to validity checking.
6109
6110 @item -gnatVn
6111 @emph{No validity checks.}
6112 @cindex @option{-gnatVn} (@command{gcc})
6113 This switch turns off all validity checking, including the default checking
6114 for case statements and left hand side subscripts. Note that the use of
6115 the switch @option{-gnatp} suppresses all run-time checks, including
6116 validity checks, and thus implies @option{-gnatVn}. When this switch
6117 is used, it cancels any other @option{-gnatV} previously issued.
6118
6119 @item -gnatVo
6120 @emph{Validity checks for operator and attribute operands.}
6121 @cindex @option{-gnatVo} (@command{gcc})
6122 Arguments for predefined operators and attributes are validity checked.
6123 This includes all operators in package @code{Standard},
6124 the shift operators defined as intrinsic in package @code{Interfaces}
6125 and operands for attributes such as @code{Pos}. Checks are also made
6126 on individual component values for composite comparisons, and on the
6127 expressions in type conversions and qualified expressions. Checks are
6128 also made on explicit ranges using @samp{..} (e.g.@: slices, loops etc).
6129
6130 @item -gnatVp
6131 @emph{Validity checks for parameters.}
6132 @cindex @option{-gnatVp} (@command{gcc})
6133 This controls the treatment of parameters within a subprogram (as opposed
6134 to @option{-gnatVi} and @option{-gnatVm} which control validity testing
6135 of parameters on a call. If either of these call options is used, then
6136 normally an assumption is made within a subprogram that the input arguments
6137 have been validity checking at the point of call, and do not need checking
6138 again within a subprogram). If @option{-gnatVp} is set, then this assumption
6139 is not made, and parameters are not assumed to be valid, so their validity
6140 will be checked (or rechecked) within the subprogram.
6141
6142 @item -gnatVr
6143 @emph{Validity checks for function returns.}
6144 @cindex @option{-gnatVr} (@command{gcc})
6145 The expression in @code{return} statements in functions is validity
6146 checked.
6147
6148 @item -gnatVs
6149 @emph{Validity checks for subscripts.}
6150 @cindex @option{-gnatVs} (@command{gcc})
6151 All subscripts expressions are checked for validity, whether they appear
6152 on the right side or left side (in default mode only left side subscripts
6153 are validity checked).
6154
6155 @item -gnatVt
6156 @emph{Validity checks for tests.}
6157 @cindex @option{-gnatVt} (@command{gcc})
6158 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
6159 statements are checked, as well as guard expressions in entry calls.
6160
6161 @end table
6162
6163 @noindent
6164 The @option{-gnatV} switch may be followed by
6165 ^a string of letters^a list of options^
6166 to turn on a series of validity checking options.
6167 For example,
6168 @option{^-gnatVcr^/VALIDITY_CHECKING=(COPIES, RETURNS)^}
6169 specifies that in addition to the default validity checking, copies and
6170 function return expressions are to be validity checked.
6171 In order to make it easier
6172 to specify the desired combination of effects,
6173 @ifclear vms
6174 the upper case letters @code{CDFIMORST} may
6175 be used to turn off the corresponding lower case option.
6176 @end ifclear
6177 @ifset vms
6178 the prefix @code{NO} on an option turns off the corresponding validity
6179 checking:
6180 @itemize @bullet
6181 @item @code{NOCOPIES}
6182 @item @code{NODEFAULT}
6183 @item @code{NOFLOATS}
6184 @item @code{NOIN_PARAMS}
6185 @item @code{NOMOD_PARAMS}
6186 @item @code{NOOPERANDS}
6187 @item @code{NORETURNS}
6188 @item @code{NOSUBSCRIPTS}
6189 @item @code{NOTESTS}
6190 @end itemize
6191 @end ifset
6192 Thus
6193 @option{^-gnatVaM^/VALIDITY_CHECKING=(ALL, NOMOD_PARAMS)^}
6194 turns on all validity checking options except for
6195 checking of @code{@b{in out}} procedure arguments.
6196
6197 The specification of additional validity checking generates extra code (and
6198 in the case of @option{-gnatVa} the code expansion can be substantial).
6199 However, these additional checks can be very useful in detecting
6200 uninitialized variables, incorrect use of unchecked conversion, and other
6201 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
6202 is useful in conjunction with the extra validity checking, since this
6203 ensures that wherever possible uninitialized variables have invalid values.
6204
6205 See also the pragma @code{Validity_Checks} which allows modification of
6206 the validity checking mode at the program source level, and also allows for
6207 temporary disabling of validity checks.
6208
6209 @node Style Checking
6210 @subsection Style Checking
6211 @findex Style checking
6212
6213 @noindent
6214 The @option{-gnaty^x^(option,option,@dots{})^} switch
6215 @cindex @option{-gnaty} (@command{gcc})
6216 causes the compiler to
6217 enforce specified style rules. A limited set of style rules has been used
6218 in writing the GNAT sources themselves. This switch allows user programs
6219 to activate all or some of these checks. If the source program fails a
6220 specified style check, an appropriate message is given, preceded by
6221 the character sequence ``(style)''. This message does not prevent
6222 successful compilation (unless the @option{-gnatwe} switch is used).
6223
6224 Note that this is by no means intended to be a general facility for
6225 checking arbitrary coding standards. It is simply an embedding of the
6226 style rules we have chosen for the GNAT sources. If you are starting
6227 a project which does not have established style standards, you may
6228 find it useful to adopt the entire set of GNAT coding standards, or
6229 some subset of them. If you already have an established set of coding
6230 standards, then it may be that selected style checking options do
6231 indeed correspond to choices you have made, but for general checking
6232 of an existing set of coding rules, you should look to the gnatcheck
6233 tool, which is designed for that purpose.
6234
6235 @ifset vms
6236 @code{(option,option,@dots{})} is a sequence of keywords
6237 @end ifset
6238 @ifclear vms
6239 The string @var{x} is a sequence of letters or digits
6240 @end ifclear
6241 indicating the particular style
6242 checks to be performed. The following checks are defined:
6243
6244 @table @option
6245 @c !sort!
6246 @item 0-9
6247 @emph{Specify indentation level.}
6248 If a digit from 1-9 appears
6249 ^in the string after @option{-gnaty}^as an option for /STYLE_CHECKS^
6250 then proper indentation is checked, with the digit indicating the
6251 indentation level required. A value of zero turns off this style check.
6252 The general style of required indentation is as specified by
6253 the examples in the Ada Reference Manual. Full line comments must be
6254 aligned with the @code{--} starting on a column that is a multiple of
6255 the alignment level, or they may be aligned the same way as the following
6256 non-blank line (this is useful when full line comments appear in the middle
6257 of a statement.
6258
6259 @item ^a^ATTRIBUTE^
6260 @emph{Check attribute casing.}
6261 Attribute names, including the case of keywords such as @code{digits}
6262 used as attributes names, must be written in mixed case, that is, the
6263 initial letter and any letter following an underscore must be uppercase.
6264 All other letters must be lowercase.
6265
6266 @item ^A^ARRAY_INDEXES^
6267 @emph{Use of array index numbers in array attributes.}
6268 When using the array attributes First, Last, Range,
6269 or Length, the index number must be omitted for one-dimensional arrays
6270 and is required for multi-dimensional arrays.
6271
6272 @item ^b^BLANKS^
6273 @emph{Blanks not allowed at statement end.}
6274 Trailing blanks are not allowed at the end of statements. The purpose of this
6275 rule, together with h (no horizontal tabs), is to enforce a canonical format
6276 for the use of blanks to separate source tokens.
6277
6278 @item ^B^BOOLEAN_OPERATORS^
6279 @emph{Check Boolean operators.}
6280 The use of AND/OR operators is not permitted except in the cases of modular
6281 operands, array operands, and simple stand-alone boolean variables or
6282 boolean constants. In all other cases AND THEN/OR ELSE are required.
6283
6284 @item ^c^COMMENTS^ (double space)
6285 @emph{Check comments, double space.}
6286 Comments must meet the following set of rules:
6287
6288 @itemize @bullet
6289
6290 @item
6291 The ``@code{--}'' that starts the column must either start in column one,
6292 or else at least one blank must precede this sequence.
6293
6294 @item
6295 Comments that follow other tokens on a line must have at least one blank
6296 following the ``@code{--}'' at the start of the comment.
6297
6298 @item
6299 Full line comments must have at least two blanks following the
6300 ``@code{--}'' that starts the comment, with the following exceptions.
6301
6302 @item
6303 A line consisting only of the ``@code{--}'' characters, possibly preceded
6304 by blanks is permitted.
6305
6306 @item
6307 A comment starting with ``@code{--x}'' where @code{x} is a special character
6308 is permitted.
6309 This allows proper processing of the output generated by specialized tools
6310 including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK
6311 annotation
6312 language (where ``@code{--#}'' is used). For the purposes of this rule, a
6313 special character is defined as being in one of the ASCII ranges
6314 @code{16#21#@dots{}16#2F#} or @code{16#3A#@dots{}16#3F#}.
6315 Note that this usage is not permitted
6316 in GNAT implementation units (i.e., when @option{-gnatg} is used).
6317
6318 @item
6319 A line consisting entirely of minus signs, possibly preceded by blanks, is
6320 permitted. This allows the construction of box comments where lines of minus
6321 signs are used to form the top and bottom of the box.
6322
6323 @item
6324 A comment that starts and ends with ``@code{--}'' is permitted as long as at
6325 least one blank follows the initial ``@code{--}''. Together with the preceding
6326 rule, this allows the construction of box comments, as shown in the following
6327 example:
6328 @smallexample
6329 ---------------------------
6330 -- This is a box comment --
6331 -- with two text lines.  --
6332 ---------------------------
6333 @end smallexample
6334 @end itemize
6335
6336 @item ^C^COMMENTS1^ (single space)
6337 @emph{Check comments, single space.}
6338 This is identical to @code{^c^COMMENTS^} except that only one space
6339 is required following the @code{--} of a comment instead of two.
6340
6341 @item ^d^DOS_LINE_ENDINGS^
6342 @emph{Check no DOS line terminators present.}
6343 All lines must be terminated by a single ASCII.LF
6344 character (in particular the DOS line terminator sequence CR/LF is not
6345 allowed).
6346
6347 @item ^e^END^
6348 @emph{Check end/exit labels.}
6349 Optional labels on @code{end} statements ending subprograms and on
6350 @code{exit} statements exiting named loops, are required to be present.
6351
6352 @item ^f^VTABS^
6353 @emph{No form feeds or vertical tabs.}
6354 Neither form feeds nor vertical tab characters are permitted
6355 in the source text.
6356
6357 @item ^g^GNAT^
6358 @emph{GNAT style mode}
6359 The set of style check switches is set to match that used by the GNAT sources.
6360 This may be useful when developing code that is eventually intended to be
6361 incorporated into GNAT. For further details, see GNAT sources.
6362
6363 @item ^h^HTABS^
6364 @emph{No horizontal tabs.}
6365 Horizontal tab characters are not permitted in the source text.
6366 Together with the b (no blanks at end of line) check, this
6367 enforces a canonical form for the use of blanks to separate
6368 source tokens.
6369
6370 @item ^i^IF_THEN^
6371 @emph{Check if-then layout.}
6372 The keyword @code{then} must appear either on the same
6373 line as corresponding @code{if}, or on a line on its own, lined
6374 up under the @code{if} with at least one non-blank line in between
6375 containing all or part of the condition to be tested.
6376
6377 @item ^I^IN_MODE^
6378 @emph{check mode IN keywords}
6379 Mode @code{in} (the default mode) is not
6380 allowed to be given explicitly. @code{in out} is fine,
6381 but not @code{in} on its own.
6382
6383 @item ^k^KEYWORD^
6384 @emph{Check keyword casing.}
6385 All keywords must be in lower case (with the exception of keywords
6386 such as @code{digits} used as attribute names to which this check
6387 does not apply).
6388
6389 @item ^l^LAYOUT^
6390 @emph{Check layout.}
6391 Layout of statement and declaration constructs must follow the
6392 recommendations in the Ada Reference Manual, as indicated by the
6393 form of the syntax rules. For example an @code{else} keyword must
6394 be lined up with the corresponding @code{if} keyword.
6395
6396 There are two respects in which the style rule enforced by this check
6397 option are more liberal than those in the Ada Reference Manual. First
6398 in the case of record declarations, it is permissible to put the
6399 @code{record} keyword on the same line as the @code{type} keyword, and
6400 then the @code{end} in @code{end record} must line up under @code{type}.
6401 This is also permitted when the type declaration is split on two lines.
6402 For example, any of the following three layouts is acceptable:
6403
6404 @smallexample @c ada
6405 @cartouche
6406 type q is record
6407    a : integer;
6408    b : integer;
6409 end record;
6410
6411 type q is
6412    record
6413       a : integer;
6414       b : integer;
6415    end record;
6416
6417 type q is
6418    record
6419       a : integer;
6420       b : integer;
6421 end record;
6422
6423 @end cartouche
6424 @end smallexample
6425
6426 @noindent
6427 Second, in the case of a block statement, a permitted alternative
6428 is to put the block label on the same line as the @code{declare} or
6429 @code{begin} keyword, and then line the @code{end} keyword up under
6430 the block label. For example both the following are permitted:
6431
6432 @smallexample @c ada
6433 @cartouche
6434 Block : declare
6435    A : Integer := 3;
6436 begin
6437    Proc (A, A);
6438 end Block;
6439
6440 Block :
6441    declare
6442       A : Integer := 3;
6443    begin
6444       Proc (A, A);
6445    end Block;
6446 @end cartouche
6447 @end smallexample
6448
6449 @noindent
6450 The same alternative format is allowed for loops. For example, both of
6451 the following are permitted:
6452
6453 @smallexample @c ada
6454 @cartouche
6455 Clear : while J < 10 loop
6456    A (J) := 0;
6457 end loop Clear;
6458
6459 Clear :
6460    while J < 10 loop
6461       A (J) := 0;
6462    end loop Clear;
6463 @end cartouche
6464 @end smallexample
6465
6466 @item ^Lnnn^MAX_NESTING=nnn^
6467 @emph{Set maximum nesting level}
6468 The maximum level of nesting of constructs (including subprograms, loops,
6469 blocks, packages, and conditionals) may not exceed the given value
6470 @option{nnn}. A value of zero disconnects this style check.
6471
6472 @item ^m^LINE_LENGTH^
6473 @emph{Check maximum line length.}
6474 The length of source lines must not exceed 79 characters, including
6475 any trailing blanks. The value of 79 allows convenient display on an
6476 80 character wide device or window, allowing for possible special
6477 treatment of 80 character lines. Note that this count is of
6478 characters in the source text. This means that a tab character counts
6479 as one character in this count but a wide character sequence counts as
6480 a single character (however many bytes are needed in the encoding).
6481
6482 @item ^Mnnn^MAX_LENGTH=nnn^
6483 @emph{Set maximum line length.}
6484 The length of lines must not exceed the
6485 given value @option{nnn}. The maximum value that can be specified is 32767.
6486
6487 @item ^n^STANDARD_CASING^
6488 @emph{Check casing of entities in Standard.}
6489 Any identifier from Standard must be cased
6490 to match the presentation in the Ada Reference Manual (for example,
6491 @code{Integer} and @code{ASCII.NUL}).
6492
6493 @item ^N^NONE^
6494 @emph{Turn off all style checks}
6495 All style check options are turned off.
6496
6497 @item ^o^ORDERED_SUBPROGRAMS^
6498 @emph{Check order of subprogram bodies.}
6499 All subprogram bodies in a given scope
6500 (e.g.@: a package body) must be in alphabetical order. The ordering
6501 rule uses normal Ada rules for comparing strings, ignoring casing
6502 of letters, except that if there is a trailing numeric suffix, then
6503 the value of this suffix is used in the ordering (e.g.@: Junk2 comes
6504 before Junk10).
6505
6506 @item ^O^OVERRIDING_INDICATORS^
6507 @emph{Check that overriding subprograms are explicitly marked as such.}
6508 The declaration of a primitive operation of a type extension that overrides
6509 an inherited operation must carry an overriding indicator.
6510
6511 @item ^p^PRAGMA^
6512 @emph{Check pragma casing.}
6513 Pragma names must be written in mixed case, that is, the
6514 initial letter and any letter following an underscore must be uppercase.
6515 All other letters must be lowercase.
6516
6517 @item ^r^REFERENCES^
6518 @emph{Check references.}
6519 All identifier references must be cased in the same way as the
6520 corresponding declaration. No specific casing style is imposed on
6521 identifiers. The only requirement is for consistency of references
6522 with declarations.
6523
6524 @item ^S^STATEMENTS_AFTER_THEN_ELSE^
6525 @emph{Check no statements after THEN/ELSE.}
6526 No statements are allowed
6527 on the same line as a THEN or ELSE keyword following the
6528 keyword in an IF statement. OR ELSE and AND THEN are not affected,
6529 and a special exception allows a pragma to appear after ELSE.
6530
6531 @item ^s^SPECS^
6532 @emph{Check separate specs.}
6533 Separate declarations (``specs'') are required for subprograms (a
6534 body is not allowed to serve as its own declaration). The only
6535 exception is that parameterless library level procedures are
6536 not required to have a separate declaration. This exception covers
6537 the most frequent form of main program procedures.
6538
6539 @item ^t^TOKEN^
6540 @emph{Check token spacing.}
6541 The following token spacing rules are enforced:
6542
6543 @itemize @bullet
6544
6545 @item
6546 The keywords @code{@b{abs}} and @code{@b{not}} must be followed by a space.
6547
6548 @item
6549 The token @code{=>} must be surrounded by spaces.
6550
6551 @item
6552 The token @code{<>} must be preceded by a space or a left parenthesis.
6553
6554 @item
6555 Binary operators other than @code{**} must be surrounded by spaces.
6556 There is no restriction on the layout of the @code{**} binary operator.
6557
6558 @item
6559 Colon must be surrounded by spaces.
6560
6561 @item
6562 Colon-equal (assignment, initialization) must be surrounded by spaces.
6563
6564 @item
6565 Comma must be the first non-blank character on the line, or be
6566 immediately preceded by a non-blank character, and must be followed
6567 by a space.
6568
6569 @item
6570 If the token preceding a left parenthesis ends with a letter or digit, then
6571 a space must separate the two tokens.
6572
6573 @item
6574 if the token following a right parenthesis starts with a letter or digit, then
6575 a space must separate the two tokens.
6576
6577 @item
6578 A right parenthesis must either be the first non-blank character on
6579 a line, or it must be preceded by a non-blank character.
6580
6581 @item
6582 A semicolon must not be preceded by a space, and must not be followed by
6583 a non-blank character.
6584
6585 @item
6586 A unary plus or minus may not be followed by a space.
6587
6588 @item
6589 A vertical bar must be surrounded by spaces.
6590 @end itemize
6591
6592 @item ^u^UNNECESSARY_BLANK_LINES^
6593 @emph{Check unnecessary blank lines.}
6594 Unnecessary blank lines are not allowed. A blank line is considered
6595 unnecessary if it appears at the end of the file, or if more than
6596 one blank line occurs in sequence.
6597
6598 @item ^x^XTRA_PARENS^
6599 @emph{Check extra parentheses.}
6600 Unnecessary extra level of parentheses (C-style) are not allowed
6601 around conditions in @code{if} statements, @code{while} statements and
6602 @code{exit} statements.
6603
6604 @item ^y^ALL_BUILTIN^
6605 @emph{Set all standard style check options}
6606 This is equivalent to @code{gnaty3aAbcefhiklmnprst}, that is all checking
6607 options enabled with the exception of @option{-gnatyo}, @option{-gnatyI},
6608 @option{-gnatyS}, @option{-gnatyLnnn},
6609 @option{-gnatyd}, @option{-gnatyu}, and @option{-gnatyx}.
6610
6611 @ifclear vms
6612 @item -
6613 @emph{Remove style check options}
6614 This causes any subsequent options in the string to act as canceling the
6615 corresponding style check option. To cancel maximum nesting level control,
6616 use @option{L} parameter witout any integer value after that, because any
6617 digit following @option{-} in the parameter string of the @option{-gnaty}
6618 option will be threated as canceling indentation check. The same is true
6619 for @option{M} parameter. @option{y} and @option{N} parameters are not
6620 allowed after @option{-}.
6621
6622 @item +
6623 This causes any subsequent options in the string to enable the corresponding
6624 style check option. That is, it cancels the effect of a previous ^-^REMOVE^,
6625 if any.
6626 @end ifclear
6627
6628 @ifset vms
6629 @item NOxxx
6630 @emph{Removing style check options}
6631 If the name of a style check is preceded by @option{NO} then the corresponding
6632 style check is turned off. For example @option{NOCOMMENTS} turns off style
6633 checking for comments.
6634 @end ifset
6635 @end table
6636
6637 @noindent
6638 In the above rules, appearing in column one is always permitted, that is,
6639 counts as meeting either a requirement for a required preceding space,
6640 or as meeting a requirement for no preceding space.
6641
6642 Appearing at the end of a line is also always permitted, that is, counts
6643 as meeting either a requirement for a following space, or as meeting
6644 a requirement for no following space.
6645
6646 @noindent
6647 If any of these style rules is violated, a message is generated giving
6648 details on the violation. The initial characters of such messages are
6649 always ``@code{(style)}''. Note that these messages are treated as warning
6650 messages, so they normally do not prevent the generation of an object
6651 file. The @option{-gnatwe} switch can be used to treat warning messages,
6652 including style messages, as fatal errors.
6653
6654 The switch
6655 @ifclear vms
6656 @option{-gnaty} on its own (that is not
6657 followed by any letters or digits), then the effect is equivalent
6658 to the use of @option{-gnatyy}, as described above, that is all
6659 built-in standard style check options are enabled.
6660
6661 @end ifclear
6662 @ifset vms
6663 /STYLE_CHECKS=ALL_BUILTIN enables all checking options with
6664 the exception of ORDERED_SUBPROGRAMS, UNNECESSARY_BLANK_LINES,
6665 XTRA_PARENS, and DOS_LINE_ENDINGS. In addition
6666 @end ifset
6667
6668 The switch
6669 @ifclear vms
6670 @option{-gnatyN}
6671 @end ifclear
6672 @ifset vms
6673 /STYLE_CHECKS=NONE
6674 @end ifset
6675 clears any previously set style checks.
6676
6677 @node Run-Time Checks
6678 @subsection Run-Time Checks
6679 @cindex Division by zero
6680 @cindex Access before elaboration
6681 @cindex Checks, division by zero
6682 @cindex Checks, access before elaboration
6683 @cindex Checks, stack overflow checking
6684
6685 @noindent
6686 By default, the following checks are suppressed: integer overflow
6687 checks, stack overflow checks, and checks for access before
6688 elaboration on subprogram calls. All other checks, including range
6689 checks and array bounds checks, are turned on by default. The
6690 following @command{gcc} switches refine this default behavior.
6691
6692 @table @option
6693 @c !sort!
6694 @item -gnatp
6695 @cindex @option{-gnatp} (@command{gcc})
6696 @cindex Suppressing checks
6697 @cindex Checks, suppressing
6698 @findex Suppress
6699 This switch causes the unit to be compiled
6700 as though @code{pragma Suppress (All_checks)}
6701 had been present in the source. Validity checks are also eliminated (in
6702 other words @option{-gnatp} also implies @option{-gnatVn}.
6703 Use this switch to improve the performance
6704 of the code at the expense of safety in the presence of invalid data or
6705 program bugs.
6706
6707 Note that when checks are suppressed, the compiler is allowed, but not
6708 required, to omit the checking code. If the run-time cost of the
6709 checking code is zero or near-zero, the compiler will generate it even
6710 if checks are suppressed. In particular, if the compiler can prove
6711 that a certain check will necessarily fail, it will generate code to
6712 do an unconditional ``raise'', even if checks are suppressed. The
6713 compiler warns in this case. Another case in which checks may not be
6714 eliminated is when they are embedded in certain run time routines such
6715 as math library routines.
6716
6717 Of course, run-time checks are omitted whenever the compiler can prove
6718 that they will not fail, whether or not checks are suppressed.
6719
6720 Note that if you suppress a check that would have failed, program
6721 execution is erroneous, which means the behavior is totally
6722 unpredictable. The program might crash, or print wrong answers, or
6723 do anything else. It might even do exactly what you wanted it to do
6724 (and then it might start failing mysteriously next week or next
6725 year). The compiler will generate code based on the assumption that
6726 the condition being checked is true, which can result in disaster if
6727 that assumption is wrong.
6728
6729 The @option{-gnatp} switch has no effect if a subsequent
6730 @option{-gnat-p} switch appears.
6731
6732 @item -gnat-p
6733 @cindex @option{-gnat-p} (@command{gcc})
6734 @cindex Suppressing checks
6735 @cindex Checks, suppressing
6736 @findex Suppress
6737 This switch cancels the effect of a previous @option{gnatp} switch.
6738
6739 @item -gnato
6740 @cindex @option{-gnato} (@command{gcc})
6741 @cindex Overflow checks
6742 @cindex Check, overflow
6743 Enables overflow checking for integer operations.
6744 This causes GNAT to generate slower and larger executable
6745 programs by adding code to check for overflow (resulting in raising
6746 @code{Constraint_Error} as required by standard Ada
6747 semantics). These overflow checks correspond to situations in which
6748 the true value of the result of an operation may be outside the base
6749 range of the result type. The following example shows the distinction:
6750
6751 @smallexample @c ada
6752 X1 : Integer := "Integer'Last";
6753 X2 : Integer range 1 .. 5 := "5";
6754 X3 : Integer := "Integer'Last";
6755 X4 : Integer range 1 .. 5 := "5";
6756 F  : Float := "2.0E+20";
6757 @dots{}
6758 X1 := X1 + 1;
6759 X2 := X2 + 1;
6760 X3 := Integer (F);
6761 X4 := Integer (F);
6762 @end smallexample
6763
6764 @noindent
6765 Note that if explicit values are assigned at compile time, the
6766 compiler may be able to detect overflow at compile time, in which case
6767 no actual run-time checking code is required, and Constraint_Error
6768 will be raised unconditionally, with or without
6769 @option{-gnato}. That's why the assigned values in the above fragment
6770 are in quotes, the meaning is "assign a value not known to the
6771 compiler that happens to be equal to ...". The remaining discussion
6772 assumes that the compiler cannot detect the values at compile time.
6773
6774 Here the first addition results in a value that is outside the base range
6775 of Integer, and hence requires an overflow check for detection of the
6776 constraint error. Thus the first assignment to @code{X1} raises a
6777 @code{Constraint_Error} exception only if @option{-gnato} is set.
6778
6779 The second increment operation results in a violation of the explicit
6780 range constraint; such range checks are performed by default, and are
6781 unaffected by @option{-gnato}.
6782
6783 The two conversions of @code{F} both result in values that are outside
6784 the base range of type @code{Integer} and thus will raise
6785 @code{Constraint_Error} exceptions only if @option{-gnato} is used.
6786 The fact that the result of the second conversion is assigned to
6787 variable @code{X4} with a restricted range is irrelevant, since the problem
6788 is in the conversion, not the assignment.
6789
6790 Basically the rule is that in the default mode (@option{-gnato} not
6791 used), the generated code assures that all integer variables stay
6792 within their declared ranges, or within the base range if there is
6793 no declared range. This prevents any serious problems like indexes
6794 out of range for array operations.
6795
6796 What is not checked in default mode is an overflow that results in
6797 an in-range, but incorrect value. In the above example, the assignments
6798 to @code{X1}, @code{X2}, @code{X3} all give results that are within the
6799 range of the target variable, but the result is wrong in the sense that
6800 it is too large to be represented correctly. Typically the assignment
6801 to @code{X1} will result in wrap around to the largest negative number.
6802 The conversions of @code{F} will result in some @code{Integer} value
6803 and if that integer value is out of the @code{X4} range then the
6804 subsequent assignment would generate an exception.
6805
6806 @findex Machine_Overflows
6807 Note that the @option{-gnato} switch does not affect the code generated
6808 for any floating-point operations; it applies only to integer
6809 semantics).
6810 For floating-point, GNAT has the @code{Machine_Overflows}
6811 attribute set to @code{False} and the normal mode of operation is to
6812 generate IEEE NaN and infinite values on overflow or invalid operations
6813 (such as dividing 0.0 by 0.0).
6814
6815 The reason that we distinguish overflow checking from other kinds of
6816 range constraint checking is that a failure of an overflow check, unlike
6817 for example the failure of a range check, can result in an incorrect
6818 value, but cannot cause random memory destruction (like an out of range
6819 subscript), or a wild jump (from an out of range case value). Overflow
6820 checking is also quite expensive in time and space, since in general it
6821 requires the use of double length arithmetic.
6822
6823 Note again that @option{-gnato} is off by default, so overflow checking is
6824 not performed in default mode. This means that out of the box, with the
6825 default settings, GNAT does not do all the checks expected from the
6826 language description in the Ada Reference Manual. If you want all constraint
6827 checks to be performed, as described in this Manual, then you must
6828 explicitly use the -gnato switch either on the @command{gnatmake} or
6829 @command{gcc} command.
6830
6831 @item -gnatE
6832 @cindex @option{-gnatE} (@command{gcc})
6833 @cindex Elaboration checks
6834 @cindex Check, elaboration
6835 Enables dynamic checks for access-before-elaboration
6836 on subprogram calls and generic instantiations.
6837 Note that @option{-gnatE} is not necessary for safety, because in the
6838 default mode, GNAT ensures statically that the checks would not fail.
6839 For full details of the effect and use of this switch,
6840 @xref{Compiling Using gcc}.
6841
6842 @item -fstack-check
6843 @cindex @option{-fstack-check} (@command{gcc})
6844 @cindex Stack Overflow Checking
6845 @cindex Checks, stack overflow checking
6846 Activates stack overflow checking. For full details of the effect and use of
6847 this switch see @ref{Stack Overflow Checking}.
6848 @end table
6849
6850 @findex Unsuppress
6851 @noindent
6852 The setting of these switches only controls the default setting of the
6853 checks. You may modify them using either @code{Suppress} (to remove
6854 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
6855 the program source.
6856
6857 @node Using gcc for Syntax Checking
6858 @subsection Using @command{gcc} for Syntax Checking
6859 @table @option
6860 @item -gnats
6861 @cindex @option{-gnats} (@command{gcc})
6862 @ifclear vms
6863
6864 @noindent
6865 The @code{s} stands for ``syntax''.
6866 @end ifclear
6867
6868 Run GNAT in syntax checking only mode. For
6869 example, the command
6870
6871 @smallexample
6872 $ gcc -c -gnats x.adb
6873 @end smallexample
6874
6875 @noindent
6876 compiles file @file{x.adb} in syntax-check-only mode. You can check a
6877 series of files in a single command
6878 @ifclear vms
6879 , and can use wild cards to specify such a group of files.
6880 Note that you must specify the @option{-c} (compile
6881 only) flag in addition to the @option{-gnats} flag.
6882 @end ifclear
6883 .
6884 You may use other switches in conjunction with @option{-gnats}. In
6885 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
6886 format of any generated error messages.
6887
6888 When the source file is empty or contains only empty lines and/or comments,
6889 the output is a warning:
6890
6891 @smallexample
6892 $ gcc -c -gnats -x ada toto.txt
6893 toto.txt:1:01: warning: empty file, contains no compilation units
6894 $
6895 @end smallexample
6896
6897 Otherwise, the output is simply the error messages, if any. No object file or
6898 ALI file is generated by a syntax-only compilation. Also, no units other
6899 than the one specified are accessed. For example, if a unit @code{X}
6900 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
6901 check only mode does not access the source file containing unit
6902 @code{Y}.
6903
6904 @cindex Multiple units, syntax checking
6905 Normally, GNAT allows only a single unit in a source file. However, this
6906 restriction does not apply in syntax-check-only mode, and it is possible
6907 to check a file containing multiple compilation units concatenated
6908 together. This is primarily used by the @code{gnatchop} utility
6909 (@pxref{Renaming Files Using gnatchop}).
6910 @end table
6911
6912 @node Using gcc for Semantic Checking
6913 @subsection Using @command{gcc} for Semantic Checking
6914 @table @option
6915 @item -gnatc
6916 @cindex @option{-gnatc} (@command{gcc})
6917
6918 @ifclear vms
6919 @noindent
6920 The @code{c} stands for ``check''.
6921 @end ifclear
6922 Causes the compiler to operate in semantic check mode,
6923 with full checking for all illegalities specified in the
6924 Ada Reference Manual, but without generation of any object code
6925 (no object file is generated).
6926
6927 Because dependent files must be accessed, you must follow the GNAT
6928 semantic restrictions on file structuring to operate in this mode:
6929
6930 @itemize @bullet
6931 @item
6932 The needed source files must be accessible
6933 (@pxref{Search Paths and the Run-Time Library (RTL)}).
6934
6935 @item
6936 Each file must contain only one compilation unit.
6937
6938 @item
6939 The file name and unit name must match (@pxref{File Naming Rules}).
6940 @end itemize
6941
6942 The output consists of error messages as appropriate. No object file is
6943 generated. An @file{ALI} file is generated for use in the context of
6944 cross-reference tools, but this file is marked as not being suitable
6945 for binding (since no object file is generated).
6946 The checking corresponds exactly to the notion of
6947 legality in the Ada Reference Manual.
6948
6949 Any unit can be compiled in semantics-checking-only mode, including
6950 units that would not normally be compiled (subunits,
6951 and specifications where a separate body is present).
6952 @end table
6953
6954 @node Compiling Different Versions of Ada
6955 @subsection Compiling Different Versions of Ada
6956
6957 @noindent
6958 The switches described in this section allow you to explicitly specify
6959 the version of the Ada language that your programs are written in.
6960 By default @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION},
6961 but you can also specify @value{NONDEFAULTLANGUAGEVERSION} or
6962 indicate Ada 83 compatibility mode.
6963
6964 @table @option
6965 @cindex Compatibility with Ada 83
6966
6967 @item -gnat83 (Ada 83 Compatibility Mode)
6968 @cindex @option{-gnat83} (@command{gcc})
6969 @cindex ACVC, Ada 83 tests
6970 @cindex Ada 83 mode
6971
6972 @noindent
6973 Although GNAT is primarily an Ada 95 / Ada 2005 compiler, this switch
6974 specifies that the program is to be compiled in Ada 83 mode. With
6975 @option{-gnat83}, GNAT rejects most post-Ada 83 extensions and applies Ada 83
6976 semantics where this can be done easily.
6977 It is not possible to guarantee this switch does a perfect
6978 job; some subtle tests, such as are
6979 found in earlier ACVC tests (and that have been removed from the ACATS suite
6980 for Ada 95), might not compile correctly.
6981 Nevertheless, this switch may be useful in some circumstances, for example
6982 where, due to contractual reasons, existing code needs to be maintained
6983 using only Ada 83 features.
6984
6985 With few exceptions (most notably the need to use @code{<>} on
6986 @cindex Generic formal parameters
6987 unconstrained generic formal parameters, the use of the new Ada 95 / Ada 2005
6988 reserved words, and the use of packages
6989 with optional bodies), it is not necessary to specify the
6990 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
6991 exceptions, Ada 95 and Ada 2005 are upwardly compatible with Ada 83. Thus
6992 a correct Ada 83 program is usually also a correct program
6993 in these later versions of the language standard.
6994 For further information, please refer to @ref{Compatibility and Porting Guide}.
6995
6996 @item -gnat95 (Ada 95 mode)
6997 @cindex @option{-gnat95} (@command{gcc})
6998 @cindex Ada 95 mode
6999
7000 @noindent
7001 This switch directs the compiler to implement the Ada 95 version of the
7002 language.
7003 Since Ada 95 is almost completely upwards
7004 compatible with Ada 83, Ada 83 programs may generally be compiled using
7005 this switch (see the description of the @option{-gnat83} switch for further
7006 information about Ada 83 mode).
7007 If an Ada 2005 program is compiled in Ada 95 mode,
7008 uses of the new Ada 2005 features will cause error
7009 messages or warnings.
7010
7011 This switch also can be used to cancel the effect of a previous
7012 @option{-gnat83}, @option{-gnat05/2005}, or @option{-gnat12/2012}
7013 switch earlier in the command line.
7014
7015 @item -gnat05 or -gnat2005 (Ada 2005 mode)
7016 @cindex @option{-gnat05} (@command{gcc})
7017 @cindex @option{-gnat2005} (@command{gcc})
7018 @cindex Ada 2005 mode
7019
7020 @noindent
7021 This switch directs the compiler to implement the Ada 2005 version of the
7022 language, as documented in the official Ada standards document.
7023 Since Ada 2005 is almost completely upwards
7024 compatible with Ada 95 (and thus also with Ada 83), Ada 83 and Ada 95 programs
7025 may generally be compiled using this switch (see the description of the
7026 @option{-gnat83} and @option{-gnat95} switches for further
7027 information).
7028
7029 @ifset PROEDITION
7030 Note that even though Ada 2005 is the current official version of the
7031 language, GNAT still compiles in Ada 95 mode by default, so if you are
7032 using Ada 2005 features in your program, you must use this switch (or
7033 the equivalent Ada_05 or Ada_2005 configuration pragmas).
7034 @end ifset
7035
7036 @item -gnat12 or -gnat2012 (Ada 2012 mode)
7037 @cindex @option{-gnat12} (@command{gcc})
7038 @cindex @option{-gnat2012} (@command{gcc})
7039 @cindex Ada 2012 mode
7040
7041 @noindent
7042 This switch directs the compiler to implement the Ada 2012 version of the
7043 language.
7044 Since Ada 2012 is almost completely upwards
7045 compatible with Ada 2005 (and thus also with Ada 83, and Ada 95),
7046 Ada 83 and Ada 95 programs
7047 may generally be compiled using this switch (see the description of the
7048 @option{-gnat83}, @option{-gnat95}, and @option{-gnat05/2005} switches
7049 for further information).
7050
7051 For information about the approved ``Ada Issues'' that have been incorporated
7052 into Ada 2012, see @url{http://www.ada-auth.org/ais.html}.
7053 Included with GNAT releases is a file @file{features-ada12} that describes
7054 the set of implemented Ada 2012 features.
7055
7056 @item -gnatX (Enable GNAT Extensions)
7057 @cindex @option{-gnatX} (@command{gcc})
7058 @cindex Ada language extensions
7059 @cindex GNAT extensions
7060
7061 @noindent
7062 This switch directs the compiler to implement the latest version of the
7063 language (currently Ada 2012) and also to enable certain GNAT implementation
7064 extensions that are not part of any Ada standard. For a full list of these
7065 extensions, see the GNAT reference manual.
7066
7067 @end table
7068
7069 @node Character Set Control
7070 @subsection Character Set Control
7071 @table @option
7072 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
7073 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
7074
7075 @noindent
7076 Normally GNAT recognizes the Latin-1 character set in source program
7077 identifiers, as described in the Ada Reference Manual.
7078 This switch causes
7079 GNAT to recognize alternate character sets in identifiers. @var{c} is a
7080 single character ^^or word^ indicating the character set, as follows:
7081
7082 @table @code
7083 @item 1
7084 ISO 8859-1 (Latin-1) identifiers
7085
7086 @item 2
7087 ISO 8859-2 (Latin-2) letters allowed in identifiers
7088
7089 @item 3
7090 ISO 8859-3 (Latin-3) letters allowed in identifiers
7091
7092 @item 4
7093 ISO 8859-4 (Latin-4) letters allowed in identifiers
7094
7095 @item 5
7096 ISO 8859-5 (Cyrillic) letters allowed in identifiers
7097
7098 @item 9
7099 ISO 8859-15 (Latin-9) letters allowed in identifiers
7100
7101 @item ^p^PC^
7102 IBM PC letters (code page 437) allowed in identifiers
7103
7104 @item ^8^PC850^
7105 IBM PC letters (code page 850) allowed in identifiers
7106
7107 @item ^f^FULL_UPPER^
7108 Full upper-half codes allowed in identifiers
7109
7110 @item ^n^NO_UPPER^
7111 No upper-half codes allowed in identifiers
7112
7113 @item ^w^WIDE^
7114 Wide-character codes (that is, codes greater than 255)
7115 allowed in identifiers
7116 @end table
7117
7118 @xref{Foreign Language Representation}, for full details on the
7119 implementation of these character sets.
7120
7121 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
7122 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
7123 Specify the method of encoding for wide characters.
7124 @var{e} is one of the following:
7125
7126 @table @code
7127
7128 @item ^h^HEX^
7129 Hex encoding (brackets coding also recognized)
7130
7131 @item ^u^UPPER^
7132 Upper half encoding (brackets encoding also recognized)
7133
7134 @item ^s^SHIFT_JIS^
7135 Shift/JIS encoding (brackets encoding also recognized)
7136
7137 @item ^e^EUC^
7138 EUC encoding (brackets encoding also recognized)
7139
7140 @item ^8^UTF8^
7141 UTF-8 encoding (brackets encoding also recognized)
7142
7143 @item ^b^BRACKETS^
7144 Brackets encoding only (default value)
7145 @end table
7146 For full details on these encoding
7147 methods see @ref{Wide Character Encodings}.
7148 Note that brackets coding is always accepted, even if one of the other
7149 options is specified, so for example @option{-gnatW8} specifies that both
7150 brackets and UTF-8 encodings will be recognized. The units that are
7151 with'ed directly or indirectly will be scanned using the specified
7152 representation scheme, and so if one of the non-brackets scheme is
7153 used, it must be used consistently throughout the program. However,
7154 since brackets encoding is always recognized, it may be conveniently
7155 used in standard libraries, allowing these libraries to be used with
7156 any of the available coding schemes.
7157 scheme.
7158
7159 If no @option{-gnatW?} parameter is present, then the default
7160 representation is normally Brackets encoding only. However, if the
7161 first three characters of the file are 16#EF# 16#BB# 16#BF# (the standard
7162 byte order mark or BOM for UTF-8), then these three characters are
7163 skipped and the default representation for the file is set to UTF-8.
7164
7165 Note that the wide character representation that is specified (explicitly
7166 or by default) for the main program also acts as the default encoding used
7167 for Wide_Text_IO files if not specifically overridden by a WCEM form
7168 parameter.
7169
7170 @end table
7171 @node File Naming Control
7172 @subsection File Naming Control
7173
7174 @table @option
7175 @item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n}
7176 @cindex @option{-gnatk} (@command{gcc})
7177 Activates file name ``krunching''. @var{n}, a decimal integer in the range
7178 1-999, indicates the maximum allowable length of a file name (not
7179 including the @file{.ads} or @file{.adb} extension). The default is not
7180 to enable file name krunching.
7181
7182 For the source file naming rules, @xref{File Naming Rules}.
7183 @end table
7184
7185 @node Subprogram Inlining Control
7186 @subsection Subprogram Inlining Control
7187
7188 @table @option
7189 @c !sort!
7190 @item -gnatn
7191 @cindex @option{-gnatn} (@command{gcc})
7192 @ifclear vms
7193 The @code{n} here is intended to suggest the first syllable of the
7194 word ``inline''.
7195 @end ifclear
7196 GNAT recognizes and processes @code{Inline} pragmas. However, for the
7197 inlining to actually occur, optimization must be enabled. To enable
7198 inlining of subprograms specified by pragma @code{Inline},
7199 you must also specify this switch.
7200 In the absence of this switch, GNAT does not attempt
7201 inlining and does not need to access the bodies of
7202 subprograms for which @code{pragma Inline} is specified if they are not
7203 in the current unit.
7204
7205 If you specify this switch the compiler will access these bodies,
7206 creating an extra source dependency for the resulting object file, and
7207 where possible, the call will be inlined.
7208 For further details on when inlining is possible
7209 see @ref{Inlining of Subprograms}.
7210
7211 @item -gnatN
7212 @cindex @option{-gnatN} (@command{gcc})
7213 This switch activates front-end inlining which also
7214 generates additional dependencies.
7215
7216 When using a gcc-based back end (in practice this means using any version
7217 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
7218 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
7219 Historically front end inlining was more extensive than the gcc back end
7220 inlining, but that is no longer the case.
7221 @end table
7222
7223 @node Auxiliary Output Control
7224 @subsection Auxiliary Output Control
7225
7226 @table @option
7227 @item -gnatt
7228 @cindex @option{-gnatt} (@command{gcc})
7229 @cindex Writing internal trees
7230 @cindex Internal trees, writing to file
7231 Causes GNAT to write the internal tree for a unit to a file (with the
7232 extension @file{.adt}.
7233 This not normally required, but is used by separate analysis tools.
7234 Typically
7235 these tools do the necessary compilations automatically, so you should
7236 not have to specify this switch in normal operation.
7237 Note that the combination of switches @option{-gnatct}
7238 generates a tree in the form required by ASIS applications.
7239
7240 @item -gnatu
7241 @cindex @option{-gnatu} (@command{gcc})
7242 Print a list of units required by this compilation on @file{stdout}.
7243 The listing includes all units on which the unit being compiled depends
7244 either directly or indirectly.
7245
7246 @ifclear vms
7247 @item -pass-exit-codes
7248 @cindex @option{-pass-exit-codes} (@command{gcc})
7249 If this switch is not used, the exit code returned by @command{gcc} when
7250 compiling multiple files indicates whether all source files have
7251 been successfully used to generate object files or not.
7252
7253 When @option{-pass-exit-codes} is used, @command{gcc} exits with an extended
7254 exit status and allows an integrated development environment to better
7255 react to a compilation failure. Those exit status are:
7256
7257 @table @asis
7258 @item 5
7259 There was an error in at least one source file.
7260 @item 3
7261 At least one source file did not generate an object file.
7262 @item 2
7263 The compiler died unexpectedly (internal error for example).
7264 @item 0
7265 An object file has been generated for every source file.
7266 @end table
7267 @end ifclear
7268 @end table
7269
7270 @node Debugging Control
7271 @subsection Debugging Control
7272
7273 @table @option
7274 @c !sort!
7275 @cindex Debugging options
7276 @ifclear vms
7277 @item -gnatd@var{x}
7278 @cindex @option{-gnatd} (@command{gcc})
7279 Activate internal debugging switches. @var{x} is a letter or digit, or
7280 string of letters or digits, which specifies the type of debugging
7281 outputs desired. Normally these are used only for internal development
7282 or system debugging purposes. You can find full documentation for these
7283 switches in the body of the @code{Debug} unit in the compiler source
7284 file @file{debug.adb}.
7285 @end ifclear
7286
7287 @item -gnatG[=nn]
7288 @cindex @option{-gnatG} (@command{gcc})
7289 This switch causes the compiler to generate auxiliary output containing
7290 a pseudo-source listing of the generated expanded code. Like most Ada
7291 compilers, GNAT works by first transforming the high level Ada code into
7292 lower level constructs. For example, tasking operations are transformed
7293 into calls to the tasking run-time routines. A unique capability of GNAT
7294 is to list this expanded code in a form very close to normal Ada source.
7295 This is very useful in understanding the implications of various Ada
7296 usage on the efficiency of the generated code. There are many cases in
7297 Ada (e.g.@: the use of controlled types), where simple Ada statements can
7298 generate a lot of run-time code. By using @option{-gnatG} you can identify
7299 these cases, and consider whether it may be desirable to modify the coding
7300 approach to improve efficiency.
7301
7302 The optional parameter @code{nn} if present after -gnatG specifies an
7303 alternative maximum line length that overrides the normal default of 72.
7304 This value is in the range 40-999999, values less than 40 being silently
7305 reset to 40. The equal sign is optional.
7306
7307 The format of the output is very similar to standard Ada source, and is
7308 easily understood by an Ada programmer. The following special syntactic
7309 additions correspond to low level features used in the generated code that
7310 do not have any exact analogies in pure Ada source form. The following
7311 is a partial list of these special constructions. See the spec
7312 of package @code{Sprint} in file @file{sprint.ads} for a full list.
7313
7314 If the switch @option{-gnatL} is used in conjunction with
7315 @cindex @option{-gnatL} (@command{gcc})
7316 @option{-gnatG}, then the original source lines are interspersed
7317 in the expanded source (as comment lines with the original line number).
7318
7319 @table @code
7320 @item new @var{xxx} @r{[}storage_pool = @var{yyy}@r{]}
7321 Shows the storage pool being used for an allocator.
7322
7323 @item at end @var{procedure-name};
7324 Shows the finalization (cleanup) procedure for a scope.
7325
7326 @item (if @var{expr} then @var{expr} else @var{expr})
7327 Conditional expression equivalent to the @code{x?y:z} construction in C.
7328
7329 @item @var{target}^^^(@var{source})
7330 A conversion with floating-point truncation instead of rounding.
7331
7332 @item @var{target}?(@var{source})
7333 A conversion that bypasses normal Ada semantic checking. In particular
7334 enumeration types and fixed-point types are treated simply as integers.
7335
7336 @item @var{target}?^^^(@var{source})
7337 Combines the above two cases.
7338
7339 @item @var{x} #/ @var{y}
7340 @itemx @var{x} #mod @var{y}
7341 @itemx @var{x} #* @var{y}
7342 @itemx @var{x} #rem @var{y}
7343 A division or multiplication of fixed-point values which are treated as
7344 integers without any kind of scaling.
7345
7346 @item free @var{expr} @r{[}storage_pool = @var{xxx}@r{]}
7347 Shows the storage pool associated with a @code{free} statement.
7348
7349 @item [subtype or type declaration]
7350 Used to list an equivalent declaration for an internally generated
7351 type that is referenced elsewhere in the listing.
7352
7353 @c @item freeze @var{type-name} @ovar{actions}
7354 @c Expanding @ovar macro inline (explanation in macro def comments)
7355 @item freeze @var{type-name} @r{[}@var{actions}@r{]}
7356 Shows the point at which @var{type-name} is frozen, with possible
7357 associated actions to be performed at the freeze point.
7358
7359 @item reference @var{itype}
7360 Reference (and hence definition) to internal type @var{itype}.
7361
7362 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
7363 Intrinsic function call.
7364
7365 @item @var{label-name} : label
7366 Declaration of label @var{labelname}.
7367
7368 @item #$ @var{subprogram-name}
7369 An implicit call to a run-time support routine
7370 (to meet the requirement of H.3.1(9) in a
7371 convenient manner).
7372
7373 @item @var{expr} && @var{expr} && @var{expr} @dots{} && @var{expr}
7374 A multiple concatenation (same effect as @var{expr} & @var{expr} &
7375 @var{expr}, but handled more efficiently).
7376
7377 @item [constraint_error]
7378 Raise the @code{Constraint_Error} exception.
7379
7380 @item @var{expression}'reference
7381 A pointer to the result of evaluating @var{expression}.
7382
7383 @item @var{target-type}!(@var{source-expression})
7384 An unchecked conversion of @var{source-expression} to @var{target-type}.
7385
7386 @item [@var{numerator}/@var{denominator}]
7387 Used to represent internal real literals (that) have no exact
7388 representation in base 2-16 (for example, the result of compile time
7389 evaluation of the expression 1.0/27.0).
7390 @end table
7391
7392 @item -gnatD[=nn]
7393 @cindex @option{-gnatD} (@command{gcc})
7394 When used in conjunction with @option{-gnatG}, this switch causes
7395 the expanded source, as described above for
7396 @option{-gnatG} to be written to files with names
7397 @file{^xxx.dg^XXX_DG^}, where @file{xxx} is the normal file name,
7398 instead of to the standard output file. For
7399 example, if the source file name is @file{hello.adb}, then a file
7400 @file{^hello.adb.dg^HELLO.ADB_DG^} will be written.  The debugging
7401 information generated by the @command{gcc} @option{^-g^/DEBUG^} switch
7402 will refer to the generated @file{^xxx.dg^XXX_DG^} file. This allows
7403 you to do source level debugging using the generated code which is
7404 sometimes useful for complex code, for example to find out exactly
7405 which part of a complex construction raised an exception. This switch
7406 also suppress generation of cross-reference information (see
7407 @option{-gnatx}) since otherwise the cross-reference information
7408 would refer to the @file{^.dg^.DG^} file, which would cause
7409 confusion since this is not the original source file.
7410
7411 Note that @option{-gnatD} actually implies @option{-gnatG}
7412 automatically, so it is not necessary to give both options.
7413 In other words @option{-gnatD} is equivalent to @option{-gnatDG}).
7414
7415 If the switch @option{-gnatL} is used in conjunction with
7416 @cindex @option{-gnatL} (@command{gcc})
7417 @option{-gnatDG}, then the original source lines are interspersed
7418 in the expanded source (as comment lines with the original line number).
7419
7420 The optional parameter @code{nn} if present after -gnatD specifies an
7421 alternative maximum line length that overrides the normal default of 72.
7422 This value is in the range 40-999999, values less than 40 being silently
7423 reset to 40. The equal sign is optional.
7424
7425 @item -gnatr
7426 @cindex @option{-gnatr} (@command{gcc})
7427 @cindex pragma Restrictions
7428 This switch causes pragma Restrictions to be treated as Restriction_Warnings
7429 so that violation of restrictions causes warnings rather than illegalities.
7430 This is useful during the development process when new restrictions are added
7431 or investigated. The switch also causes pragma Profile to be treated as
7432 Profile_Warnings, and pragma Restricted_Run_Time and pragma Ravenscar set
7433 restriction warnings rather than restrictions.
7434
7435 @ifclear vms
7436 @item -gnatR@r{[}0@r{|}1@r{|}2@r{|}3@r{[}s@r{]]}
7437 @cindex @option{-gnatR} (@command{gcc})
7438 This switch controls output from the compiler of a listing showing
7439 representation information for declared types and objects. For
7440 @option{-gnatR0}, no information is output (equivalent to omitting
7441 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
7442 so @option{-gnatR} with no parameter has the same effect), size and alignment
7443 information is listed for declared array and record types. For
7444 @option{-gnatR2}, size and alignment information is listed for all
7445 declared types and objects. Finally @option{-gnatR3} includes symbolic
7446 expressions for values that are computed at run time for
7447 variant records. These symbolic expressions have a mostly obvious
7448 format with #n being used to represent the value of the n'th
7449 discriminant. See source files @file{repinfo.ads/adb} in the
7450 @code{GNAT} sources for full details on the format of @option{-gnatR3}
7451 output. If the switch is followed by an s (e.g.@: @option{-gnatR2s}), then
7452 the output is to a file with the name @file{^file.rep^file_REP^} where
7453 file is the name of the corresponding source file.
7454 @end ifclear
7455 @ifset vms
7456 @item /REPRESENTATION_INFO
7457 @cindex @option{/REPRESENTATION_INFO} (@command{gcc})
7458 This qualifier controls output from the compiler of a listing showing
7459 representation information for declared types and objects. For
7460 @option{/REPRESENTATION_INFO=NONE}, no information is output
7461 (equivalent to omitting the @option{/REPRESENTATION_INFO} qualifier).
7462 @option{/REPRESENTATION_INFO} without option is equivalent to
7463 @option{/REPRESENTATION_INFO=ARRAYS}.
7464 For @option{/REPRESENTATION_INFO=ARRAYS}, size and alignment
7465 information is listed for declared array and record types. For
7466 @option{/REPRESENTATION_INFO=OBJECTS}, size and alignment information
7467 is listed for all expression information for values that are computed
7468 at run time for variant records. These symbolic expressions have a mostly
7469 obvious format with #n being used to represent the value of the n'th
7470 discriminant. See source files @file{REPINFO.ADS/ADB} in the
7471 @code{GNAT} sources for full details on the format of
7472 @option{/REPRESENTATION_INFO=SYMBOLIC} output.
7473 If _FILE is added at the end of an option
7474 (e.g.@: @option{/REPRESENTATION_INFO=ARRAYS_FILE}),
7475 then the output is to a file with the name @file{file_REP} where
7476 file is the name of the corresponding source file.
7477 @end ifset
7478 Note that it is possible for record components to have zero size. In
7479 this case, the component clause uses an obvious extension of permitted
7480 Ada syntax, for example @code{at 0 range 0 .. -1}.
7481
7482 Representation information requires that code be generated (since it is the
7483 code generator that lays out complex data structures). If an attempt is made
7484 to output representation information when no code is generated, for example
7485 when a subunit is compiled on its own, then no information can be generated
7486 and the compiler outputs a message to this effect.
7487
7488 @item -gnatS
7489 @cindex @option{-gnatS} (@command{gcc})
7490 The use of the switch @option{-gnatS} for an
7491 Ada compilation will cause the compiler to output a
7492 representation of package Standard in a form very
7493 close to standard Ada. It is not quite possible to
7494 do this entirely in standard Ada (since new
7495 numeric base types cannot be created in standard
7496 Ada), but the output is easily
7497 readable to any Ada programmer, and is useful to
7498 determine the characteristics of target dependent
7499 types in package Standard.
7500
7501 @item -gnatx
7502 @cindex @option{-gnatx} (@command{gcc})
7503 Normally the compiler generates full cross-referencing information in
7504 the @file{ALI} file. This information is used by a number of tools,
7505 including @code{gnatfind} and @code{gnatxref}. The @option{-gnatx} switch
7506 suppresses this information. This saves some space and may slightly
7507 speed up compilation, but means that these tools cannot be used.
7508 @end table
7509
7510 @node Exception Handling Control
7511 @subsection Exception Handling Control
7512
7513 @noindent
7514 GNAT uses two methods for handling exceptions at run-time. The
7515 @code{setjmp/longjmp} method saves the context when entering
7516 a frame with an exception handler. Then when an exception is
7517 raised, the context can be restored immediately, without the
7518 need for tracing stack frames. This method provides very fast
7519 exception propagation, but introduces significant overhead for
7520 the use of exception handlers, even if no exception is raised.
7521
7522 The other approach is called ``zero cost'' exception handling.
7523 With this method, the compiler builds static tables to describe
7524 the exception ranges. No dynamic code is required when entering
7525 a frame containing an exception handler. When an exception is
7526 raised, the tables are used to control a back trace of the
7527 subprogram invocation stack to locate the required exception
7528 handler. This method has considerably poorer performance for
7529 the propagation of exceptions, but there is no overhead for
7530 exception handlers if no exception is raised. Note that in this
7531 mode and in the context of mixed Ada and C/C++ programming,
7532 to propagate an exception through a C/C++ code, the C/C++ code
7533 must be compiled with the @option{-funwind-tables} GCC's
7534 option.
7535
7536 The following switches may be used to control which of the
7537 two exception handling methods is used.
7538
7539 @table @option
7540 @c !sort!
7541
7542 @item --RTS=sjlj
7543 @cindex @option{--RTS=sjlj} (@command{gnatmake})
7544 This switch causes the setjmp/longjmp run-time (when available) to be used
7545 for exception handling. If the default
7546 mechanism for the target is zero cost exceptions, then
7547 this switch can be used to modify this default, and must be
7548 used for all units in the partition.
7549 This option is rarely used. One case in which it may be
7550 advantageous is if you have an application where exception
7551 raising is common and the overall performance of the
7552 application is improved by favoring exception propagation.
7553
7554 @item --RTS=zcx
7555 @cindex @option{--RTS=zcx} (@command{gnatmake})
7556 @cindex Zero Cost Exceptions
7557 This switch causes the zero cost approach to be used
7558 for exception handling. If this is the default mechanism for the
7559 target (see below), then this switch is unneeded. If the default
7560 mechanism for the target is setjmp/longjmp exceptions, then
7561 this switch can be used to modify this default, and must be
7562 used for all units in the partition.
7563 This option can only be used if the zero cost approach
7564 is available for the target in use, otherwise it will generate an error.
7565 @end table
7566
7567 @noindent
7568 The same option @option{--RTS} must be used both for @command{gcc}
7569 and @command{gnatbind}. Passing this option to @command{gnatmake}
7570 (@pxref{Switches for gnatmake}) will ensure the required consistency
7571 through the compilation and binding steps.
7572
7573 @node Units to Sources Mapping Files
7574 @subsection Units to Sources Mapping Files
7575
7576 @table @option
7577
7578 @item -gnatem=@var{path}
7579 @cindex @option{-gnatem} (@command{gcc})
7580 A mapping file is a way to communicate to the compiler two mappings:
7581 from unit names to file names (without any directory information) and from
7582 file names to path names (with full directory information). These mappings
7583 are used by the compiler to short-circuit the path search.
7584
7585 The use of mapping files is not required for correct operation of the
7586 compiler, but mapping files can improve efficiency, particularly when
7587 sources are read over a slow network connection. In normal operation,
7588 you need not be concerned with the format or use of mapping files,
7589 and the @option{-gnatem} switch is not a switch that you would use
7590 explicitly. It is intended primarily for use by automatic tools such as
7591 @command{gnatmake} running under the project file facility. The
7592 description here of the format of mapping files is provided
7593 for completeness and for possible use by other tools.
7594
7595 A mapping file is a sequence of sets of three lines. In each set, the
7596 first line is the unit name, in lower case, with @code{%s} appended
7597 for specs and @code{%b} appended for bodies; the second line is the
7598 file name; and the third line is the path name.
7599
7600 Example:
7601 @smallexample
7602    main%b
7603    main.2.ada
7604    /gnat/project1/sources/main.2.ada
7605 @end smallexample
7606
7607 When the switch @option{-gnatem} is specified, the compiler will
7608 create in memory the two mappings from the specified file. If there is
7609 any problem (nonexistent file, truncated file or duplicate entries),
7610 no mapping will be created.
7611
7612 Several @option{-gnatem} switches may be specified; however, only the
7613 last one on the command line will be taken into account.
7614
7615 When using a project file, @command{gnatmake} creates a temporary
7616 mapping file and communicates it to the compiler using this switch.
7617
7618 @end table
7619
7620 @node Integrated Preprocessing
7621 @subsection Integrated Preprocessing
7622
7623 @noindent
7624 GNAT sources may be preprocessed immediately before compilation.
7625 In this case, the actual
7626 text of the source is not the text of the source file, but is derived from it
7627 through a process called preprocessing. Integrated preprocessing is specified
7628 through switches @option{-gnatep} and/or @option{-gnateD}. @option{-gnatep}
7629 indicates, through a text file, the preprocessing data to be used.
7630 @option{-gnateD} specifies or modifies the values of preprocessing symbol.
7631
7632 @noindent
7633 Note that when integrated preprocessing is used, the output from the
7634 preprocessor is not written to any external file. Instead it is passed
7635 internally to the compiler. If you need to preserve the result of
7636 preprocessing in a file, then you should use @command{gnatprep}
7637 to perform the desired preprocessing in stand-alone mode.
7638
7639 @noindent
7640 It is recommended that @command{gnatmake} switch ^-s^/SWITCH_CHECK^ should be
7641 used when Integrated Preprocessing is used. The reason is that preprocessing
7642 with another Preprocessing Data file without changing the sources will
7643 not trigger recompilation without this switch.
7644
7645 @noindent
7646 Note that @command{gnatmake} switch ^-m^/MINIMAL_RECOMPILATION^ will almost
7647 always trigger recompilation for sources that are preprocessed,
7648 because @command{gnatmake} cannot compute the checksum of the source after
7649 preprocessing.
7650
7651 @noindent
7652 The actual preprocessing function is described in details in section
7653 @ref{Preprocessing Using gnatprep}. This section only describes how integrated
7654 preprocessing is triggered and parameterized.
7655
7656 @table @code
7657
7658 @item -gnatep=@var{file}
7659 @cindex @option{-gnatep} (@command{gcc})
7660 This switch indicates to the compiler the file name (without directory
7661 information) of the preprocessor data file to use. The preprocessor data file
7662 should be found in the source directories. Note that when the compiler is
7663 called by a builder (@command{gnatmake} or @command{gprbuild}) with a project
7664 file, if the object directory is not also a source directory, the builder needs
7665 to be called with @option{-x}.
7666
7667 @noindent
7668 A preprocessing data file is a text file with significant lines indicating
7669 how should be preprocessed either a specific source or all sources not
7670 mentioned in other lines. A significant line is a nonempty, non-comment line.
7671 Comments are similar to Ada comments.
7672
7673 @noindent
7674 Each significant line starts with either a literal string or the character '*'.
7675 A literal string is the file name (without directory information) of the source
7676 to preprocess. A character '*' indicates the preprocessing for all the sources
7677 that are not specified explicitly on other lines (order of the lines is not
7678 significant). It is an error to have two lines with the same file name or two
7679 lines starting with the character '*'.
7680
7681 @noindent
7682 After the file name or the character '*', another optional literal string
7683 indicating the file name of the definition file to be used for preprocessing
7684 (@pxref{Form of Definitions File}). The definition files are found by the
7685 compiler in one of the source directories. In some cases, when compiling
7686 a source in a directory other than the current directory, if the definition
7687 file is in the current directory, it may be necessary to add the current
7688 directory as a source directory through switch ^-I.^/SEARCH=[]^, otherwise
7689 the compiler would not find the definition file.
7690
7691 @noindent
7692 Then, optionally, ^switches^switches^ similar to those of @code{gnatprep} may
7693 be found. Those ^switches^switches^ are:
7694
7695 @table @code
7696
7697 @item -b
7698 Causes both preprocessor lines and the lines deleted by
7699 preprocessing to be replaced by blank lines, preserving the line number.
7700 This ^switch^switch^ is always implied; however, if specified after @option{-c}
7701 it cancels the effect of @option{-c}.
7702
7703 @item -c
7704 Causes both preprocessor lines and the lines deleted
7705 by preprocessing to be retained as comments marked
7706 with the special string ``@code{--! }''.
7707
7708 @item -Dsymbol=value
7709 Define or redefine a symbol, associated with value. A symbol is an Ada
7710 identifier, or an Ada reserved word, with the exception of @code{if},
7711 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7712 @code{value} is either a literal string, an Ada identifier or any Ada reserved
7713 word. A symbol declared with this ^switch^switch^ replaces a symbol with the
7714 same name defined in a definition file.
7715
7716 @item -s
7717 Causes a sorted list of symbol names and values to be
7718 listed on the standard output file.
7719
7720 @item -u
7721 Causes undefined symbols to be treated as having the value @code{FALSE}
7722 in the context
7723 of a preprocessor test. In the absence of this option, an undefined symbol in
7724 a @code{#if} or @code{#elsif} test will be treated as an error.
7725
7726 @end table
7727
7728 @noindent
7729 Examples of valid lines in a preprocessor data file:
7730
7731 @smallexample
7732   "toto.adb"  "prep.def" -u
7733   --  preprocess "toto.adb", using definition file "prep.def",
7734   --  undefined symbol are False.
7735
7736   * -c -DVERSION=V101
7737   --  preprocess all other sources without a definition file;
7738   --  suppressed lined are commented; symbol VERSION has the value V101.
7739
7740   "titi.adb" "prep2.def" -s
7741   --  preprocess "titi.adb", using definition file "prep2.def";
7742   --  list all symbols with their values.
7743 @end smallexample
7744
7745 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=value@r{]}
7746 @cindex @option{-gnateD} (@command{gcc})
7747 Define or redefine a preprocessing symbol, associated with value. If no value
7748 is given on the command line, then the value of the symbol is @code{True}.
7749 A symbol is an identifier, following normal Ada (case-insensitive)
7750 rules for its syntax, and value is any sequence (including an empty sequence)
7751 of characters from the set (letters, digits, period, underline).
7752 Ada reserved words may be used as symbols, with the exceptions of @code{if},
7753 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7754
7755 @noindent
7756 A symbol declared with this ^switch^switch^ on the command line replaces a
7757 symbol with the same name either in a definition file or specified with a
7758 ^switch^switch^ -D in the preprocessor data file.
7759
7760 @noindent
7761 This switch is similar to switch @option{^-D^/ASSOCIATE^} of @code{gnatprep}.
7762
7763 @item -gnateG
7764 When integrated preprocessing is performed and the preprocessor modifies
7765 the source text, write the result of this preprocessing into a file
7766 <source>^.prep^_prep^.
7767
7768 @end table
7769
7770 @node Code Generation Control
7771 @subsection Code Generation Control
7772
7773 @noindent
7774
7775 The GCC technology provides a wide range of target dependent
7776 @option{-m} switches for controlling
7777 details of code generation with respect to different versions of
7778 architectures. This includes variations in instruction sets (e.g.@:
7779 different members of the power pc family), and different requirements
7780 for optimal arrangement of instructions (e.g.@: different members of
7781 the x86 family). The list of available @option{-m} switches may be
7782 found in the GCC documentation.
7783
7784 Use of these @option{-m} switches may in some cases result in improved
7785 code performance.
7786
7787 The @value{EDITION} technology is tested and qualified without any
7788 @option{-m} switches,
7789 so generally the most reliable approach is to avoid the use of these
7790 switches. However, we generally expect most of these switches to work
7791 successfully with @value{EDITION}, and many customers have reported successful
7792 use of these options.
7793
7794 Our general advice is to avoid the use of @option{-m} switches unless
7795 special needs lead to requirements in this area. In particular,
7796 there is no point in using @option{-m} switches to improve performance
7797 unless you actually see a performance improvement.
7798
7799 @ifset vms
7800 @node Return Codes
7801 @subsection Return Codes
7802 @cindex Return Codes
7803 @cindex @option{/RETURN_CODES=VMS}
7804
7805 @noindent
7806 On VMS, GNAT compiled programs return POSIX-style codes by default,
7807 e.g.@: @option{/RETURN_CODES=POSIX}.
7808
7809 To enable VMS style return codes, use GNAT BIND and LINK with the option
7810 @option{/RETURN_CODES=VMS}. For example:
7811
7812 @smallexample
7813 GNAT BIND MYMAIN.ALI /RETURN_CODES=VMS
7814 GNAT LINK MYMAIN.ALI /RETURN_CODES=VMS
7815 @end smallexample
7816
7817 @noindent
7818 Programs built with /RETURN_CODES=VMS are suitable to be called in
7819 VMS DCL scripts. Programs compiled with the default /RETURN_CODES=POSIX
7820 are suitable for spawning with appropriate GNAT RTL routines.
7821
7822 @end ifset
7823
7824 @node Search Paths and the Run-Time Library (RTL)
7825 @section Search Paths and the Run-Time Library (RTL)
7826
7827 @noindent
7828 With the GNAT source-based library system, the compiler must be able to
7829 find source files for units that are needed by the unit being compiled.
7830 Search paths are used to guide this process.
7831
7832 The compiler compiles one source file whose name must be given
7833 explicitly on the command line. In other words, no searching is done
7834 for this file. To find all other source files that are needed (the most
7835 common being the specs of units), the compiler examines the following
7836 directories, in the following order:
7837
7838 @enumerate
7839 @item
7840 The directory containing the source file of the main unit being compiled
7841 (the file name on the command line).
7842
7843 @item
7844 Each directory named by an @option{^-I^/SOURCE_SEARCH^} switch given on the
7845 @command{gcc} command line, in the order given.
7846
7847 @item
7848 @findex ADA_PRJ_INCLUDE_FILE
7849 Each of the directories listed in the text file whose name is given
7850 by the @env{ADA_PRJ_INCLUDE_FILE} ^environment variable^logical name^.
7851
7852 @noindent
7853 @env{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
7854 driver when project files are used. It should not normally be set
7855 by other means.
7856
7857 @item
7858 @findex ADA_INCLUDE_PATH
7859 Each of the directories listed in the value of the
7860 @env{ADA_INCLUDE_PATH} ^environment variable^logical name^.
7861 @ifclear vms
7862 Construct this value
7863 exactly as the @env{PATH} environment variable: a list of directory
7864 names separated by colons (semicolons when working with the NT version).
7865 @end ifclear
7866 @ifset vms
7867 Normally, define this value as a logical name containing a comma separated
7868 list of directory names.
7869
7870 This variable can also be defined by means of an environment string
7871 (an argument to the HP C exec* set of functions).
7872
7873 Logical Name:
7874 @smallexample
7875 DEFINE ANOTHER_PATH FOO:[BAG]
7876 DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
7877 @end smallexample
7878
7879 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
7880 first, followed by the standard Ada
7881 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADAINCLUDE].
7882 If this is not redefined, the user will obtain the HP Ada 83 IO packages
7883 (Text_IO, Sequential_IO, etc)
7884 instead of the standard Ada packages. Thus, in order to get the standard Ada
7885 packages by default, ADA_INCLUDE_PATH must be redefined.
7886 @end ifset
7887
7888 @item
7889 The content of the @file{ada_source_path} file which is part of the GNAT
7890 installation tree and is used to store standard libraries such as the
7891 GNAT Run Time Library (RTL) source files.
7892 @ifclear vms
7893 @ref{Installing a library}
7894 @end ifclear
7895 @end enumerate
7896
7897 @noindent
7898 Specifying the switch @option{^-I-^/NOCURRENT_DIRECTORY^}
7899 inhibits the use of the directory
7900 containing the source file named in the command line. You can still
7901 have this directory on your search path, but in this case it must be
7902 explicitly requested with a @option{^-I^/SOURCE_SEARCH^} switch.
7903
7904 Specifying the switch @option{-nostdinc}
7905 inhibits the search of the default location for the GNAT Run Time
7906 Library (RTL) source files.
7907
7908 The compiler outputs its object files and ALI files in the current
7909 working directory.
7910 @ifclear vms
7911 Caution: The object file can be redirected with the @option{-o} switch;
7912 however, @command{gcc} and @code{gnat1} have not been coordinated on this
7913 so the @file{ALI} file will not go to the right place. Therefore, you should
7914 avoid using the @option{-o} switch.
7915 @end ifclear
7916
7917 @findex System.IO
7918 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
7919 children make up the GNAT RTL, together with the simple @code{System.IO}
7920 package used in the @code{"Hello World"} example. The sources for these units
7921 are needed by the compiler and are kept together in one directory. Not
7922 all of the bodies are needed, but all of the sources are kept together
7923 anyway. In a normal installation, you need not specify these directory
7924 names when compiling or binding. Either the environment variables or
7925 the built-in defaults cause these files to be found.
7926
7927 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
7928 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
7929 consisting of child units of @code{GNAT}. This is a collection of generally
7930 useful types, subprograms, etc. @xref{Top, GNAT Reference Manual, About
7931 This Guid, gnat_rm, GNAT Reference Manual}, for further details.
7932
7933 Besides simplifying access to the RTL, a major use of search paths is
7934 in compiling sources from multiple directories. This can make
7935 development environments much more flexible.
7936
7937 @node Order of Compilation Issues
7938 @section Order of Compilation Issues
7939
7940 @noindent
7941 If, in our earlier example, there was a spec for the @code{hello}
7942 procedure, it would be contained in the file @file{hello.ads}; yet this
7943 file would not have to be explicitly compiled. This is the result of the
7944 model we chose to implement library management. Some of the consequences
7945 of this model are as follows:
7946
7947 @itemize @bullet
7948 @item
7949 There is no point in compiling specs (except for package
7950 specs with no bodies) because these are compiled as needed by clients. If
7951 you attempt a useless compilation, you will receive an error message.
7952 It is also useless to compile subunits because they are compiled as needed
7953 by the parent.
7954
7955 @item
7956 There are no order of compilation requirements: performing a
7957 compilation never obsoletes anything. The only way you can obsolete
7958 something and require recompilations is to modify one of the
7959 source files on which it depends.
7960
7961 @item
7962 There is no library as such, apart from the ALI files
7963 (@pxref{The Ada Library Information Files}, for information on the format
7964 of these files). For now we find it convenient to create separate ALI files,
7965 but eventually the information therein may be incorporated into the object
7966 file directly.
7967
7968 @item
7969 When you compile a unit, the source files for the specs of all units
7970 that it @code{with}'s, all its subunits, and the bodies of any generics it
7971 instantiates must be available (reachable by the search-paths mechanism
7972 described above), or you will receive a fatal error message.
7973 @end itemize
7974
7975 @node Examples
7976 @section Examples
7977
7978 @noindent
7979 The following are some typical Ada compilation command line examples:
7980
7981 @table @code
7982 @item $ gcc -c xyz.adb
7983 Compile body in file @file{xyz.adb} with all default options.
7984
7985 @ifclear vms
7986 @item $ gcc -c -O2 -gnata xyz-def.adb
7987 @end ifclear
7988 @ifset vms
7989 @item $ GNAT COMPILE /OPTIMIZE=ALL -gnata xyz-def.adb
7990 @end ifset
7991
7992 Compile the child unit package in file @file{xyz-def.adb} with extensive
7993 optimizations, and pragma @code{Assert}/@code{Debug} statements
7994 enabled.
7995
7996 @item $ gcc -c -gnatc abc-def.adb
7997 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
7998 mode.
7999 @end table
8000
8001 @node Binding Using gnatbind
8002 @chapter Binding Using @code{gnatbind}
8003 @findex gnatbind
8004
8005 @menu
8006 * Running gnatbind::
8007 * Switches for gnatbind::
8008 * Command-Line Access::
8009 * Search Paths for gnatbind::
8010 * Examples of gnatbind Usage::
8011 @end menu
8012
8013 @noindent
8014 This chapter describes the GNAT binder, @code{gnatbind}, which is used
8015 to bind compiled GNAT objects.
8016
8017 Note: to invoke @code{gnatbind} with a project file, use the @code{gnat}
8018 driver (see @ref{The GNAT Driver and Project Files}).
8019
8020 The @code{gnatbind} program performs four separate functions:
8021
8022 @enumerate
8023 @item
8024 Checks that a program is consistent, in accordance with the rules in
8025 Chapter 10 of the Ada Reference Manual. In particular, error
8026 messages are generated if a program uses inconsistent versions of a
8027 given unit.
8028
8029 @item
8030 Checks that an acceptable order of elaboration exists for the program
8031 and issues an error message if it cannot find an order of elaboration
8032 that satisfies the rules in Chapter 10 of the Ada Language Manual.
8033
8034 @item
8035 Generates a main program incorporating the given elaboration order.
8036 This program is a small Ada package (body and spec) that
8037 must be subsequently compiled
8038 using the GNAT compiler. The necessary compilation step is usually
8039 performed automatically by @command{gnatlink}. The two most important
8040 functions of this program
8041 are to call the elaboration routines of units in an appropriate order
8042 and to call the main program.
8043
8044 @item
8045 Determines the set of object files required by the given main program.
8046 This information is output in the forms of comments in the generated program,
8047 to be read by the @command{gnatlink} utility used to link the Ada application.
8048 @end enumerate
8049
8050 @node Running gnatbind
8051 @section Running @code{gnatbind}
8052
8053 @noindent
8054 The form of the @code{gnatbind} command is
8055
8056 @smallexample
8057 @c $ gnatbind @ovar{switches} @var{mainprog}@r{[}.ali@r{]} @ovar{switches}
8058 @c Expanding @ovar macro inline (explanation in macro def comments)
8059 $ gnatbind @r{[}@var{switches}@r{]} @var{mainprog}@r{[}.ali@r{]} @r{[}@var{switches}@r{]}
8060 @end smallexample
8061
8062 @noindent
8063 where @file{@var{mainprog}.adb} is the Ada file containing the main program
8064 unit body. @code{gnatbind} constructs an Ada
8065 package in two files whose names are
8066 @file{b~@var{mainprog}.ads}, and @file{b~@var{mainprog}.adb}.
8067 For example, if given the
8068 parameter @file{hello.ali}, for a main program contained in file
8069 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
8070 and @file{b~hello.adb}.
8071
8072 When doing consistency checking, the binder takes into consideration
8073 any source files it can locate. For example, if the binder determines
8074 that the given main program requires the package @code{Pack}, whose
8075 @file{.ALI}
8076 file is @file{pack.ali} and whose corresponding source spec file is
8077 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
8078 (using the same search path conventions as previously described for the
8079 @command{gcc} command). If it can locate this source file, it checks that
8080 the time stamps
8081 or source checksums of the source and its references to in @file{ALI} files
8082 match. In other words, any @file{ALI} files that mentions this spec must have
8083 resulted from compiling this version of the source file (or in the case
8084 where the source checksums match, a version close enough that the
8085 difference does not matter).
8086
8087 @cindex Source files, use by binder
8088 The effect of this consistency checking, which includes source files, is
8089 that the binder ensures that the program is consistent with the latest
8090 version of the source files that can be located at bind time. Editing a
8091 source file without compiling files that depend on the source file cause
8092 error messages to be generated by the binder.
8093
8094 For example, suppose you have a main program @file{hello.adb} and a
8095 package @code{P}, from file @file{p.ads} and you perform the following
8096 steps:
8097
8098 @enumerate
8099 @item
8100 Enter @code{gcc -c hello.adb} to compile the main program.
8101
8102 @item
8103 Enter @code{gcc -c p.ads} to compile package @code{P}.
8104
8105 @item
8106 Edit file @file{p.ads}.
8107
8108 @item
8109 Enter @code{gnatbind hello}.
8110 @end enumerate
8111
8112 @noindent
8113 At this point, the file @file{p.ali} contains an out-of-date time stamp
8114 because the file @file{p.ads} has been edited. The attempt at binding
8115 fails, and the binder generates the following error messages:
8116
8117 @smallexample
8118 error: "hello.adb" must be recompiled ("p.ads" has been modified)
8119 error: "p.ads" has been modified and must be recompiled
8120 @end smallexample
8121
8122 @noindent
8123 Now both files must be recompiled as indicated, and then the bind can
8124 succeed, generating a main program. You need not normally be concerned
8125 with the contents of this file, but for reference purposes a sample
8126 binder output file is given in @ref{Example of Binder Output File}.
8127
8128 In most normal usage, the default mode of @command{gnatbind} which is to
8129 generate the main package in Ada, as described in the previous section.
8130 In particular, this means that any Ada programmer can read and understand
8131 the generated main program. It can also be debugged just like any other
8132 Ada code provided the @option{^-g^/DEBUG^} switch is used for
8133 @command{gnatbind} and @command{gnatlink}.
8134
8135 @node Switches for gnatbind
8136 @section Switches for @command{gnatbind}
8137
8138 @noindent
8139 The following switches are available with @code{gnatbind}; details will
8140 be presented in subsequent sections.
8141
8142 @menu
8143 * Consistency-Checking Modes::
8144 * Binder Error Message Control::
8145 * Elaboration Control::
8146 * Output Control::
8147 * Dynamic Allocation Control::
8148 * Binding with Non-Ada Main Programs::
8149 * Binding Programs with No Main Subprogram::
8150 @end menu
8151
8152 @table @option
8153 @c !sort!
8154
8155 @item --version
8156 @cindex @option{--version} @command{gnatbind}
8157 Display Copyright and version, then exit disregarding all other options.
8158
8159 @item --help
8160 @cindex @option{--help} @command{gnatbind}
8161 If @option{--version} was not used, display usage, then exit disregarding
8162 all other options.
8163
8164 @item -a
8165 @cindex @option{-a} @command{gnatbind}
8166 Indicates that, if supported by the platform, the adainit procedure should
8167 be treated as an initialisation routine by the linker (a constructor). This
8168 is intended to be used by the Project Manager to automatically initialize
8169 shared Stand-Alone Libraries.
8170
8171 @item ^-aO^/OBJECT_SEARCH^
8172 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatbind})
8173 Specify directory to be searched for ALI files.
8174
8175 @item ^-aI^/SOURCE_SEARCH^
8176 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
8177 Specify directory to be searched for source file.
8178
8179 @item ^-A^/ALI_LIST^@r{[=}@var{filename}@r{]}
8180 @cindex @option{^-A^/ALI_LIST^} (@command{gnatbind})
8181 Output ALI list (to standard output or to the named file).
8182
8183 @item ^-b^/REPORT_ERRORS=BRIEF^
8184 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@command{gnatbind})
8185 Generate brief messages to @file{stderr} even if verbose mode set.
8186
8187 @item ^-c^/NOOUTPUT^
8188 @cindex @option{^-c^/NOOUTPUT^} (@command{gnatbind})
8189 Check only, no generation of binder output file.
8190
8191 @item ^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
8192 @cindex @option{^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}} (@command{gnatbind})
8193 This switch can be used to change the default task stack size value
8194 to a specified size @var{nn}, which is expressed in bytes by default, or
8195 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8196 with @var{m}.
8197 In the absence of a @samp{@r{[}k@r{|}m@r{]}} suffix, this switch is equivalent,
8198 in effect, to completing all task specs with
8199 @smallexample @c ada
8200    pragma Storage_Size (nn);
8201 @end smallexample
8202 When they do not already have such a pragma.
8203
8204 @item ^-D^/DEFAULT_SECONDARY_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
8205 @cindex @option{^-D^/DEFAULT_SECONDARY_STACK_SIZE=nnnnn^} (@command{gnatbind})
8206 This switch can be used to change the default secondary stack size value
8207 to a specified size @var{nn}, which is expressed in bytes by default, or
8208 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8209 with @var{m}.
8210
8211 The secondary stack is used to deal with functions that return a variable
8212 sized result, for example a function returning an unconstrained
8213 String. There are two ways in which this secondary stack is allocated.
8214
8215 For most targets, the secondary stack is growing on demand and is allocated
8216 as a chain of blocks in the heap. The -D option is not very
8217 relevant. It only give some control over the size of the allocated
8218 blocks (whose size is the minimum of the default secondary stack size value,
8219 and the actual size needed for the current allocation request).
8220
8221 For certain targets, notably VxWorks 653,
8222 the secondary stack is allocated by carving off a fixed ratio chunk of the
8223 primary task stack. The -D option is used to define the
8224 size of the environment task's secondary stack.
8225
8226 @item ^-e^/ELABORATION_DEPENDENCIES^
8227 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@command{gnatbind})
8228 Output complete list of elaboration-order dependencies.
8229
8230 @item ^-E^/STORE_TRACEBACKS^
8231 @cindex @option{^-E^/STORE_TRACEBACKS^} (@command{gnatbind})
8232 Store tracebacks in exception occurrences when the target supports it.
8233 @ignore
8234 @c The following may get moved to an appendix
8235 This option is currently supported on the following targets:
8236 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
8237 @end ignore
8238 See also the packages @code{GNAT.Traceback} and
8239 @code{GNAT.Traceback.Symbolic} for more information.
8240 @ifclear vms
8241 Note that on x86 ports, you must not use @option{-fomit-frame-pointer}
8242 @command{gcc} option.
8243 @end ifclear
8244
8245 @item ^-F^/FORCE_ELABS_FLAGS^
8246 @cindex @option{^-F^/FORCE_ELABS_FLAGS^} (@command{gnatbind})
8247 Force the checks of elaboration flags. @command{gnatbind} does not normally
8248 generate checks of elaboration flags for the main executable, except when
8249 a Stand-Alone Library is used. However, there are cases when this cannot be
8250 detected by gnatbind. An example is importing an interface of a Stand-Alone
8251 Library through a pragma Import and only specifying through a linker switch
8252 this Stand-Alone Library. This switch is used to guarantee that elaboration
8253 flag checks are generated.
8254
8255 @item ^-h^/HELP^
8256 @cindex @option{^-h^/HELP^} (@command{gnatbind})
8257 Output usage (help) information
8258
8259 @item ^-H32^/32_MALLOC^
8260 @cindex @option{^-H32^/32_MALLOC^} (@command{gnatbind})
8261 Use 32-bit allocations for @code{__gnat_malloc} (and thus for access types).
8262 For further details see @ref{Dynamic Allocation Control}.
8263
8264 @item ^-H64^/64_MALLOC^
8265 @cindex @option{^-H64^/64_MALLOC^} (@command{gnatbind})
8266 Use 64-bit allocations for @code{__gnat_malloc} (and thus for access types).
8267 @cindex @code{__gnat_malloc}
8268 For further details see @ref{Dynamic Allocation Control}.
8269
8270 @item ^-I^/SEARCH^
8271 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8272 Specify directory to be searched for source and ALI files.
8273
8274 @item ^-I-^/NOCURRENT_DIRECTORY^
8275 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatbind})
8276 Do not look for sources in the current directory where @code{gnatbind} was
8277 invoked, and do not look for ALI files in the directory containing the
8278 ALI file named in the @code{gnatbind} command line.
8279
8280 @item ^-l^/ORDER_OF_ELABORATION^
8281 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@command{gnatbind})
8282 Output chosen elaboration order.
8283
8284 @item ^-L@var{xxx}^/BUILD_LIBRARY=@var{xxx}^
8285 @cindex @option{^-L^/BUILD_LIBRARY^} (@command{gnatbind})
8286 Bind the units for library building. In this case the adainit and
8287 adafinal procedures (@pxref{Binding with Non-Ada Main Programs})
8288 are renamed to ^@var{xxx}init^@var{XXX}INIT^ and
8289 ^@var{xxx}final^@var{XXX}FINAL^.
8290 Implies ^-n^/NOCOMPILE^.
8291 @ifclear vms
8292 (@xref{GNAT and Libraries}, for more details.)
8293 @end ifclear
8294 @ifset vms
8295 On OpenVMS, these init and final procedures are exported in uppercase
8296 letters. For example if /BUILD_LIBRARY=toto is used, the exported name of
8297 the init procedure will be "TOTOINIT" and the exported name of the final
8298 procedure will be "TOTOFINAL".
8299 @end ifset
8300
8301 @item ^-Mxyz^/RENAME_MAIN=xyz^
8302 @cindex @option{^-M^/RENAME_MAIN^} (@command{gnatbind})
8303 Rename generated main program from main to xyz. This option is
8304 supported on cross environments only.
8305
8306 @item ^-m^/ERROR_LIMIT=^@var{n}
8307 @cindex @option{^-m^/ERROR_LIMIT^} (@command{gnatbind})
8308 Limit number of detected errors or warnings to @var{n}, where @var{n} is
8309 in the range 1..999999. The default value if no switch is
8310 given is 9999. If the number of warnings reaches this limit, then a
8311 message is output and further warnings are suppressed, the bind
8312 continues in this case. If the number of errors reaches this
8313 limit, then a message is output and the bind is abandoned.
8314 A value of zero means that no limit is enforced. The equal
8315 sign is optional.
8316
8317 @ifset unw
8318 Furthermore, under Windows, the sources pointed to by the libraries path
8319 set in the registry are not searched for.
8320 @end ifset
8321
8322 @item ^-n^/NOMAIN^
8323 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8324 No main program.
8325
8326 @item -nostdinc
8327 @cindex @option{-nostdinc} (@command{gnatbind})
8328 Do not look for sources in the system default directory.
8329
8330 @item -nostdlib
8331 @cindex @option{-nostdlib} (@command{gnatbind})
8332 Do not look for library files in the system default directory.
8333
8334 @item --RTS=@var{rts-path}
8335 @cindex @option{--RTS} (@code{gnatbind})
8336 Specifies the default location of the runtime library. Same meaning as the
8337 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
8338
8339 @item ^-o ^/OUTPUT=^@var{file}
8340 @cindex @option{^-o ^/OUTPUT^} (@command{gnatbind})
8341 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
8342 Note that if this option is used, then linking must be done manually,
8343 gnatlink cannot be used.
8344
8345 @item ^-O^/OBJECT_LIST^@r{[=}@var{filename}@r{]}
8346 @cindex @option{^-O^/OBJECT_LIST^} (@command{gnatbind})
8347 Output object list (to standard output or to the named file).
8348
8349 @item ^-p^/PESSIMISTIC_ELABORATION^
8350 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@command{gnatbind})
8351 Pessimistic (worst-case) elaboration order
8352
8353 @item ^-P^-P^
8354 @cindex @option{^-P^/CODEPEER^} (@command{gnatbind})
8355 Generate binder file suitable for CodePeer.
8356
8357 @item ^-R^-R^
8358 @cindex @option{^-R^-R^} (@command{gnatbind})
8359 Output closure source list.
8360
8361 @item ^-s^/READ_SOURCES=ALL^
8362 @cindex @option{^-s^/READ_SOURCES=ALL^} (@command{gnatbind})
8363 Require all source files to be present.
8364
8365 @item ^-S@var{xxx}^/INITIALIZE_SCALARS=@var{xxx}^
8366 @cindex @option{^-S^/INITIALIZE_SCALARS^} (@command{gnatbind})
8367 Specifies the value to be used when detecting uninitialized scalar
8368 objects with pragma Initialize_Scalars.
8369 The @var{xxx} ^string specified with the switch^option^ may be either
8370 @itemize @bullet
8371 @item ``@option{^in^INVALID^}'' requesting an invalid value where possible
8372 @item ``@option{^lo^LOW^}'' for the lowest possible value
8373 @item ``@option{^hi^HIGH^}'' for the highest possible value
8374 @item ``@option{@var{xx}}'' for a value consisting of repeated bytes with the
8375 value @code{16#@var{xx}#} (i.e., @var{xx} is a string of two hexadecimal digits).
8376 @end itemize
8377
8378 In addition, you can specify @option{-Sev} to indicate that the value is
8379 to be set at run time. In this case, the program will look for an environment
8380 @cindex GNAT_INIT_SCALARS
8381 variable of the form @env{GNAT_INIT_SCALARS=@var{xx}}, where @var{xx} is one
8382 of @option{in/lo/hi/@var{xx}} with the same meanings as above.
8383 If no environment variable is found, or if it does not have a valid value,
8384 then the default is @option{in} (invalid values).
8385
8386 @ifclear vms
8387 @item -static
8388 @cindex @option{-static} (@code{gnatbind})
8389 Link against a static GNAT run time.
8390
8391 @item -shared
8392 @cindex @option{-shared} (@code{gnatbind})
8393 Link against a shared GNAT run time when available.
8394 @end ifclear
8395
8396 @item ^-t^/NOTIME_STAMP_CHECK^
8397 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8398 Tolerate time stamp and other consistency errors
8399
8400 @item ^-T@var{n}^/TIME_SLICE=@var{n}^
8401 @cindex @option{^-T^/TIME_SLICE^} (@code{gnatbind})
8402 Set the time slice value to @var{n} milliseconds. If the system supports
8403 the specification of a specific time slice value, then the indicated value
8404 is used. If the system does not support specific time slice values, but
8405 does support some general notion of round-robin scheduling, then any
8406 nonzero value will activate round-robin scheduling.
8407
8408 A value of zero is treated specially. It turns off time
8409 slicing, and in addition, indicates to the tasking run time that the
8410 semantics should match as closely as possible the Annex D
8411 requirements of the Ada RM, and in particular sets the default
8412 scheduling policy to @code{FIFO_Within_Priorities}.
8413
8414 @item ^-u@var{n}^/DYNAMIC_STACK_USAGE=@var{n}^
8415 @cindex @option{^-u^/DYNAMIC_STACK_USAGE^} (@code{gnatbind})
8416 Enable dynamic stack usage, with @var{n} results stored and displayed
8417 at program termination. A result is generated when a task
8418 terminates. Results that can't be stored are displayed on the fly, at
8419 task termination. This option is currently not supported on Itanium
8420 platforms. (See @ref{Dynamic Stack Usage Analysis} for details.)
8421
8422 @item ^-v^/REPORT_ERRORS=VERBOSE^
8423 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8424 Verbose mode. Write error messages, header, summary output to
8425 @file{stdout}.
8426
8427 @ifclear vms
8428 @item -w@var{x}
8429 @cindex @option{-w} (@code{gnatbind})
8430 Warning mode (@var{x}=s/e for suppress/treat as error)
8431 @end ifclear
8432
8433 @ifset vms
8434 @item /WARNINGS=NORMAL
8435 @cindex @option{/WARNINGS} (@code{gnatbind})
8436 Normal warnings mode. Warnings are issued but ignored
8437
8438 @item /WARNINGS=SUPPRESS
8439 @cindex @option{/WARNINGS} (@code{gnatbind})
8440 All warning messages are suppressed
8441
8442 @item /WARNINGS=ERROR
8443 @cindex @option{/WARNINGS} (@code{gnatbind})
8444 Warning messages are treated as fatal errors
8445 @end ifset
8446
8447 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8448 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8449 Override default wide character encoding for standard Text_IO files.
8450
8451 @item ^-x^/READ_SOURCES=NONE^
8452 @cindex @option{^-x^/READ_SOURCES^} (@code{gnatbind})
8453 Exclude source files (check object consistency only).
8454
8455 @ifset vms
8456 @item /READ_SOURCES=AVAILABLE
8457 @cindex @option{/READ_SOURCES} (@code{gnatbind})
8458 Default mode, in which sources are checked for consistency only if
8459 they are available.
8460 @end ifset
8461
8462 @item ^-y^/ENABLE_LEAP_SECONDS^
8463 @cindex @option{^-y^/ENABLE_LEAP_SECONDS^} (@code{gnatbind})
8464 Enable leap seconds support in @code{Ada.Calendar} and its children.
8465
8466 @item ^-z^/ZERO_MAIN^
8467 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8468 No main subprogram.
8469 @end table
8470
8471 @ifclear vms
8472 @noindent
8473 You may obtain this listing of switches by running @code{gnatbind} with
8474 no arguments.
8475 @end ifclear
8476
8477 @node Consistency-Checking Modes
8478 @subsection Consistency-Checking Modes
8479
8480 @noindent
8481 As described earlier, by default @code{gnatbind} checks
8482 that object files are consistent with one another and are consistent
8483 with any source files it can locate. The following switches control binder
8484 access to sources.
8485
8486 @table @option
8487 @c !sort!
8488 @item ^-s^/READ_SOURCES=ALL^
8489 @cindex @option{^-s^/READ_SOURCES=ALL^} (@code{gnatbind})
8490 Require source files to be present. In this mode, the binder must be
8491 able to locate all source files that are referenced, in order to check
8492 their consistency. In normal mode, if a source file cannot be located it
8493 is simply ignored. If you specify this switch, a missing source
8494 file is an error.
8495
8496 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8497 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8498 Override default wide character encoding for standard Text_IO files.
8499 Normally the default wide character encoding method used for standard
8500 [Wide_[Wide_]]Text_IO files is taken from the encoding specified for
8501 the main source input (see description of switch
8502 @option{^-gnatWx^/WIDE_CHARACTER_ENCODING^} for the compiler). The
8503 use of this switch for the binder (which has the same set of
8504 possible arguments) overrides this default as specified.
8505
8506 @item ^-x^/READ_SOURCES=NONE^
8507 @cindex @option{^-x^/READ_SOURCES=NONE^} (@code{gnatbind})
8508 Exclude source files. In this mode, the binder only checks that ALI
8509 files are consistent with one another. Source files are not accessed.
8510 The binder runs faster in this mode, and there is still a guarantee that
8511 the resulting program is self-consistent.
8512 If a source file has been edited since it was last compiled, and you
8513 specify this switch, the binder will not detect that the object
8514 file is out of date with respect to the source file. Note that this is the
8515 mode that is automatically used by @command{gnatmake} because in this
8516 case the checking against sources has already been performed by
8517 @command{gnatmake} in the course of compilation (i.e.@: before binding).
8518
8519 @ifset vms
8520 @item /READ_SOURCES=AVAILABLE
8521 @cindex @code{/READ_SOURCES=AVAILABLE} (@code{gnatbind})
8522 This is the default mode in which source files are checked if they are
8523 available, and ignored if they are not available.
8524 @end ifset
8525 @end table
8526
8527 @node Binder Error Message Control
8528 @subsection Binder Error Message Control
8529
8530 @noindent
8531 The following switches provide control over the generation of error
8532 messages from the binder:
8533
8534 @table @option
8535 @c !sort!
8536 @item ^-v^/REPORT_ERRORS=VERBOSE^
8537 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8538 Verbose mode. In the normal mode, brief error messages are generated to
8539 @file{stderr}. If this switch is present, a header is written
8540 to @file{stdout} and any error messages are directed to @file{stdout}.
8541 All that is written to @file{stderr} is a brief summary message.
8542
8543 @item ^-b^/REPORT_ERRORS=BRIEF^
8544 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@code{gnatbind})
8545 Generate brief error messages to @file{stderr} even if verbose mode is
8546 specified. This is relevant only when used with the
8547 @option{^-v^/REPORT_ERRORS=VERBOSE^} switch.
8548
8549 @ifclear vms
8550 @item -m@var{n}
8551 @cindex @option{-m} (@code{gnatbind})
8552 Limits the number of error messages to @var{n}, a decimal integer in the
8553 range 1-999. The binder terminates immediately if this limit is reached.
8554
8555 @item -M@var{xxx}
8556 @cindex @option{-M} (@code{gnatbind})
8557 Renames the generated main program from @code{main} to @code{xxx}.
8558 This is useful in the case of some cross-building environments, where
8559 the actual main program is separate from the one generated
8560 by @code{gnatbind}.
8561 @end ifclear
8562
8563 @item ^-ws^/WARNINGS=SUPPRESS^
8564 @cindex @option{^-ws^/WARNINGS=SUPPRESS^} (@code{gnatbind})
8565 @cindex Warnings
8566 Suppress all warning messages.
8567
8568 @item ^-we^/WARNINGS=ERROR^
8569 @cindex @option{^-we^/WARNINGS=ERROR^} (@code{gnatbind})
8570 Treat any warning messages as fatal errors.
8571
8572 @ifset vms
8573 @item /WARNINGS=NORMAL
8574 Standard mode with warnings generated, but warnings do not get treated
8575 as errors.
8576 @end ifset
8577
8578 @item ^-t^/NOTIME_STAMP_CHECK^
8579 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8580 @cindex Time stamp checks, in binder
8581 @cindex Binder consistency checks
8582 @cindex Consistency checks, in binder
8583 The binder performs a number of consistency checks including:
8584
8585 @itemize @bullet
8586 @item
8587 Check that time stamps of a given source unit are consistent
8588 @item
8589 Check that checksums of a given source unit are consistent
8590 @item
8591 Check that consistent versions of @code{GNAT} were used for compilation
8592 @item
8593 Check consistency of configuration pragmas as required
8594 @end itemize
8595
8596 @noindent
8597 Normally failure of such checks, in accordance with the consistency
8598 requirements of the Ada Reference Manual, causes error messages to be
8599 generated which abort the binder and prevent the output of a binder
8600 file and subsequent link to obtain an executable.
8601
8602 The @option{^-t^/NOTIME_STAMP_CHECK^} switch converts these error messages
8603 into warnings, so that
8604 binding and linking can continue to completion even in the presence of such
8605 errors. The result may be a failed link (due to missing symbols), or a
8606 non-functional executable which has undefined semantics.
8607 @emph{This means that
8608 @option{^-t^/NOTIME_STAMP_CHECK^} should be used only in unusual situations,
8609 with extreme care.}
8610 @end table
8611
8612 @node Elaboration Control
8613 @subsection Elaboration Control
8614
8615 @noindent
8616 The following switches provide additional control over the elaboration
8617 order. For full details see @ref{Elaboration Order Handling in GNAT}.
8618
8619 @table @option
8620 @item ^-p^/PESSIMISTIC_ELABORATION^
8621 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@code{gnatbind})
8622 Normally the binder attempts to choose an elaboration order that is
8623 likely to minimize the likelihood of an elaboration order error resulting
8624 in raising a @code{Program_Error} exception. This switch reverses the
8625 action of the binder, and requests that it deliberately choose an order
8626 that is likely to maximize the likelihood of an elaboration error.
8627 This is useful in ensuring portability and avoiding dependence on
8628 accidental fortuitous elaboration ordering.
8629
8630 Normally it only makes sense to use the @option{^-p^/PESSIMISTIC_ELABORATION^}
8631 switch if dynamic
8632 elaboration checking is used (@option{-gnatE} switch used for compilation).
8633 This is because in the default static elaboration mode, all necessary
8634 @code{Elaborate} and @code{Elaborate_All} pragmas are implicitly inserted.
8635 These implicit pragmas are still respected by the binder in
8636 @option{^-p^/PESSIMISTIC_ELABORATION^} mode, so a
8637 safe elaboration order is assured.
8638 @end table
8639
8640 @node Output Control
8641 @subsection Output Control
8642
8643 @noindent
8644 The following switches allow additional control over the output
8645 generated by the binder.
8646
8647 @table @option
8648 @c !sort!
8649
8650 @item ^-c^/NOOUTPUT^
8651 @cindex @option{^-c^/NOOUTPUT^} (@code{gnatbind})
8652 Check only. Do not generate the binder output file. In this mode the
8653 binder performs all error checks but does not generate an output file.
8654
8655 @item ^-e^/ELABORATION_DEPENDENCIES^
8656 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@code{gnatbind})
8657 Output complete list of elaboration-order dependencies, showing the
8658 reason for each dependency. This output can be rather extensive but may
8659 be useful in diagnosing problems with elaboration order. The output is
8660 written to @file{stdout}.
8661
8662 @item ^-h^/HELP^
8663 @cindex @option{^-h^/HELP^} (@code{gnatbind})
8664 Output usage information. The output is written to @file{stdout}.
8665
8666 @item ^-K^/LINKER_OPTION_LIST^
8667 @cindex @option{^-K^/LINKER_OPTION_LIST^} (@code{gnatbind})
8668 Output linker options to @file{stdout}. Includes library search paths,
8669 contents of pragmas Ident and Linker_Options, and libraries added
8670 by @code{gnatbind}.
8671
8672 @item ^-l^/ORDER_OF_ELABORATION^
8673 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@code{gnatbind})
8674 Output chosen elaboration order. The output is written to @file{stdout}.
8675
8676 @item ^-O^/OBJECT_LIST^
8677 @cindex @option{^-O^/OBJECT_LIST^} (@code{gnatbind})
8678 Output full names of all the object files that must be linked to provide
8679 the Ada component of the program. The output is written to @file{stdout}.
8680 This list includes the files explicitly supplied and referenced by the user
8681 as well as implicitly referenced run-time unit files. The latter are
8682 omitted if the corresponding units reside in shared libraries. The
8683 directory names for the run-time units depend on the system configuration.
8684
8685 @item ^-o ^/OUTPUT=^@var{file}
8686 @cindex @option{^-o^/OUTPUT^} (@code{gnatbind})
8687 Set name of output file to @var{file} instead of the normal
8688 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
8689 binder generated body filename.
8690 Note that if this option is used, then linking must be done manually.
8691 It is not possible to use gnatlink in this case, since it cannot locate
8692 the binder file.
8693
8694 @item ^-r^/RESTRICTION_LIST^
8695 @cindex @option{^-r^/RESTRICTION_LIST^} (@code{gnatbind})
8696 Generate list of @code{pragma Restrictions} that could be applied to
8697 the current unit. This is useful for code audit purposes, and also may
8698 be used to improve code generation in some cases.
8699
8700 @end table
8701
8702 @node Dynamic Allocation Control
8703 @subsection Dynamic Allocation Control
8704
8705 @noindent
8706 The heap control switches -- @option{-H32} and @option{-H64} --
8707 determine whether dynamic allocation uses 32-bit or 64-bit memory.
8708 They only affect compiler-generated allocations via @code{__gnat_malloc};
8709 explicit calls to @code{malloc} and related functions from the C
8710 run-time library are unaffected.
8711
8712 @table @option
8713 @item -H32
8714 Allocate memory on 32-bit heap
8715
8716 @item -H64
8717 Allocate memory on 64-bit heap.  This is the default
8718 unless explicitly overridden by a @code{'Size} clause on the access type.
8719 @end table
8720
8721 @ifset vms
8722 @noindent
8723 See also @ref{Access types and 32/64-bit allocation}.
8724 @end ifset
8725 @ifclear vms
8726 @noindent
8727 These switches are only effective on VMS platforms.
8728 @end ifclear
8729
8730
8731 @node Binding with Non-Ada Main Programs
8732 @subsection Binding with Non-Ada Main Programs
8733
8734 @noindent
8735 In our description so far we have assumed that the main
8736 program is in Ada, and that the task of the binder is to generate a
8737 corresponding function @code{main} that invokes this Ada main
8738 program. GNAT also supports the building of executable programs where
8739 the main program is not in Ada, but some of the called routines are
8740 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
8741 The following switch is used in this situation:
8742
8743 @table @option
8744 @item ^-n^/NOMAIN^
8745 @cindex @option{^-n^/NOMAIN^} (@code{gnatbind})
8746 No main program. The main program is not in Ada.
8747 @end table
8748
8749 @noindent
8750 In this case, most of the functions of the binder are still required,
8751 but instead of generating a main program, the binder generates a file
8752 containing the following callable routines:
8753
8754 @table @code
8755 @item adainit
8756 @findex adainit
8757 You must call this routine to initialize the Ada part of the program by
8758 calling the necessary elaboration routines. A call to @code{adainit} is
8759 required before the first call to an Ada subprogram.
8760
8761 Note that it is assumed that the basic execution environment must be setup
8762 to be appropriate for Ada execution at the point where the first Ada
8763 subprogram is called. In particular, if the Ada code will do any
8764 floating-point operations, then the FPU must be setup in an appropriate
8765 manner. For the case of the x86, for example, full precision mode is
8766 required. The procedure GNAT.Float_Control.Reset may be used to ensure
8767 that the FPU is in the right state.
8768
8769 @item adafinal
8770 @findex adafinal
8771 You must call this routine to perform any library-level finalization
8772 required by the Ada subprograms. A call to @code{adafinal} is required
8773 after the last call to an Ada subprogram, and before the program
8774 terminates.
8775 @end table
8776
8777 @noindent
8778 If the @option{^-n^/NOMAIN^} switch
8779 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8780 @cindex Binder, multiple input files
8781 is given, more than one ALI file may appear on
8782 the command line for @code{gnatbind}. The normal @dfn{closure}
8783 calculation is performed for each of the specified units. Calculating
8784 the closure means finding out the set of units involved by tracing
8785 @code{with} references. The reason it is necessary to be able to
8786 specify more than one ALI file is that a given program may invoke two or
8787 more quite separate groups of Ada units.
8788
8789 The binder takes the name of its output file from the last specified ALI
8790 file, unless overridden by the use of the @option{^-o file^/OUTPUT=file^}.
8791 @cindex @option{^-o^/OUTPUT^} (@command{gnatbind})
8792 The output is an Ada unit in source form that can be compiled with GNAT.
8793 This compilation occurs automatically as part of the @command{gnatlink}
8794 processing.
8795
8796 Currently the GNAT run time requires a FPU using 80 bits mode
8797 precision. Under targets where this is not the default it is required to
8798 call GNAT.Float_Control.Reset before using floating point numbers (this
8799 include float computation, float input and output) in the Ada code. A
8800 side effect is that this could be the wrong mode for the foreign code
8801 where floating point computation could be broken after this call.
8802
8803 @node Binding Programs with No Main Subprogram
8804 @subsection Binding Programs with No Main Subprogram
8805
8806 @noindent
8807 It is possible to have an Ada program which does not have a main
8808 subprogram. This program will call the elaboration routines of all the
8809 packages, then the finalization routines.
8810
8811 The following switch is used to bind programs organized in this manner:
8812
8813 @table @option
8814 @item ^-z^/ZERO_MAIN^
8815 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8816 Normally the binder checks that the unit name given on the command line
8817 corresponds to a suitable main subprogram. When this switch is used,
8818 a list of ALI files can be given, and the execution of the program
8819 consists of elaboration of these units in an appropriate order. Note
8820 that the default wide character encoding method for standard Text_IO
8821 files is always set to Brackets if this switch is set (you can use
8822 the binder switch
8823 @option{^-Wx^WIDE_CHARACTER_ENCODING^} to override this default).
8824 @end table
8825
8826 @node Command-Line Access
8827 @section Command-Line Access
8828
8829 @noindent
8830 The package @code{Ada.Command_Line} provides access to the command-line
8831 arguments and program name. In order for this interface to operate
8832 correctly, the two variables
8833
8834 @smallexample
8835 @group
8836 int gnat_argc;
8837 char **gnat_argv;
8838 @end group
8839 @end smallexample
8840
8841 @noindent
8842 @findex gnat_argv
8843 @findex gnat_argc
8844 are declared in one of the GNAT library routines. These variables must
8845 be set from the actual @code{argc} and @code{argv} values passed to the
8846 main program. With no @option{^n^/NOMAIN^} present, @code{gnatbind}
8847 generates the C main program to automatically set these variables.
8848 If the @option{^n^/NOMAIN^} switch is used, there is no automatic way to
8849 set these variables. If they are not set, the procedures in
8850 @code{Ada.Command_Line} will not be available, and any attempt to use
8851 them will raise @code{Constraint_Error}. If command line access is
8852 required, your main program must set @code{gnat_argc} and
8853 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
8854 it.
8855
8856 @node Search Paths for gnatbind
8857 @section Search Paths for @code{gnatbind}
8858
8859 @noindent
8860 The binder takes the name of an ALI file as its argument and needs to
8861 locate source files as well as other ALI files to verify object consistency.
8862
8863 For source files, it follows exactly the same search rules as @command{gcc}
8864 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
8865 directories searched are:
8866
8867 @enumerate
8868 @item
8869 The directory containing the ALI file named in the command line, unless
8870 the switch @option{^-I-^/NOCURRENT_DIRECTORY^} is specified.
8871
8872 @item
8873 All directories specified by @option{^-I^/SEARCH^}
8874 switches on the @code{gnatbind}
8875 command line, in the order given.
8876
8877 @item
8878 @findex ADA_PRJ_OBJECTS_FILE
8879 Each of the directories listed in the text file whose name is given
8880 by the @env{ADA_PRJ_OBJECTS_FILE} ^environment variable^logical name^.
8881
8882 @noindent
8883 @env{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
8884 driver when project files are used. It should not normally be set
8885 by other means.
8886
8887 @item
8888 @findex ADA_OBJECTS_PATH
8889 Each of the directories listed in the value of the
8890 @env{ADA_OBJECTS_PATH} ^environment variable^logical name^.
8891 @ifset unw
8892 Construct this value
8893 exactly as the @env{PATH} environment variable: a list of directory
8894 names separated by colons (semicolons when working with the NT version
8895 of GNAT).
8896 @end ifset
8897 @ifset vms
8898 Normally, define this value as a logical name containing a comma separated
8899 list of directory names.
8900
8901 This variable can also be defined by means of an environment string
8902 (an argument to the HP C exec* set of functions).
8903
8904 Logical Name:
8905 @smallexample
8906 DEFINE ANOTHER_PATH FOO:[BAG]
8907 DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
8908 @end smallexample
8909
8910 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
8911 first, followed by the standard Ada
8912 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB].
8913 If this is not redefined, the user will obtain the HP Ada 83 IO packages
8914 (Text_IO, Sequential_IO, etc)
8915 instead of the standard Ada packages. Thus, in order to get the standard Ada
8916 packages by default, ADA_OBJECTS_PATH must be redefined.
8917 @end ifset
8918
8919 @item
8920 The content of the @file{ada_object_path} file which is part of the GNAT
8921 installation tree and is used to store standard libraries such as the
8922 GNAT Run Time Library (RTL) unless the switch @option{-nostdlib} is
8923 specified.
8924 @ifclear vms
8925 @ref{Installing a library}
8926 @end ifclear
8927 @end enumerate
8928
8929 @noindent
8930 In the binder the switch @option{^-I^/SEARCH^}
8931 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8932 is used to specify both source and
8933 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
8934 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
8935 instead if you want to specify
8936 source paths only, and @option{^-aO^/LIBRARY_SEARCH^}
8937 @cindex @option{^-aO^/LIBRARY_SEARCH^} (@command{gnatbind})
8938 if you want to specify library paths
8939 only. This means that for the binder
8940 @option{^-I^/SEARCH=^}@var{dir} is equivalent to
8941 @option{^-aI^/SOURCE_SEARCH=^}@var{dir}
8942 @option{^-aO^/OBJECT_SEARCH=^}@var{dir}.
8943 The binder generates the bind file (a C language source file) in the
8944 current working directory.
8945
8946 @findex Ada
8947 @findex System
8948 @findex Interfaces
8949 @findex GNAT
8950 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
8951 children make up the GNAT Run-Time Library, together with the package
8952 GNAT and its children, which contain a set of useful additional
8953 library functions provided by GNAT. The sources for these units are
8954 needed by the compiler and are kept together in one directory. The ALI
8955 files and object files generated by compiling the RTL are needed by the
8956 binder and the linker and are kept together in one directory, typically
8957 different from the directory containing the sources. In a normal
8958 installation, you need not specify these directory names when compiling
8959 or binding. Either the environment variables or the built-in defaults
8960 cause these files to be found.
8961
8962 Besides simplifying access to the RTL, a major use of search paths is
8963 in compiling sources from multiple directories. This can make
8964 development environments much more flexible.
8965
8966 @node Examples of gnatbind Usage
8967 @section Examples of @code{gnatbind} Usage
8968
8969 @noindent
8970 This section contains a number of examples of using the GNAT binding
8971 utility @code{gnatbind}.
8972
8973 @table @code
8974 @item gnatbind hello
8975 The main program @code{Hello} (source program in @file{hello.adb}) is
8976 bound using the standard switch settings. The generated main program is
8977 @file{b~hello.adb}. This is the normal, default use of the binder.
8978
8979 @ifclear vms
8980 @item gnatbind hello -o mainprog.adb
8981 @end ifclear
8982 @ifset vms
8983 @item gnatbind HELLO.ALI /OUTPUT=Mainprog.ADB
8984 @end ifset
8985 The main program @code{Hello} (source program in @file{hello.adb}) is
8986 bound using the standard switch settings. The generated main program is
8987 @file{mainprog.adb} with the associated spec in
8988 @file{mainprog.ads}. Note that you must specify the body here not the
8989 spec. Note that if this option is used, then linking must be done manually,
8990 since gnatlink will not be able to find the generated file.
8991 @end table
8992
8993 @c ------------------------------------
8994 @node Linking Using gnatlink
8995 @chapter Linking Using @command{gnatlink}
8996 @c ------------------------------------
8997 @findex gnatlink
8998
8999 @noindent
9000 This chapter discusses @command{gnatlink}, a tool that links
9001 an Ada program and builds an executable file. This utility
9002 invokes the system linker ^(via the @command{gcc} command)^^
9003 with a correct list of object files and library references.
9004 @command{gnatlink} automatically determines the list of files and
9005 references for the Ada part of a program. It uses the binder file
9006 generated by the @command{gnatbind} to determine this list.
9007
9008 Note: to invoke @code{gnatlink} with a project file, use the @code{gnat}
9009 driver (see @ref{The GNAT Driver and Project Files}).
9010
9011 @menu
9012 * Running gnatlink::
9013 * Switches for gnatlink::
9014 @end menu
9015
9016 @node Running gnatlink
9017 @section Running @command{gnatlink}
9018
9019 @noindent
9020 The form of the @command{gnatlink} command is
9021
9022 @smallexample
9023 @c $ gnatlink @ovar{switches} @var{mainprog}@r{[}.ali@r{]}
9024 @c            @ovar{non-Ada objects} @ovar{linker options}
9025 @c Expanding @ovar macro inline (explanation in macro def comments)
9026 $ gnatlink @r{[}@var{switches}@r{]} @var{mainprog}@r{[}.ali@r{]}
9027            @r{[}@var{non-Ada objects}@r{]} @r{[}@var{linker options}@r{]}
9028
9029 @end smallexample
9030
9031 @noindent
9032 The arguments of @command{gnatlink} (switches, main @file{ALI} file,
9033 non-Ada objects
9034 or linker options) may be in any order, provided that no non-Ada object may
9035 be mistaken for a main @file{ALI} file.
9036 Any file name @file{F} without the @file{.ali}
9037 extension will be taken as the main @file{ALI} file if a file exists
9038 whose name is the concatenation of @file{F} and @file{.ali}.
9039
9040 @noindent
9041 @file{@var{mainprog}.ali} references the ALI file of the main program.
9042 The @file{.ali} extension of this file can be omitted. From this
9043 reference, @command{gnatlink} locates the corresponding binder file
9044 @file{b~@var{mainprog}.adb} and, using the information in this file along
9045 with the list of non-Ada objects and linker options, constructs a
9046 linker command file to create the executable.
9047
9048 The arguments other than the @command{gnatlink} switches and the main
9049 @file{ALI} file are passed to the linker uninterpreted.
9050 They typically include the names of
9051 object files for units written in other languages than Ada and any library
9052 references required to resolve references in any of these foreign language
9053 units, or in @code{Import} pragmas in any Ada units.
9054
9055 @var{linker options} is an optional list of linker specific
9056 switches.
9057 The default linker called by gnatlink is @command{gcc} which in
9058 turn calls the appropriate system linker.
9059
9060 One useful option for the linker is @option{-s}: it reduces the size of the
9061 executable by removing all symbol table and relocation information from the
9062 executable.
9063
9064 Standard options for the linker such as @option{-lmy_lib} or
9065 @option{-Ldir} can be added as is.
9066 For options that are not recognized by
9067 @command{gcc} as linker options, use the @command{gcc} switches
9068 @option{-Xlinker} or @option{-Wl,}.
9069
9070 Refer to the GCC documentation for
9071 details.
9072
9073 Here is an example showing how to generate a linker map:
9074
9075 @smallexample
9076 $ ^gnatlink my_prog -Wl,-Map,MAPFILE^GNAT LINK my_prog.ali /MAP^
9077 @end smallexample
9078
9079 Using @var{linker options} it is possible to set the program stack and
9080 heap size.
9081 @ifset unw
9082 See @ref{Setting Stack Size from gnatlink} and
9083 @ref{Setting Heap Size from gnatlink}.
9084 @end ifset
9085
9086 @command{gnatlink} determines the list of objects required by the Ada
9087 program and prepends them to the list of objects passed to the linker.
9088 @command{gnatlink} also gathers any arguments set by the use of
9089 @code{pragma Linker_Options} and adds them to the list of arguments
9090 presented to the linker.
9091
9092 @ifset vms
9093 @command{gnatlink} accepts the following types of extra files on the command
9094 line: objects (@file{.OBJ}), libraries (@file{.OLB}), sharable images
9095 (@file{.EXE}), and options files (@file{.OPT}). These are recognized and
9096 handled according to their extension.
9097 @end ifset
9098
9099 @node Switches for gnatlink
9100 @section Switches for @command{gnatlink}
9101
9102 @noindent
9103 The following switches are available with the @command{gnatlink} utility:
9104
9105 @table @option
9106 @c !sort!
9107
9108 @item --version
9109 @cindex @option{--version} @command{gnatlink}
9110 Display Copyright and version, then exit disregarding all other options.
9111
9112 @item --help
9113 @cindex @option{--help} @command{gnatlink}
9114 If @option{--version} was not used, display usage, then exit disregarding
9115 all other options.
9116
9117 @item ^-f^/FORCE_OBJECT_FILE_LIST^
9118 @cindex Command line length
9119 @cindex @option{^-f^/FORCE_OBJECT_FILE_LIST^} (@command{gnatlink})
9120 On some targets, the command line length is limited, and @command{gnatlink}
9121 will generate a separate file for the linker if the list of object files
9122 is too long.
9123 The @option{^-f^/FORCE_OBJECT_FILE_LIST^} switch forces this file
9124 to be generated even if
9125 the limit is not exceeded. This is useful in some cases to deal with
9126 special situations where the command line length is exceeded.
9127
9128 @item ^-g^/DEBUG^
9129 @cindex Debugging information, including
9130 @cindex @option{^-g^/DEBUG^} (@command{gnatlink})
9131 The option to include debugging information causes the Ada bind file (in
9132 other words, @file{b~@var{mainprog}.adb}) to be compiled with
9133 @option{^-g^/DEBUG^}.
9134 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
9135 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
9136 Without @option{^-g^/DEBUG^}, the binder removes these files by
9137 default. The same procedure apply if a C bind file was generated using
9138 @option{^-C^/BIND_FILE=C^} @code{gnatbind} option, in this case the filenames
9139 are @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
9140
9141 @item ^-n^/NOCOMPILE^
9142 @cindex @option{^-n^/NOCOMPILE^} (@command{gnatlink})
9143 Do not compile the file generated by the binder. This may be used when
9144 a link is rerun with different options, but there is no need to recompile
9145 the binder file.
9146
9147 @item ^-v^/VERBOSE^
9148 @cindex @option{^-v^/VERBOSE^} (@command{gnatlink})
9149 Causes additional information to be output, including a full list of the
9150 included object files. This switch option is most useful when you want
9151 to see what set of object files are being used in the link step.
9152
9153 @item ^-v -v^/VERBOSE/VERBOSE^
9154 @cindex @option{^-v -v^/VERBOSE/VERBOSE^} (@command{gnatlink})
9155 Very verbose mode. Requests that the compiler operate in verbose mode when
9156 it compiles the binder file, and that the system linker run in verbose mode.
9157
9158 @item ^-o ^/EXECUTABLE=^@var{exec-name}
9159 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatlink})
9160 @var{exec-name} specifies an alternate name for the generated
9161 executable program. If this switch is omitted, the executable has the same
9162 name as the main unit. For example, @code{gnatlink try.ali} creates
9163 an executable called @file{^try^TRY.EXE^}.
9164
9165 @ifclear vms
9166 @item -b @var{target}
9167 @cindex @option{-b} (@command{gnatlink})
9168 Compile your program to run on @var{target}, which is the name of a
9169 system configuration. You must have a GNAT cross-compiler built if
9170 @var{target} is not the same as your host system.
9171
9172 @item -B@var{dir}
9173 @cindex @option{-B} (@command{gnatlink})
9174 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
9175 from @var{dir} instead of the default location. Only use this switch
9176 when multiple versions of the GNAT compiler are available.
9177 @xref{Directory Options,,, gcc, The GNU Compiler Collection},
9178 for further details. You would normally use the @option{-b} or
9179 @option{-V} switch instead.
9180
9181 @item -M
9182 When linking an executable, create a map file. The name of the map file
9183 has the same name as the executable with extension ".map".
9184
9185 @item -M=mapfile
9186 When linking an executable, create a map file. The name of the map file is
9187 "mapfile".
9188
9189 @item --GCC=@var{compiler_name}
9190 @cindex @option{--GCC=compiler_name} (@command{gnatlink})
9191 Program used for compiling the binder file. The default is
9192 @command{gcc}. You need to use quotes around @var{compiler_name} if
9193 @code{compiler_name} contains spaces or other separator characters.
9194 As an example @option{--GCC="foo -x -y"} will instruct @command{gnatlink} to
9195 use @code{foo -x -y} as your compiler. Note that switch @option{-c} is always
9196 inserted after your command name. Thus in the above example the compiler
9197 command that will be used by @command{gnatlink} will be @code{foo -c -x -y}.
9198 A limitation of this syntax is that the name and path name of the executable
9199 itself must not include any embedded spaces. If the compiler executable is
9200 different from the default one (gcc or <prefix>-gcc), then the back-end
9201 switches in the ALI file are not used to compile the binder generated source.
9202 For example, this is the case with @option{--GCC="foo -x -y"}. But the back end
9203 switches will be used for @option{--GCC="gcc -gnatv"}. If several
9204 @option{--GCC=compiler_name} are used, only the last @var{compiler_name}
9205 is taken into account. However, all the additional switches are also taken
9206 into account. Thus,
9207 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9208 @option{--GCC="bar -x -y -z -t"}.
9209
9210 @item --LINK=@var{name}
9211 @cindex @option{--LINK=} (@command{gnatlink})
9212 @var{name} is the name of the linker to be invoked. This is especially
9213 useful in mixed language programs since languages such as C++ require
9214 their own linker to be used. When this switch is omitted, the default
9215 name for the linker is @command{gcc}. When this switch is used, the
9216 specified linker is called instead of @command{gcc} with exactly the same
9217 parameters that would have been passed to @command{gcc} so if the desired
9218 linker requires different parameters it is necessary to use a wrapper
9219 script that massages the parameters before invoking the real linker. It
9220 may be useful to control the exact invocation by using the verbose
9221 switch.
9222
9223 @end ifclear
9224
9225 @ifset vms
9226 @item /DEBUG=TRACEBACK
9227 @cindex @code{/DEBUG=TRACEBACK} (@command{gnatlink})
9228 This qualifier causes sufficient information to be included in the
9229 executable file to allow a traceback, but does not include the full
9230 symbol information needed by the debugger.
9231
9232 @item /IDENTIFICATION="<string>"
9233 @code{"<string>"} specifies the string to be stored in the image file
9234 identification field in the image header.
9235 It overrides any pragma @code{Ident} specified string.
9236
9237 @item /NOINHIBIT-EXEC
9238 Generate the executable file even if there are linker warnings.
9239
9240 @item /NOSTART_FILES
9241 Don't link in the object file containing the ``main'' transfer address.
9242 Used when linking with a foreign language main program compiled with an
9243 HP compiler.
9244
9245 @item /STATIC
9246 Prefer linking with object libraries over sharable images, even without
9247 /DEBUG.
9248 @end ifset
9249
9250 @end table
9251
9252 @node The GNAT Make Program gnatmake
9253 @chapter The GNAT Make Program @command{gnatmake}
9254 @findex gnatmake
9255
9256 @menu
9257 * Running gnatmake::
9258 * Switches for gnatmake::
9259 * Mode Switches for gnatmake::
9260 * Notes on the Command Line::
9261 * How gnatmake Works::
9262 * Examples of gnatmake Usage::
9263 @end menu
9264 @noindent
9265 A typical development cycle when working on an Ada program consists of
9266 the following steps:
9267
9268 @enumerate
9269 @item
9270 Edit some sources to fix bugs.
9271
9272 @item
9273 Add enhancements.
9274
9275 @item
9276 Compile all sources affected.
9277
9278 @item
9279 Rebind and relink.
9280
9281 @item
9282 Test.
9283 @end enumerate
9284
9285 @noindent
9286 The third step can be tricky, because not only do the modified files
9287 @cindex Dependency rules
9288 have to be compiled, but any files depending on these files must also be
9289 recompiled. The dependency rules in Ada can be quite complex, especially
9290 in the presence of overloading, @code{use} clauses, generics and inlined
9291 subprograms.
9292
9293 @command{gnatmake} automatically takes care of the third and fourth steps
9294 of this process. It determines which sources need to be compiled,
9295 compiles them, and binds and links the resulting object files.
9296
9297 Unlike some other Ada make programs, the dependencies are always
9298 accurately recomputed from the new sources. The source based approach of
9299 the GNAT compilation model makes this possible. This means that if
9300 changes to the source program cause corresponding changes in
9301 dependencies, they will always be tracked exactly correctly by
9302 @command{gnatmake}.
9303
9304 @node Running gnatmake
9305 @section Running @command{gnatmake}
9306
9307 @noindent
9308 The usual form of the @command{gnatmake} command is
9309
9310 @smallexample
9311 @c $ gnatmake @ovar{switches} @var{file_name}
9312 @c       @ovar{file_names} @ovar{mode_switches}
9313 @c Expanding @ovar macro inline (explanation in macro def comments)
9314 $ gnatmake @r{[}@var{switches}@r{]} @var{file_name}
9315       @r{[}@var{file_names}@r{]} @r{[}@var{mode_switches}@r{]}
9316 @end smallexample
9317
9318 @noindent
9319 The only required argument is one @var{file_name}, which specifies
9320 a compilation unit that is a main program. Several @var{file_names} can be
9321 specified: this will result in several executables being built.
9322 If @code{switches} are present, they can be placed before the first
9323 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
9324 If @var{mode_switches} are present, they must always be placed after
9325 the last @var{file_name} and all @code{switches}.
9326
9327 If you are using standard file extensions (@file{.adb} and @file{.ads}), then the
9328 extension may be omitted from the @var{file_name} arguments. However, if
9329 you are using non-standard extensions, then it is required that the
9330 extension be given. A relative or absolute directory path can be
9331 specified in a @var{file_name}, in which case, the input source file will
9332 be searched for in the specified directory only. Otherwise, the input
9333 source file will first be searched in the directory where
9334 @command{gnatmake} was invoked and if it is not found, it will be search on
9335 the source path of the compiler as described in
9336 @ref{Search Paths and the Run-Time Library (RTL)}.
9337
9338 All @command{gnatmake} output (except when you specify
9339 @option{^-M^/DEPENDENCIES_LIST^}) is to
9340 @file{stderr}. The output produced by the
9341 @option{^-M^/DEPENDENCIES_LIST^} switch is send to
9342 @file{stdout}.
9343
9344 @node Switches for gnatmake
9345 @section Switches for @command{gnatmake}
9346
9347 @noindent
9348 You may specify any of the following switches to @command{gnatmake}:
9349
9350 @table @option
9351 @c !sort!
9352
9353 @item --version
9354 @cindex @option{--version} @command{gnatmake}
9355 Display Copyright and version, then exit disregarding all other options.
9356
9357 @item --help
9358 @cindex @option{--help} @command{gnatmake}
9359 If @option{--version} was not used, display usage, then exit disregarding
9360 all other options.
9361
9362 @ifclear vms
9363 @item --GCC=@var{compiler_name}
9364 @cindex @option{--GCC=compiler_name} (@command{gnatmake})
9365 Program used for compiling. The default is `@command{gcc}'. You need to use
9366 quotes around @var{compiler_name} if @code{compiler_name} contains
9367 spaces or other separator characters. As an example @option{--GCC="foo -x
9368 -y"} will instruct @command{gnatmake} to use @code{foo -x -y} as your
9369 compiler. A limitation of this syntax is that the name and path name of
9370 the executable itself must not include any embedded spaces. Note that
9371 switch @option{-c} is always inserted after your command name. Thus in the
9372 above example the compiler command that will be used by @command{gnatmake}
9373 will be @code{foo -c -x -y}. If several @option{--GCC=compiler_name} are
9374 used, only the last @var{compiler_name} is taken into account. However,
9375 all the additional switches are also taken into account. Thus,
9376 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9377 @option{--GCC="bar -x -y -z -t"}.
9378
9379 @item --GNATBIND=@var{binder_name}
9380 @cindex @option{--GNATBIND=binder_name} (@command{gnatmake})
9381 Program used for binding. The default is `@code{gnatbind}'. You need to
9382 use quotes around @var{binder_name} if @var{binder_name} contains spaces
9383 or other separator characters. As an example @option{--GNATBIND="bar -x
9384 -y"} will instruct @command{gnatmake} to use @code{bar -x -y} as your
9385 binder. Binder switches that are normally appended by @command{gnatmake}
9386 to `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
9387 A limitation of this syntax is that the name and path name of the executable
9388 itself must not include any embedded spaces.
9389
9390 @item --GNATLINK=@var{linker_name}
9391 @cindex @option{--GNATLINK=linker_name} (@command{gnatmake})
9392 Program used for linking. The default is `@command{gnatlink}'. You need to
9393 use quotes around @var{linker_name} if @var{linker_name} contains spaces
9394 or other separator characters. As an example @option{--GNATLINK="lan -x
9395 -y"} will instruct @command{gnatmake} to use @code{lan -x -y} as your
9396 linker. Linker switches that are normally appended by @command{gnatmake} to
9397 `@command{gnatlink}' are now appended to the end of @code{lan -x -y}.
9398 A limitation of this syntax is that the name and path name of the executable
9399 itself must not include any embedded spaces.
9400
9401 @end ifclear
9402
9403 @item ^--subdirs^/SUBDIRS^=subdir
9404 Actual object directory of each project file is the subdirectory subdir of the
9405 object directory specified or defaulted in the project file.
9406
9407 @item ^--single-compile-per-obj-dir^/SINGLE_COMPILE_PER_OBJ_DIR^
9408 Disallow simultaneous compilations in the same object directory when
9409 project files are used.
9410
9411 @item ^--unchecked-shared-lib-imports^/UNCHECKED_SHARED_LIB_IMPORTS^
9412 By default, shared library projects are not allowed to import static library
9413 projects. When this switch is used on the command line, this restriction is
9414 relaxed.
9415
9416 @item ^--source-info=<source info file>^/SRC_INFO=source-info-file^
9417 Specify a source info file. This switch is active only when project files
9418 are used. If the source info file is specified as a relative path, then it is
9419 relative to the object directory of the main project. If the source info file
9420 does not exist, then after the Project Manager has successfully parsed and
9421 processed the project files and found the sources, it creates the source info
9422 file. If the source info file already exists and can be read successfully,
9423 then the Project Manager will get all the needed information about the sources
9424 from the source info file and will not look for them. This reduces the time
9425 to process the project files, especially when looking for sources that take a
9426 long time. If the source info file exists but cannot be parsed successfully,
9427 the Project Manager will attempt to recreate it. If the Project Manager fails
9428 to create the source info file, a message is issued, but gnatmake does not
9429 fail. @command{gnatmake} "trusts" the source info file. This means that
9430 if the source files have changed (addition, deletion, moving to a different
9431 source directory), then the source info file need to be deleted and recreated.
9432
9433 @ifclear vms
9434 @item --create-map-file
9435 When linking an executable, create a map file. The name of the map file
9436 has the same name as the executable with extension ".map".
9437
9438 @item --create-map-file=mapfile
9439 When linking an executable, create a map file. The name of the map file is
9440 "mapfile".
9441
9442 @end ifclear
9443
9444 @item ^-a^/ALL_FILES^
9445 @cindex @option{^-a^/ALL_FILES^} (@command{gnatmake})
9446 Consider all files in the make process, even the GNAT internal system
9447 files (for example, the predefined Ada library files), as well as any
9448 locked files. Locked files are files whose ALI file is write-protected.
9449 By default,
9450 @command{gnatmake} does not check these files,
9451 because the assumption is that the GNAT internal files are properly up
9452 to date, and also that any write protected ALI files have been properly
9453 installed. Note that if there is an installation problem, such that one
9454 of these files is not up to date, it will be properly caught by the
9455 binder.
9456 You may have to specify this switch if you are working on GNAT
9457 itself. The switch @option{^-a^/ALL_FILES^} is also useful
9458 in conjunction with @option{^-f^/FORCE_COMPILE^}
9459 if you need to recompile an entire application,
9460 including run-time files, using special configuration pragmas,
9461 such as a @code{Normalize_Scalars} pragma.
9462
9463 By default
9464 @code{gnatmake ^-a^/ALL_FILES^} compiles all GNAT
9465 internal files with
9466 @ifclear vms
9467 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
9468 @end ifclear
9469 @ifset vms
9470 the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} switch.
9471 @end ifset
9472
9473 @item ^-b^/ACTIONS=BIND^
9474 @cindex @option{^-b^/ACTIONS=BIND^} (@command{gnatmake})
9475 Bind only. Can be combined with @option{^-c^/ACTIONS=COMPILE^} to do
9476 compilation and binding, but no link.
9477 Can be combined with @option{^-l^/ACTIONS=LINK^}
9478 to do binding and linking. When not combined with
9479 @option{^-c^/ACTIONS=COMPILE^}
9480 all the units in the closure of the main program must have been previously
9481 compiled and must be up to date. The root unit specified by @var{file_name}
9482 may be given without extension, with the source extension or, if no GNAT
9483 Project File is specified, with the ALI file extension.
9484
9485 @item ^-c^/ACTIONS=COMPILE^
9486 @cindex @option{^-c^/ACTIONS=COMPILE^} (@command{gnatmake})
9487 Compile only. Do not perform binding, except when @option{^-b^/ACTIONS=BIND^}
9488 is also specified. Do not perform linking, except if both
9489 @option{^-b^/ACTIONS=BIND^} and
9490 @option{^-l^/ACTIONS=LINK^} are also specified.
9491 If the root unit specified by @var{file_name} is not a main unit, this is the
9492 default. Otherwise @command{gnatmake} will attempt binding and linking
9493 unless all objects are up to date and the executable is more recent than
9494 the objects.
9495
9496 @item ^-C^/MAPPING^
9497 @cindex @option{^-C^/MAPPING^} (@command{gnatmake})
9498 Use a temporary mapping file. A mapping file is a way to communicate
9499 to the compiler two mappings: from unit names to file names (without
9500 any directory information) and from file names to path names (with
9501 full directory information). A mapping file can make the compiler's
9502 file searches faster, especially if there are many source directories,
9503 or the sources are read over a slow network connection. If
9504 @option{^-P^/PROJECT_FILE^} is used, a mapping file is always used, so
9505 @option{^-C^/MAPPING^} is unnecessary; in this case the mapping file
9506 is initially populated based on the project file. If
9507 @option{^-C^/MAPPING^} is used without
9508 @option{^-P^/PROJECT_FILE^},
9509 the mapping file is initially empty. Each invocation of the compiler
9510 will add any newly accessed sources to the mapping file.
9511
9512 @item ^-C=^/USE_MAPPING_FILE=^@var{file}
9513 @cindex @option{^-C=^/USE_MAPPING^} (@command{gnatmake})
9514 Use a specific mapping file. The file, specified as a path name (absolute or
9515 relative) by this switch, should already exist, otherwise the switch is
9516 ineffective. The specified mapping file will be communicated to the compiler.
9517 This switch is not compatible with a project file
9518 (^-P^/PROJECT_FILE=^@var{file}) or with multiple compiling processes
9519 (^-j^/PROCESSES=^nnn, when nnn is greater than 1).
9520
9521 @item ^-d^/DISPLAY_PROGRESS^
9522 @cindex @option{^-d^/DISPLAY_PROGRESS^} (@command{gnatmake})
9523 Display progress for each source, up to date or not, as a single line
9524
9525 @smallexample
9526 completed x out of y (zz%)
9527 @end smallexample
9528
9529 If the file needs to be compiled this is displayed after the invocation of
9530 the compiler. These lines are displayed even in quiet output mode.
9531
9532 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
9533 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@command{gnatmake})
9534 Put all object files and ALI file in directory @var{dir}.
9535 If the @option{^-D^/DIRECTORY_OBJECTS^} switch is not used, all object files
9536 and ALI files go in the current working directory.
9537
9538 This switch cannot be used when using a project file.
9539
9540 @item -eInnn
9541 @cindex @option{-eI} (@command{gnatmake})
9542 Indicates that the main source is a multi-unit source and the rank of the unit
9543 in the source file is nnn. nnn needs to be a positive number and a valid
9544 index in the source. This switch cannot be used when @command{gnatmake} is
9545 invoked for several mains.
9546
9547 @ifclear vms
9548 @item -eL
9549 @cindex @option{-eL} (@command{gnatmake})
9550 @cindex symbolic links
9551 Follow all symbolic links when processing project files.
9552 This should be used if your project uses symbolic links for files or
9553 directories, but is not needed in other cases.
9554
9555 @cindex naming scheme
9556 This also assumes that no directory matches the naming scheme for files (for
9557 instance that you do not have a directory called "sources.ads" when using the
9558 default GNAT naming scheme).
9559
9560 When you do not have to use this switch (i.e.@: by default), gnatmake is able to
9561 save a lot of system calls (several per source file and object file), which
9562 can result in a significant speed up to load and manipulate a project file,
9563 especially when using source files from a remote system.
9564
9565 @end ifclear
9566
9567 @item ^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^
9568 @cindex @option{^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^} (@command{gnatmake})
9569 Output the commands for the compiler, the binder and the linker
9570 on ^standard output^SYS$OUTPUT^,
9571 instead of ^standard error^SYS$ERROR^.
9572
9573 @item ^-f^/FORCE_COMPILE^
9574 @cindex @option{^-f^/FORCE_COMPILE^} (@command{gnatmake})
9575 Force recompilations. Recompile all sources, even though some object
9576 files may be up to date, but don't recompile predefined or GNAT internal
9577 files or locked files (files with a write-protected ALI file),
9578 unless the @option{^-a^/ALL_FILES^} switch is also specified.
9579
9580 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
9581 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@command{gnatmake})
9582 When using project files, if some errors or warnings are detected during
9583 parsing and verbose mode is not in effect (no use of switch
9584 ^-v^/VERBOSE^), then error lines start with the full path name of the project
9585 file, rather than its simple file name.
9586
9587 @item ^-g^/DEBUG^
9588 @cindex @option{^-g^/DEBUG^} (@command{gnatmake})
9589 Enable debugging. This switch is simply passed to the compiler and to the
9590 linker.
9591
9592 @item ^-i^/IN_PLACE^
9593 @cindex @option{^-i^/IN_PLACE^} (@command{gnatmake})
9594 In normal mode, @command{gnatmake} compiles all object files and ALI files
9595 into the current directory. If the @option{^-i^/IN_PLACE^} switch is used,
9596 then instead object files and ALI files that already exist are overwritten
9597 in place. This means that once a large project is organized into separate
9598 directories in the desired manner, then @command{gnatmake} will automatically
9599 maintain and update this organization. If no ALI files are found on the
9600 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
9601 the new object and ALI files are created in the
9602 directory containing the source being compiled. If another organization
9603 is desired, where objects and sources are kept in different directories,
9604 a useful technique is to create dummy ALI files in the desired directories.
9605 When detecting such a dummy file, @command{gnatmake} will be forced to
9606 recompile the corresponding source file, and it will be put the resulting
9607 object and ALI files in the directory where it found the dummy file.
9608
9609 @item ^-j^/PROCESSES=^@var{n}
9610 @cindex @option{^-j^/PROCESSES^} (@command{gnatmake})
9611 @cindex Parallel make
9612 Use @var{n} processes to carry out the (re)compilations. On a
9613 multiprocessor machine compilations will occur in parallel. In the
9614 event of compilation errors, messages from various compilations might
9615 get interspersed (but @command{gnatmake} will give you the full ordered
9616 list of failing compiles at the end). If this is problematic, rerun
9617 the make process with n set to 1 to get a clean list of messages.
9618
9619 @item ^-k^/CONTINUE_ON_ERROR^
9620 @cindex @option{^-k^/CONTINUE_ON_ERROR^} (@command{gnatmake})
9621 Keep going. Continue as much as possible after a compilation error. To
9622 ease the programmer's task in case of compilation errors, the list of
9623 sources for which the compile fails is given when @command{gnatmake}
9624 terminates.
9625
9626 If @command{gnatmake} is invoked with several @file{file_names} and with this
9627 switch, if there are compilation errors when building an executable,
9628 @command{gnatmake} will not attempt to build the following executables.
9629
9630 @item ^-l^/ACTIONS=LINK^
9631 @cindex @option{^-l^/ACTIONS=LINK^} (@command{gnatmake})
9632 Link only. Can be combined with @option{^-b^/ACTIONS=BIND^} to binding
9633 and linking. Linking will not be performed if combined with
9634 @option{^-c^/ACTIONS=COMPILE^}
9635 but not with @option{^-b^/ACTIONS=BIND^}.
9636 When not combined with @option{^-b^/ACTIONS=BIND^}
9637 all the units in the closure of the main program must have been previously
9638 compiled and must be up to date, and the main program needs to have been bound.
9639 The root unit specified by @var{file_name}
9640 may be given without extension, with the source extension or, if no GNAT
9641 Project File is specified, with the ALI file extension.
9642
9643 @item ^-m^/MINIMAL_RECOMPILATION^
9644 @cindex @option{^-m^/MINIMAL_RECOMPILATION^} (@command{gnatmake})
9645 Specify that the minimum necessary amount of recompilations
9646 be performed. In this mode @command{gnatmake} ignores time
9647 stamp differences when the only
9648 modifications to a source file consist in adding/removing comments,
9649 empty lines, spaces or tabs. This means that if you have changed the
9650 comments in a source file or have simply reformatted it, using this
9651 switch will tell @command{gnatmake} not to recompile files that depend on it
9652 (provided other sources on which these files depend have undergone no
9653 semantic modifications). Note that the debugging information may be
9654 out of date with respect to the sources if the @option{-m} switch causes
9655 a compilation to be switched, so the use of this switch represents a
9656 trade-off between compilation time and accurate debugging information.
9657
9658 @item ^-M^/DEPENDENCIES_LIST^
9659 @cindex Dependencies, producing list
9660 @cindex @option{^-M^/DEPENDENCIES_LIST^} (@command{gnatmake})
9661 Check if all objects are up to date. If they are, output the object
9662 dependences to @file{stdout} in a form that can be directly exploited in
9663 a @file{Makefile}. By default, each source file is prefixed with its
9664 (relative or absolute) directory name. This name is whatever you
9665 specified in the various @option{^-aI^/SOURCE_SEARCH^}
9666 and @option{^-I^/SEARCH^} switches. If you use
9667 @code{gnatmake ^-M^/DEPENDENCIES_LIST^}
9668 @option{^-q^/QUIET^}
9669 (see below), only the source file names,
9670 without relative paths, are output. If you just specify the
9671 @option{^-M^/DEPENDENCIES_LIST^}
9672 switch, dependencies of the GNAT internal system files are omitted. This
9673 is typically what you want. If you also specify
9674 the @option{^-a^/ALL_FILES^} switch,
9675 dependencies of the GNAT internal files are also listed. Note that
9676 dependencies of the objects in external Ada libraries (see switch
9677 @option{^-aL^/SKIP_MISSING=^}@var{dir} in the following list)
9678 are never reported.
9679
9680 @item ^-n^/DO_OBJECT_CHECK^
9681 @cindex @option{^-n^/DO_OBJECT_CHECK^} (@command{gnatmake})
9682 Don't compile, bind, or link. Checks if all objects are up to date.
9683 If they are not, the full name of the first file that needs to be
9684 recompiled is printed.
9685 Repeated use of this option, followed by compiling the indicated source
9686 file, will eventually result in recompiling all required units.
9687
9688 @item ^-o ^/EXECUTABLE=^@var{exec_name}
9689 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatmake})
9690 Output executable name. The name of the final executable program will be
9691 @var{exec_name}. If the @option{^-o^/EXECUTABLE^} switch is omitted the default
9692 name for the executable will be the name of the input file in appropriate form
9693 for an executable file on the host system.
9694
9695 This switch cannot be used when invoking @command{gnatmake} with several
9696 @file{file_names}.
9697
9698 @item ^-p or --create-missing-dirs^/CREATE_MISSING_DIRS^
9699 @cindex @option{^-p^/CREATE_MISSING_DIRS^} (@command{gnatmake})
9700 When using project files (^-P^/PROJECT_FILE=^@var{project}), create
9701 automatically missing object directories, library directories and exec
9702 directories.
9703
9704 @item ^-P^/PROJECT_FILE=^@var{project}
9705 @cindex @option{^-P^/PROJECT_FILE^} (@command{gnatmake})
9706 Use project file @var{project}. Only one such switch can be used.
9707 @xref{gnatmake and Project Files}.
9708
9709 @item ^-q^/QUIET^
9710 @cindex @option{^-q^/QUIET^} (@command{gnatmake})
9711 Quiet. When this flag is not set, the commands carried out by
9712 @command{gnatmake} are displayed.
9713
9714 @item ^-s^/SWITCH_CHECK/^
9715 @cindex @option{^-s^/SWITCH_CHECK^} (@command{gnatmake})
9716 Recompile if compiler switches have changed since last compilation.
9717 All compiler switches but -I and -o are taken into account in the
9718 following way:
9719 orders between different ``first letter'' switches are ignored, but
9720 orders between same switches are taken into account. For example,
9721 @option{-O -O2} is different than @option{-O2 -O}, but @option{-g -O}
9722 is equivalent to @option{-O -g}.
9723
9724 This switch is recommended when Integrated Preprocessing is used.
9725
9726 @item ^-u^/UNIQUE^
9727 @cindex @option{^-u^/UNIQUE^} (@command{gnatmake})
9728 Unique. Recompile at most the main files. It implies -c. Combined with
9729 -f, it is equivalent to calling the compiler directly. Note that using
9730 ^-u^/UNIQUE^ with a project file and no main has a special meaning
9731 (@pxref{Project Files and Main Subprograms}).
9732
9733 @item ^-U^/ALL_PROJECTS^
9734 @cindex @option{^-U^/ALL_PROJECTS^} (@command{gnatmake})
9735 When used without a project file or with one or several mains on the command
9736 line, is equivalent to ^-u^/UNIQUE^. When used with a project file and no main
9737 on the command line, all sources of all project files are checked and compiled
9738 if not up to date, and libraries are rebuilt, if necessary.
9739
9740 @item ^-v^/REASONS^
9741 @cindex @option{^-v^/REASONS^} (@command{gnatmake})
9742 Verbose. Display the reason for all recompilations @command{gnatmake}
9743 decides are necessary, with the highest verbosity level.
9744
9745 @item ^-vl^/LOW_VERBOSITY^
9746 @cindex @option{^-vl^/LOW_VERBOSITY^} (@command{gnatmake})
9747 Verbosity level Low. Display fewer lines than in verbosity Medium.
9748
9749 @item ^-vm^/MEDIUM_VERBOSITY^
9750 @cindex @option{^-vm^/MEDIUM_VERBOSITY^} (@command{gnatmake})
9751 Verbosity level Medium. Potentially display fewer lines than in verbosity High.
9752
9753 @item ^-vh^/HIGH_VERBOSITY^
9754 @cindex @option{^-vm^/HIGH_VERBOSITY^} (@command{gnatmake})
9755 Verbosity level High. Equivalent to ^-v^/REASONS^.
9756
9757 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
9758 Indicate the verbosity of the parsing of GNAT project files.
9759 @xref{Switches Related to Project Files}.
9760
9761 @item ^-x^/NON_PROJECT_UNIT_COMPILATION^
9762 @cindex @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} (@command{gnatmake})
9763 Indicate that sources that are not part of any Project File may be compiled.
9764 Normally, when using Project Files, only sources that are part of a Project
9765 File may be compile. When this switch is used, a source outside of all Project
9766 Files may be compiled. The ALI file and the object file will be put in the
9767 object directory of the main Project. The compilation switches used will only
9768 be those specified on the command line. Even when
9769 @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} is used, mains specified on the
9770 command line need to be sources of a project file.
9771
9772 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
9773 Indicate that external variable @var{name} has the value @var{value}.
9774 The Project Manager will use this value for occurrences of
9775 @code{external(name)} when parsing the project file.
9776 @xref{Switches Related to Project Files}.
9777
9778 @item ^-z^/NOMAIN^
9779 @cindex @option{^-z^/NOMAIN^} (@command{gnatmake})
9780 No main subprogram. Bind and link the program even if the unit name
9781 given on the command line is a package name. The resulting executable
9782 will execute the elaboration routines of the package and its closure,
9783 then the finalization routines.
9784
9785 @end table
9786
9787 @table @asis
9788 @item @command{gcc} @asis{switches}
9789 @ifclear vms
9790 Any uppercase or multi-character switch that is not a @command{gnatmake} switch
9791 is passed to @command{gcc} (e.g.@: @option{-O}, @option{-gnato,} etc.)
9792 @end ifclear
9793 @ifset vms
9794 Any qualifier that cannot be recognized as a qualifier for @code{GNAT MAKE}
9795 but is recognizable as a valid qualifier for @code{GNAT COMPILE} is
9796 automatically treated as a compiler switch, and passed on to all
9797 compilations that are carried out.
9798 @end ifset
9799 @end table
9800
9801 @noindent
9802 Source and library search path switches:
9803
9804 @table @option
9805 @c !sort!
9806 @item ^-aI^/SOURCE_SEARCH=^@var{dir}
9807 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatmake})
9808 When looking for source files also look in directory @var{dir}.
9809 The order in which source files search is undertaken is
9810 described in @ref{Search Paths and the Run-Time Library (RTL)}.
9811
9812 @item ^-aL^/SKIP_MISSING=^@var{dir}
9813 @cindex @option{^-aL^/SKIP_MISSING^} (@command{gnatmake})
9814 Consider @var{dir} as being an externally provided Ada library.
9815 Instructs @command{gnatmake} to skip compilation units whose @file{.ALI}
9816 files have been located in directory @var{dir}. This allows you to have
9817 missing bodies for the units in @var{dir} and to ignore out of date bodies
9818 for the same units. You still need to specify
9819 the location of the specs for these units by using the switches
9820 @option{^-aI^/SOURCE_SEARCH=^@var{dir}}
9821 or @option{^-I^/SEARCH=^@var{dir}}.
9822 Note: this switch is provided for compatibility with previous versions
9823 of @command{gnatmake}. The easier method of causing standard libraries
9824 to be excluded from consideration is to write-protect the corresponding
9825 ALI files.
9826
9827 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
9828 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatmake})
9829 When searching for library and object files, look in directory
9830 @var{dir}. The order in which library files are searched is described in
9831 @ref{Search Paths for gnatbind}.
9832
9833 @item ^-A^/CONDITIONAL_SOURCE_SEARCH=^@var{dir}
9834 @cindex Search paths, for @command{gnatmake}
9835 @cindex @option{^-A^/CONDITIONAL_SOURCE_SEARCH^} (@command{gnatmake})
9836 Equivalent to @option{^-aL^/SKIP_MISSING=^@var{dir}
9837 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9838
9839 @item ^-I^/SEARCH=^@var{dir}
9840 @cindex @option{^-I^/SEARCH^} (@command{gnatmake})
9841 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}
9842 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9843
9844 @item ^-I-^/NOCURRENT_DIRECTORY^
9845 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatmake})
9846 @cindex Source files, suppressing search
9847 Do not look for source files in the directory containing the source
9848 file named in the command line.
9849 Do not look for ALI or object files in the directory
9850 where @command{gnatmake} was invoked.
9851
9852 @item ^-L^/LIBRARY_SEARCH=^@var{dir}
9853 @cindex @option{^-L^/LIBRARY_SEARCH^} (@command{gnatmake})
9854 @cindex Linker libraries
9855 Add directory @var{dir} to the list of directories in which the linker
9856 will search for libraries. This is equivalent to
9857 @option{-largs ^-L^/LIBRARY_SEARCH=^}@var{dir}.
9858 @ifclear vms
9859 Furthermore, under Windows, the sources pointed to by the libraries path
9860 set in the registry are not searched for.
9861 @end ifclear
9862
9863 @item -nostdinc
9864 @cindex @option{-nostdinc} (@command{gnatmake})
9865 Do not look for source files in the system default directory.
9866
9867 @item -nostdlib
9868 @cindex @option{-nostdlib} (@command{gnatmake})
9869 Do not look for library files in the system default directory.
9870
9871 @item --RTS=@var{rts-path}
9872 @cindex @option{--RTS} (@command{gnatmake})
9873 Specifies the default location of the runtime library. GNAT looks for the
9874 runtime
9875 in the following directories, and stops as soon as a valid runtime is found
9876 (@file{adainclude} or @file{ada_source_path}, and @file{adalib} or
9877 @file{ada_object_path} present):
9878
9879 @itemize @bullet
9880 @item <current directory>/$rts_path
9881
9882 @item <default-search-dir>/$rts_path
9883
9884 @item <default-search-dir>/rts-$rts_path
9885 @end itemize
9886
9887 @noindent
9888 The selected path is handled like a normal RTS path.
9889
9890 @end table
9891
9892 @node Mode Switches for gnatmake
9893 @section Mode Switches for @command{gnatmake}
9894
9895 @noindent
9896 The mode switches (referred to as @code{mode_switches}) allow the
9897 inclusion of switches that are to be passed to the compiler itself, the
9898 binder or the linker. The effect of a mode switch is to cause all
9899 subsequent switches up to the end of the switch list, or up to the next
9900 mode switch, to be interpreted as switches to be passed on to the
9901 designated component of GNAT.
9902
9903 @table @option
9904 @c !sort!
9905 @item -cargs @var{switches}
9906 @cindex @option{-cargs} (@command{gnatmake})
9907 Compiler switches. Here @var{switches} is a list of switches
9908 that are valid switches for @command{gcc}. They will be passed on to
9909 all compile steps performed by @command{gnatmake}.
9910
9911 @item -bargs @var{switches}
9912 @cindex @option{-bargs} (@command{gnatmake})
9913 Binder switches. Here @var{switches} is a list of switches
9914 that are valid switches for @code{gnatbind}. They will be passed on to
9915 all bind steps performed by @command{gnatmake}.
9916
9917 @item -largs @var{switches}
9918 @cindex @option{-largs} (@command{gnatmake})
9919 Linker switches. Here @var{switches} is a list of switches
9920 that are valid switches for @command{gnatlink}. They will be passed on to
9921 all link steps performed by @command{gnatmake}.
9922
9923 @item -margs @var{switches}
9924 @cindex @option{-margs} (@command{gnatmake})
9925 Make switches. The switches are directly interpreted by @command{gnatmake},
9926 regardless of any previous occurrence of @option{-cargs}, @option{-bargs}
9927 or @option{-largs}.
9928 @end table
9929
9930 @node Notes on the Command Line
9931 @section Notes on the Command Line
9932
9933 @noindent
9934 This section contains some additional useful notes on the operation
9935 of the @command{gnatmake} command.
9936
9937 @itemize @bullet
9938 @item
9939 @cindex Recompilation, by @command{gnatmake}
9940 If @command{gnatmake} finds no ALI files, it recompiles the main program
9941 and all other units required by the main program.
9942 This means that @command{gnatmake}
9943 can be used for the initial compile, as well as during subsequent steps of
9944 the development cycle.
9945
9946 @item
9947 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
9948 is a subunit or body of a generic unit, @command{gnatmake} recompiles
9949 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
9950 warning.
9951
9952 @item
9953 In @command{gnatmake} the switch @option{^-I^/SEARCH^}
9954 is used to specify both source and
9955 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
9956 instead if you just want to specify
9957 source paths only and @option{^-aO^/OBJECT_SEARCH^}
9958 if you want to specify library paths
9959 only.
9960
9961 @item
9962 @command{gnatmake} will ignore any files whose ALI file is write-protected.
9963 This may conveniently be used to exclude standard libraries from
9964 consideration and in particular it means that the use of the
9965 @option{^-f^/FORCE_COMPILE^} switch will not recompile these files
9966 unless @option{^-a^/ALL_FILES^} is also specified.
9967
9968 @item
9969 @command{gnatmake} has been designed to make the use of Ada libraries
9970 particularly convenient. Assume you have an Ada library organized
9971 as follows: @i{^obj-dir^[OBJ_DIR]^} contains the objects and ALI files for
9972 of your Ada compilation units,
9973 whereas @i{^include-dir^[INCLUDE_DIR]^} contains the
9974 specs of these units, but no bodies. Then to compile a unit
9975 stored in @code{main.adb}, which uses this Ada library you would just type
9976
9977 @smallexample
9978 @ifclear vms
9979 $ gnatmake -aI@var{include-dir}  -aL@var{obj-dir}  main
9980 @end ifclear
9981 @ifset vms
9982 $ gnatmake /SOURCE_SEARCH=@i{[INCLUDE_DIR]}
9983            /SKIP_MISSING=@i{[OBJ_DIR]} main
9984 @end ifset
9985 @end smallexample
9986
9987 @item
9988 Using @command{gnatmake} along with the
9989 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}
9990 switch provides a mechanism for avoiding unnecessary recompilations. Using
9991 this switch,
9992 you can update the comments/format of your
9993 source files without having to recompile everything. Note, however, that
9994 adding or deleting lines in a source files may render its debugging
9995 info obsolete. If the file in question is a spec, the impact is rather
9996 limited, as that debugging info will only be useful during the
9997 elaboration phase of your program. For bodies the impact can be more
9998 significant. In all events, your debugger will warn you if a source file
9999 is more recent than the corresponding object, and alert you to the fact
10000 that the debugging information may be out of date.
10001 @end itemize
10002
10003 @node How gnatmake Works
10004 @section How @command{gnatmake} Works
10005
10006 @noindent
10007 Generally @command{gnatmake} automatically performs all necessary
10008 recompilations and you don't need to worry about how it works. However,
10009 it may be useful to have some basic understanding of the @command{gnatmake}
10010 approach and in particular to understand how it uses the results of
10011 previous compilations without incorrectly depending on them.
10012
10013 First a definition: an object file is considered @dfn{up to date} if the
10014 corresponding ALI file exists and if all the source files listed in the
10015 dependency section of this ALI file have time stamps matching those in
10016 the ALI file. This means that neither the source file itself nor any
10017 files that it depends on have been modified, and hence there is no need
10018 to recompile this file.
10019
10020 @command{gnatmake} works by first checking if the specified main unit is up
10021 to date. If so, no compilations are required for the main unit. If not,
10022 @command{gnatmake} compiles the main program to build a new ALI file that
10023 reflects the latest sources. Then the ALI file of the main unit is
10024 examined to find all the source files on which the main program depends,
10025 and @command{gnatmake} recursively applies the above procedure on all these
10026 files.
10027
10028 This process ensures that @command{gnatmake} only trusts the dependencies
10029 in an existing ALI file if they are known to be correct. Otherwise it
10030 always recompiles to determine a new, guaranteed accurate set of
10031 dependencies. As a result the program is compiled ``upside down'' from what may
10032 be more familiar as the required order of compilation in some other Ada
10033 systems. In particular, clients are compiled before the units on which
10034 they depend. The ability of GNAT to compile in any order is critical in
10035 allowing an order of compilation to be chosen that guarantees that
10036 @command{gnatmake} will recompute a correct set of new dependencies if
10037 necessary.
10038
10039 When invoking @command{gnatmake} with several @var{file_names}, if a unit is
10040 imported by several of the executables, it will be recompiled at most once.
10041
10042 Note: when using non-standard naming conventions
10043 (@pxref{Using Other File Names}), changing through a configuration pragmas
10044 file the version of a source and invoking @command{gnatmake} to recompile may
10045 have no effect, if the previous version of the source is still accessible
10046 by @command{gnatmake}. It may be necessary to use the switch
10047 ^-f^/FORCE_COMPILE^.
10048
10049 @node Examples of gnatmake Usage
10050 @section Examples of @command{gnatmake} Usage
10051
10052 @table @code
10053 @item gnatmake hello.adb
10054 Compile all files necessary to bind and link the main program
10055 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
10056 resulting object files to generate an executable file @file{^hello^HELLO.EXE^}.
10057
10058 @item gnatmake main1 main2 main3
10059 Compile all files necessary to bind and link the main programs
10060 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
10061 (containing unit @code{Main2}) and @file{main3.adb}
10062 (containing unit @code{Main3}) and bind and link the resulting object files
10063 to generate three executable files @file{^main1^MAIN1.EXE^},
10064 @file{^main2^MAIN2.EXE^}
10065 and @file{^main3^MAIN3.EXE^}.
10066
10067 @ifclear vms
10068 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
10069 @end ifclear
10070
10071 @ifset vms
10072 @item gnatmake Main_Unit /QUIET
10073 /COMPILER_QUALIFIERS /OPTIMIZE=ALL
10074 /BINDER_QUALIFIERS /ORDER_OF_ELABORATION
10075 @end ifset
10076 Compile all files necessary to bind and link the main program unit
10077 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
10078 be done with optimization level 2 and the order of elaboration will be
10079 listed by the binder. @command{gnatmake} will operate in quiet mode, not
10080 displaying commands it is executing.
10081 @end table
10082
10083 @c *************************
10084 @node Improving Performance
10085 @chapter Improving Performance
10086 @cindex Improving performance
10087
10088 @noindent
10089 This chapter presents several topics related to program performance.
10090 It first describes some of the tradeoffs that need to be considered
10091 and some of the techniques for making your program run faster.
10092 It then documents the @command{gnatelim} tool and unused subprogram/data
10093 elimination feature, which can reduce the size of program executables.
10094
10095 @ifnottex
10096 @menu
10097 * Performance Considerations::
10098 * Text_IO Suggestions::
10099 * Reducing Size of Ada Executables with gnatelim::
10100 * Reducing Size of Executables with unused subprogram/data elimination::
10101 @end menu
10102 @end ifnottex
10103
10104 @c *****************************
10105 @node Performance Considerations
10106 @section Performance Considerations
10107
10108 @noindent
10109 The GNAT system provides a number of options that allow a trade-off
10110 between
10111
10112 @itemize @bullet
10113 @item
10114 performance of the generated code
10115
10116 @item
10117 speed of compilation
10118
10119 @item
10120 minimization of dependences and recompilation
10121
10122 @item
10123 the degree of run-time checking.
10124 @end itemize
10125
10126 @noindent
10127 The defaults (if no options are selected) aim at improving the speed
10128 of compilation and minimizing dependences, at the expense of performance
10129 of the generated code:
10130
10131 @itemize @bullet
10132 @item
10133 no optimization
10134
10135 @item
10136 no inlining of subprogram calls
10137
10138 @item
10139 all run-time checks enabled except overflow and elaboration checks
10140 @end itemize
10141
10142 @noindent
10143 These options are suitable for most program development purposes. This
10144 chapter describes how you can modify these choices, and also provides
10145 some guidelines on debugging optimized code.
10146
10147 @menu
10148 * Controlling Run-Time Checks::
10149 * Use of Restrictions::
10150 * Optimization Levels::
10151 * Debugging Optimized Code::
10152 * Inlining of Subprograms::
10153 * Other Optimization Switches::
10154 * Optimization and Strict Aliasing::
10155
10156 @ifset vms
10157 * Coverage Analysis::
10158 @end ifset
10159 @end menu
10160
10161 @node Controlling Run-Time Checks
10162 @subsection Controlling Run-Time Checks
10163
10164 @noindent
10165 By default, GNAT generates all run-time checks, except integer overflow
10166 checks, stack overflow checks, and checks for access before elaboration on
10167 subprogram calls. The latter are not required in default mode, because all
10168 necessary checking is done at compile time.
10169 @cindex @option{-gnatp} (@command{gcc})
10170 @cindex @option{-gnato} (@command{gcc})
10171 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
10172 be modified. @xref{Run-Time Checks}.
10173
10174 Our experience is that the default is suitable for most development
10175 purposes.
10176
10177 We treat integer overflow specially because these
10178 are quite expensive and in our experience are not as important as other
10179 run-time checks in the development process. Note that division by zero
10180 is not considered an overflow check, and divide by zero checks are
10181 generated where required by default.
10182
10183 Elaboration checks are off by default, and also not needed by default, since
10184 GNAT uses a static elaboration analysis approach that avoids the need for
10185 run-time checking. This manual contains a full chapter discussing the issue
10186 of elaboration checks, and if the default is not satisfactory for your use,
10187 you should read this chapter.
10188
10189 For validity checks, the minimal checks required by the Ada Reference
10190 Manual (for case statements and assignments to array elements) are on
10191 by default. These can be suppressed by use of the @option{-gnatVn} switch.
10192 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
10193 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
10194 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
10195 are also suppressed entirely if @option{-gnatp} is used.
10196
10197 @cindex Overflow checks
10198 @cindex Checks, overflow
10199 @findex Suppress
10200 @findex Unsuppress
10201 @cindex pragma Suppress
10202 @cindex pragma Unsuppress
10203 Note that the setting of the switches controls the default setting of
10204 the checks. They may be modified using either @code{pragma Suppress} (to
10205 remove checks) or @code{pragma Unsuppress} (to add back suppressed
10206 checks) in the program source.
10207
10208 @node Use of Restrictions
10209 @subsection Use of Restrictions
10210
10211 @noindent
10212 The use of pragma Restrictions allows you to control which features are
10213 permitted in your program. Apart from the obvious point that if you avoid
10214 relatively expensive features like finalization (enforceable by the use
10215 of pragma Restrictions (No_Finalization), the use of this pragma does not
10216 affect the generated code in most cases.
10217
10218 One notable exception to this rule is that the possibility of task abort
10219 results in some distributed overhead, particularly if finalization or
10220 exception handlers are used. The reason is that certain sections of code
10221 have to be marked as non-abortable.
10222
10223 If you use neither the @code{abort} statement, nor asynchronous transfer
10224 of control (@code{select @dots{} then abort}), then this distributed overhead
10225 is removed, which may have a general positive effect in improving
10226 overall performance.  Especially code involving frequent use of tasking
10227 constructs and controlled types will show much improved performance.
10228 The relevant restrictions pragmas are
10229
10230 @smallexample @c ada
10231    pragma Restrictions (No_Abort_Statements);
10232    pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
10233 @end smallexample
10234
10235 @noindent
10236 It is recommended that these restriction pragmas be used if possible. Note
10237 that this also means that you can write code without worrying about the
10238 possibility of an immediate abort at any point.
10239
10240 @node Optimization Levels
10241 @subsection Optimization Levels
10242 @cindex @option{^-O^/OPTIMIZE^} (@command{gcc})
10243
10244 @noindent
10245 Without any optimization ^option,^qualifier,^
10246 the compiler's goal is to reduce the cost of
10247 compilation and to make debugging produce the expected results.
10248 Statements are independent: if you stop the program with a breakpoint between
10249 statements, you can then assign a new value to any variable or change
10250 the program counter to any other statement in the subprogram and get exactly
10251 the results you would expect from the source code.
10252
10253 Turning on optimization makes the compiler attempt to improve the
10254 performance and/or code size at the expense of compilation time and
10255 possibly the ability to debug the program.
10256
10257 If you use multiple
10258 ^-O options, with or without level numbers,^/OPTIMIZE qualifiers,^
10259 the last such option is the one that is effective.
10260
10261 @noindent
10262 The default is optimization off. This results in the fastest compile
10263 times, but GNAT makes absolutely no attempt to optimize, and the
10264 generated programs are considerably larger and slower than when
10265 optimization is enabled. You can use the
10266 @ifclear vms
10267 @option{-O} switch (the permitted forms are @option{-O0}, @option{-O1}
10268 @option{-O2}, @option{-O3}, and @option{-Os})
10269 @end ifclear
10270 @ifset vms
10271 @code{OPTIMIZE} qualifier
10272 @end ifset
10273 to @command{gcc} to control the optimization level:
10274
10275 @table @option
10276 @item ^-O0^/OPTIMIZE=NONE^
10277 No optimization (the default);
10278 generates unoptimized code but has
10279 the fastest compilation time.
10280
10281 Note that many other compilers do fairly extensive optimization
10282 even if ``no optimization'' is specified. With gcc, it is
10283 very unusual to use ^-O0^/OPTIMIZE=NONE^ for production if
10284 execution time is of any concern, since ^-O0^/OPTIMIZE=NONE^
10285 really does mean no optimization at all. This difference between
10286 gcc and other compilers should be kept in mind when doing
10287 performance comparisons.
10288
10289 @item ^-O1^/OPTIMIZE=SOME^
10290 Moderate optimization;
10291 optimizes reasonably well but does not
10292 degrade compilation time significantly.
10293
10294 @item ^-O2^/OPTIMIZE=ALL^
10295 @ifset vms
10296 @itemx /OPTIMIZE=DEVELOPMENT
10297 @end ifset
10298 Full optimization;
10299 generates highly optimized code and has
10300 the slowest compilation time.
10301
10302 @item ^-O3^/OPTIMIZE=INLINING^
10303 Full optimization as in @option{-O2};
10304 also uses more aggressive automatic inlining of subprograms within a unit
10305 (@pxref{Inlining of Subprograms}) and attempts to vectorize loops.
10306
10307 @item ^-Os^/OPTIMIZE=SPACE^
10308 Optimize space usage (code and data) of resulting program.
10309 @end table
10310
10311 @noindent
10312 Higher optimization levels perform more global transformations on the
10313 program and apply more expensive analysis algorithms in order to generate
10314 faster and more compact code. The price in compilation time, and the
10315 resulting improvement in execution time,
10316 both depend on the particular application and the hardware environment.
10317 You should experiment to find the best level for your application.
10318
10319 Since the precise set of optimizations done at each level will vary from
10320 release to release (and sometime from target to target), it is best to think
10321 of the optimization settings in general terms.
10322 @xref{Optimize Options,, Options That Control Optimization, gcc, Using
10323 the GNU Compiler Collection (GCC)}, for details about
10324 ^the @option{-O} settings and a number of @option{-f} options that^how to^
10325 individually enable or disable specific optimizations.
10326
10327 Unlike some other compilation systems, ^@command{gcc}^GNAT^ has
10328 been tested extensively at all optimization levels. There are some bugs
10329 which appear only with optimization turned on, but there have also been
10330 bugs which show up only in @emph{unoptimized} code. Selecting a lower
10331 level of optimization does not improve the reliability of the code
10332 generator, which in practice is highly reliable at all optimization
10333 levels.
10334
10335 Note regarding the use of @option{-O3}: The use of this optimization level
10336 is generally discouraged with GNAT, since it often results in larger
10337 executables which may run more slowly. See further discussion of this point
10338 in @ref{Inlining of Subprograms}.
10339
10340 @node Debugging Optimized Code
10341 @subsection Debugging Optimized Code
10342 @cindex Debugging optimized code
10343 @cindex Optimization and debugging
10344
10345 @noindent
10346 Although it is possible to do a reasonable amount of debugging at
10347 @ifclear vms
10348 nonzero optimization levels,
10349 the higher the level the more likely that
10350 @end ifclear
10351 @ifset vms
10352 @option{/OPTIMIZE} settings other than @code{NONE},
10353 such settings will make it more likely that
10354 @end ifset
10355 source-level constructs will have been eliminated by optimization.
10356 For example, if a loop is strength-reduced, the loop
10357 control variable may be completely eliminated and thus cannot be
10358 displayed in the debugger.
10359 This can only happen at @option{-O2} or @option{-O3}.
10360 Explicit temporary variables that you code might be eliminated at
10361 ^level^setting^ @option{-O1} or higher.
10362
10363 The use of the @option{^-g^/DEBUG^} switch,
10364 @cindex @option{^-g^/DEBUG^} (@command{gcc})
10365 which is needed for source-level debugging,
10366 affects the size of the program executable on disk,
10367 and indeed the debugging information can be quite large.
10368 However, it has no effect on the generated code (and thus does not
10369 degrade performance)
10370
10371 Since the compiler generates debugging tables for a compilation unit before
10372 it performs optimizations, the optimizing transformations may invalidate some
10373 of the debugging data.  You therefore need to anticipate certain
10374 anomalous situations that may arise while debugging optimized code.
10375 These are the most common cases:
10376
10377 @enumerate
10378 @item
10379 @i{The ``hopping Program Counter'':}  Repeated @code{step} or @code{next}
10380 commands show
10381 the PC bouncing back and forth in the code.  This may result from any of
10382 the following optimizations:
10383
10384 @itemize @bullet
10385 @item
10386 @i{Common subexpression elimination:} using a single instance of code for a
10387 quantity that the source computes several times.  As a result you
10388 may not be able to stop on what looks like a statement.
10389
10390 @item
10391 @i{Invariant code motion:} moving an expression that does not change within a
10392 loop, to the beginning of the loop.
10393
10394 @item
10395 @i{Instruction scheduling:} moving instructions so as to
10396 overlap loads and stores (typically) with other code, or in
10397 general to move computations of values closer to their uses. Often
10398 this causes you to pass an assignment statement without the assignment
10399 happening and then later bounce back to the statement when the
10400 value is actually needed.  Placing a breakpoint on a line of code
10401 and then stepping over it may, therefore, not always cause all the
10402 expected side-effects.
10403 @end itemize
10404
10405 @item
10406 @i{The ``big leap'':} More commonly known as @emph{cross-jumping}, in which
10407 two identical pieces of code are merged and the program counter suddenly
10408 jumps to a statement that is not supposed to be executed, simply because
10409 it (and the code following) translates to the same thing as the code
10410 that @emph{was} supposed to be executed.  This effect is typically seen in
10411 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
10412 a @code{break} in a C @code{^switch^switch^} statement.
10413
10414 @item
10415 @i{The ``roving variable'':} The symptom is an unexpected value in a variable.
10416 There are various reasons for this effect:
10417
10418 @itemize @bullet
10419 @item
10420 In a subprogram prologue, a parameter may not yet have been moved to its
10421 ``home''.
10422
10423 @item
10424 A variable may be dead, and its register re-used.  This is
10425 probably the most common cause.
10426
10427 @item
10428 As mentioned above, the assignment of a value to a variable may
10429 have been moved.
10430
10431 @item
10432 A variable may be eliminated entirely by value propagation or
10433 other means.  In this case, GCC may incorrectly generate debugging
10434 information for the variable
10435 @end itemize
10436
10437 @noindent
10438 In general, when an unexpected value appears for a local variable or parameter
10439 you should first ascertain if that value was actually computed by
10440 your program, as opposed to being incorrectly reported by the debugger.
10441 Record fields or
10442 array elements in an object designated by an access value
10443 are generally less of a problem, once you have ascertained that the access
10444 value is sensible.
10445 Typically, this means checking variables in the preceding code and in the
10446 calling subprogram to verify that the value observed is explainable from other
10447 values (one must apply the procedure recursively to those
10448 other values); or re-running the code and stopping a little earlier
10449 (perhaps before the call) and stepping to better see how the variable obtained
10450 the value in question; or continuing to step @emph{from} the point of the
10451 strange value to see if code motion had simply moved the variable's
10452 assignments later.
10453 @end enumerate
10454
10455 @noindent
10456 In light of such anomalies, a recommended technique is to use @option{-O0}
10457 early in the software development cycle, when extensive debugging capabilities
10458 are most needed, and then move to @option{-O1} and later @option{-O2} as
10459 the debugger becomes less critical.
10460 Whether to use the @option{^-g^/DEBUG^} switch in the release version is
10461 a release management issue.
10462 @ifclear vms
10463 Note that if you use @option{-g} you can then use the @command{strip} program
10464 on the resulting executable,
10465 which removes both debugging information and global symbols.
10466 @end ifclear
10467
10468 @node Inlining of Subprograms
10469 @subsection Inlining of Subprograms
10470
10471 @noindent
10472 A call to a subprogram in the current unit is inlined if all the
10473 following conditions are met:
10474
10475 @itemize @bullet
10476 @item
10477 The optimization level is at least @option{-O1}.
10478
10479 @item
10480 The called subprogram is suitable for inlining: It must be small enough
10481 and not contain something that @command{gcc} cannot support in inlined
10482 subprograms.
10483
10484 @item
10485 @cindex pragma Inline
10486 @findex Inline
10487 Any one of the following applies: @code{pragma Inline} is applied to the
10488 subprogram and the @option{^-gnatn^/INLINE^} switch is specified; the
10489 subprogram is local to the unit and called once from within it; the
10490 subprogram is small and optimization level @option{-O2} is specified;
10491 optimization level @option{-O3}) is specified.
10492 @end itemize
10493
10494 @noindent
10495 Calls to subprograms in @code{with}'ed units are normally not inlined.
10496 To achieve actual inlining (that is, replacement of the call by the code
10497 in the body of the subprogram), the following conditions must all be true.
10498
10499 @itemize @bullet
10500 @item
10501 The optimization level is at least @option{-O1}.
10502
10503 @item
10504 The called subprogram is suitable for inlining: It must be small enough
10505 and not contain something that @command{gcc} cannot support in inlined
10506 subprograms.
10507
10508 @item
10509 The call appears in a body (not in a package spec).
10510
10511 @item
10512 There is a @code{pragma Inline} for the subprogram.
10513
10514 @item
10515 The @option{^-gnatn^/INLINE^} switch is used on the command line.
10516 @end itemize
10517
10518 Even if all these conditions are met, it may not be possible for
10519 the compiler to inline the call, due to the length of the body,
10520 or features in the body that make it impossible for the compiler
10521 to do the inlining.
10522
10523 Note that specifying the @option{-gnatn} switch causes additional
10524 compilation dependencies. Consider the following:
10525
10526 @smallexample @c ada
10527 @cartouche
10528 package R is
10529    procedure Q;
10530    pragma Inline (Q);
10531 end R;
10532 package body R is
10533    @dots{}
10534 end R;
10535
10536 with R;
10537 procedure Main is
10538 begin
10539    @dots{}
10540    R.Q;
10541 end Main;
10542 @end cartouche
10543 @end smallexample
10544
10545 @noindent
10546 With the default behavior (no @option{-gnatn} switch specified), the
10547 compilation of the @code{Main} procedure depends only on its own source,
10548 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
10549 means that editing the body of @code{R} does not require recompiling
10550 @code{Main}.
10551
10552 On the other hand, the call @code{R.Q} is not inlined under these
10553 circumstances. If the @option{-gnatn} switch is present when @code{Main}
10554 is compiled, the call will be inlined if the body of @code{Q} is small
10555 enough, but now @code{Main} depends on the body of @code{R} in
10556 @file{r.adb} as well as on the spec. This means that if this body is edited,
10557 the main program must be recompiled. Note that this extra dependency
10558 occurs whether or not the call is in fact inlined by @command{gcc}.
10559
10560 The use of front end inlining with @option{-gnatN} generates similar
10561 additional dependencies.
10562
10563 @cindex @option{^-fno-inline^/INLINE=SUPPRESS^} (@command{gcc})
10564 Note: The @option{^-fno-inline^/INLINE=SUPPRESS^} switch
10565 can be used to prevent
10566 all inlining. This switch overrides all other conditions and ensures
10567 that no inlining occurs. The extra dependences resulting from
10568 @option{-gnatn} will still be active, even if
10569 this switch is used to suppress the resulting inlining actions.
10570
10571 @cindex @option{-fno-inline-functions} (@command{gcc})
10572 Note: The @option{-fno-inline-functions} switch can be used to prevent
10573 automatic inlining of subprograms if @option{-O3} is used.
10574
10575 @cindex @option{-fno-inline-small-functions} (@command{gcc})
10576 Note: The @option{-fno-inline-small-functions} switch can be used to prevent
10577 automatic inlining of small subprograms if @option{-O2} is used.
10578
10579 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
10580 Note: The @option{-fno-inline-functions-called-once} switch
10581 can be used to prevent inlining of subprograms local to the unit
10582 and called once from within it if @option{-O1} is used.
10583
10584 Note regarding the use of @option{-O3}: There is no difference in inlining
10585 behavior between @option{-O2} and @option{-O3} for subprograms with an explicit
10586 pragma @code{Inline} assuming the use of @option{-gnatn}
10587 or @option{-gnatN} (the switches that activate inlining). If you have used
10588 pragma @code{Inline} in appropriate cases, then it is usually much better
10589 to use @option{-O2} and @option{-gnatn} and avoid the use of @option{-O3} which
10590 in this case only has the effect of inlining subprograms you did not
10591 think should be inlined. We often find that the use of @option{-O3} slows
10592 down code by performing excessive inlining, leading to increased instruction
10593 cache pressure from the increased code size. So the bottom line here is
10594 that you should not automatically assume that @option{-O3} is better than
10595 @option{-O2}, and indeed you should use @option{-O3} only if tests show that
10596 it actually improves performance.
10597
10598 @node Other Optimization Switches
10599 @subsection Other Optimization Switches
10600 @cindex Optimization Switches
10601
10602 Since @code{GNAT} uses the @command{gcc} back end, all the specialized
10603 @command{gcc} optimization switches are potentially usable. These switches
10604 have not been extensively tested with GNAT but can generally be expected
10605 to work. Examples of switches in this category are
10606 @option{-funroll-loops} and
10607 the various target-specific @option{-m} options (in particular, it has been
10608 observed that @option{-march=pentium4} can significantly improve performance
10609 on appropriate machines). For full details of these switches, see
10610 @ref{Submodel Options,, Hardware Models and Configurations, gcc, Using
10611 the GNU Compiler Collection (GCC)}.
10612
10613 @node Optimization and Strict Aliasing
10614 @subsection Optimization and Strict Aliasing
10615 @cindex Aliasing
10616 @cindex Strict Aliasing
10617 @cindex No_Strict_Aliasing
10618
10619 @noindent
10620 The strong typing capabilities of Ada allow an optimizer to generate
10621 efficient code in situations where other languages would be forced to
10622 make worst case assumptions preventing such optimizations. Consider
10623 the following example:
10624
10625 @smallexample @c ada
10626 @cartouche
10627 procedure R is
10628    type Int1 is new Integer;
10629    type Int2 is new Integer;
10630    type Int1A is access Int1;
10631    type Int2A is access Int2;
10632    Int1V : Int1A;
10633    Int2V : Int2A;
10634    @dots{}
10635
10636 begin
10637    @dots{}
10638    for J in Data'Range loop
10639       if Data (J) = Int1V.all then
10640          Int2V.all := Int2V.all + 1;
10641       end if;
10642    end loop;
10643    @dots{}
10644 end R;
10645 @end cartouche
10646 @end smallexample
10647
10648 @noindent
10649 In this example, since the variable @code{Int1V} can only access objects
10650 of type @code{Int1}, and @code{Int2V} can only access objects of type
10651 @code{Int2}, there is no possibility that the assignment to
10652 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
10653 the compiler optimizer can "know" that the value @code{Int1V.all} is constant
10654 for all iterations of the loop and avoid the extra memory reference
10655 required to dereference it each time through the loop.
10656
10657 This kind of optimization, called strict aliasing analysis, is
10658 triggered by specifying an optimization level of @option{-O2} or
10659 higher or @option{-Os} and allows @code{GNAT} to generate more efficient code
10660 when access values are involved.
10661
10662 However, although this optimization is always correct in terms of
10663 the formal semantics of the Ada Reference Manual, difficulties can
10664 arise if features like @code{Unchecked_Conversion} are used to break
10665 the typing system. Consider the following complete program example:
10666
10667 @smallexample @c ada
10668 @cartouche
10669 package p1 is
10670    type int1 is new integer;
10671    type int2 is new integer;
10672    type a1 is access int1;
10673    type a2 is access int2;
10674 end p1;
10675
10676 with p1; use p1;
10677 package p2 is
10678    function to_a2 (Input : a1) return a2;
10679 end p2;
10680
10681 with Unchecked_Conversion;
10682 package body p2 is
10683    function to_a2 (Input : a1) return a2 is
10684       function to_a2u is
10685         new Unchecked_Conversion (a1, a2);
10686    begin
10687       return to_a2u (Input);
10688    end to_a2;
10689 end p2;
10690
10691 with p2; use p2;
10692 with p1; use p1;
10693 with Text_IO; use Text_IO;
10694 procedure m is
10695    v1 : a1 := new int1;
10696    v2 : a2 := to_a2 (v1);
10697 begin
10698    v1.all := 1;
10699    v2.all := 0;
10700    put_line (int1'image (v1.all));
10701 end;
10702 @end cartouche
10703 @end smallexample
10704
10705 @noindent
10706 This program prints out 0 in @option{-O0} or @option{-O1}
10707 mode, but it prints out 1 in @option{-O2} mode. That's
10708 because in strict aliasing mode, the compiler can and
10709 does assume that the assignment to @code{v2.all} could not
10710 affect the value of @code{v1.all}, since different types
10711 are involved.
10712
10713 This behavior is not a case of non-conformance with the standard, since
10714 the Ada RM specifies that an unchecked conversion where the resulting
10715 bit pattern is not a correct value of the target type can result in an
10716 abnormal value and attempting to reference an abnormal value makes the
10717 execution of a program erroneous.  That's the case here since the result
10718 does not point to an object of type @code{int2}.  This means that the
10719 effect is entirely unpredictable.
10720
10721 However, although that explanation may satisfy a language
10722 lawyer, in practice an applications programmer expects an
10723 unchecked conversion involving pointers to create true
10724 aliases and the behavior of printing 1 seems plain wrong.
10725 In this case, the strict aliasing optimization is unwelcome.
10726
10727 Indeed the compiler recognizes this possibility, and the
10728 unchecked conversion generates a warning:
10729
10730 @smallexample
10731 p2.adb:5:07: warning: possible aliasing problem with type "a2"
10732 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
10733 p2.adb:5:07: warning:  or use "pragma No_Strict_Aliasing (a2);"
10734 @end smallexample
10735
10736 @noindent
10737 Unfortunately the problem is recognized when compiling the body of
10738 package @code{p2}, but the actual "bad" code is generated while
10739 compiling the body of @code{m} and this latter compilation does not see
10740 the suspicious @code{Unchecked_Conversion}.
10741
10742 As implied by the warning message, there are approaches you can use to
10743 avoid the unwanted strict aliasing optimization in a case like this.
10744
10745 One possibility is to simply avoid the use of @option{-O2}, but
10746 that is a bit drastic, since it throws away a number of useful
10747 optimizations that do not involve strict aliasing assumptions.
10748
10749 A less drastic approach is to compile the program using the
10750 option @option{-fno-strict-aliasing}. Actually it is only the
10751 unit containing the dereferencing of the suspicious pointer
10752 that needs to be compiled. So in this case, if we compile
10753 unit @code{m} with this switch, then we get the expected
10754 value of zero printed. Analyzing which units might need
10755 the switch can be painful, so a more reasonable approach
10756 is to compile the entire program with options @option{-O2}
10757 and @option{-fno-strict-aliasing}. If the performance is
10758 satisfactory with this combination of options, then the
10759 advantage is that the entire issue of possible "wrong"
10760 optimization due to strict aliasing is avoided.
10761
10762 To avoid the use of compiler switches, the configuration
10763 pragma @code{No_Strict_Aliasing} with no parameters may be
10764 used to specify that for all access types, the strict
10765 aliasing optimization should be suppressed.
10766
10767 However, these approaches are still overkill, in that they causes
10768 all manipulations of all access values to be deoptimized. A more
10769 refined approach is to concentrate attention on the specific
10770 access type identified as problematic.
10771
10772 First, if a careful analysis of uses of the pointer shows
10773 that there are no possible problematic references, then
10774 the warning can be suppressed by bracketing the
10775 instantiation of @code{Unchecked_Conversion} to turn
10776 the warning off:
10777
10778 @smallexample @c ada
10779    pragma Warnings (Off);
10780    function to_a2u is
10781      new Unchecked_Conversion (a1, a2);
10782    pragma Warnings (On);
10783 @end smallexample
10784
10785 @noindent
10786 Of course that approach is not appropriate for this particular
10787 example, since indeed there is a problematic reference. In this
10788 case we can take one of two other approaches.
10789
10790 The first possibility is to move the instantiation of unchecked
10791 conversion to the unit in which the type is declared. In
10792 this example, we would move the instantiation of
10793 @code{Unchecked_Conversion} from the body of package
10794 @code{p2} to the spec of package @code{p1}. Now the
10795 warning disappears. That's because any use of the
10796 access type knows there is a suspicious unchecked
10797 conversion, and the strict aliasing optimization
10798 is automatically suppressed for the type.
10799
10800 If it is not practical to move the unchecked conversion to the same unit
10801 in which the destination access type is declared (perhaps because the
10802 source type is not visible in that unit), you may use pragma
10803 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
10804 same declarative sequence as the declaration of the access type:
10805
10806 @smallexample @c ada
10807    type a2 is access int2;
10808    pragma No_Strict_Aliasing (a2);
10809 @end smallexample
10810
10811 @noindent
10812 Here again, the compiler now knows that the strict aliasing optimization
10813 should be suppressed for any reference to type @code{a2} and the
10814 expected behavior is obtained.
10815
10816 Finally, note that although the compiler can generate warnings for
10817 simple cases of unchecked conversions, there are tricker and more
10818 indirect ways of creating type incorrect aliases which the compiler
10819 cannot detect. Examples are the use of address overlays and unchecked
10820 conversions involving composite types containing access types as
10821 components. In such cases, no warnings are generated, but there can
10822 still be aliasing problems. One safe coding practice is to forbid the
10823 use of address clauses for type overlaying, and to allow unchecked
10824 conversion only for primitive types. This is not really a significant
10825 restriction since any possible desired effect can be achieved by
10826 unchecked conversion of access values.
10827
10828 The aliasing analysis done in strict aliasing mode can certainly
10829 have significant benefits. We have seen cases of large scale
10830 application code where the time is increased by up to 5% by turning
10831 this optimization off. If you have code that includes significant
10832 usage of unchecked conversion, you might want to just stick with
10833 @option{-O1} and avoid the entire issue. If you get adequate
10834 performance at this level of optimization level, that's probably
10835 the safest approach. If tests show that you really need higher
10836 levels of optimization, then you can experiment with @option{-O2}
10837 and @option{-O2 -fno-strict-aliasing} to see how much effect this
10838 has on size and speed of the code. If you really need to use
10839 @option{-O2} with strict aliasing in effect, then you should
10840 review any uses of unchecked conversion of access types,
10841 particularly if you are getting the warnings described above.
10842
10843 @ifset vms
10844 @node Coverage Analysis
10845 @subsection Coverage Analysis
10846
10847 @noindent
10848 GNAT supports the HP Performance Coverage Analyzer (PCA), which allows
10849 the user to determine the distribution of execution time across a program,
10850 @pxref{Profiling} for details of usage.
10851 @end ifset
10852
10853
10854 @node Text_IO Suggestions
10855 @section @code{Text_IO} Suggestions
10856 @cindex @code{Text_IO} and performance
10857
10858 @noindent
10859 The @code{Ada.Text_IO} package has fairly high overheads due in part to
10860 the requirement of maintaining page and line counts. If performance
10861 is critical, a recommendation is to use @code{Stream_IO} instead of
10862 @code{Text_IO} for volume output, since this package has less overhead.
10863
10864 If @code{Text_IO} must be used, note that by default output to the standard
10865 output and standard error files is unbuffered (this provides better
10866 behavior when output statements are used for debugging, or if the
10867 progress of a program is observed by tracking the output, e.g. by
10868 using the Unix @command{tail -f} command to watch redirected output.
10869
10870 If you are generating large volumes of output with @code{Text_IO} and
10871 performance is an important factor, use a designated file instead
10872 of the standard output file, or change the standard output file to
10873 be buffered using @code{Interfaces.C_Streams.setvbuf}.
10874
10875
10876
10877 @node Reducing Size of Ada Executables with gnatelim
10878 @section Reducing Size of Ada Executables with @code{gnatelim}
10879 @findex gnatelim
10880
10881 @noindent
10882 This section describes @command{gnatelim}, a tool which detects unused
10883 subprograms and helps the compiler to create a smaller executable for your
10884 program.
10885
10886 @menu
10887 * About gnatelim::
10888 * Running gnatelim::
10889 * Processing Precompiled Libraries::
10890 * Correcting the List of Eliminate Pragmas::
10891 * Making Your Executables Smaller::
10892 * Summary of the gnatelim Usage Cycle::
10893 @end menu
10894
10895 @node About gnatelim
10896 @subsection About @code{gnatelim}
10897
10898 @noindent
10899 When a program shares a set of Ada
10900 packages with other programs, it may happen that this program uses
10901 only a fraction of the subprograms defined in these packages. The code
10902 created for these unused subprograms increases the size of the executable.
10903
10904 @code{gnatelim} tracks unused subprograms in an Ada program and
10905 outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the
10906 subprograms that are declared but never called. By placing the list of
10907 @code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and
10908 recompiling your program, you may decrease the size of its executable,
10909 because the compiler will not generate the code for 'eliminated' subprograms.
10910 @xref{Pragma Eliminate,,, gnat_rm, GNAT Reference Manual}, for more
10911 information about this pragma.
10912
10913 @code{gnatelim} needs as its input data the name of the main subprogram.
10914
10915 If a set of source files is specified as @code{gnatelim} arguments, it
10916 treats these files as a complete set of sources making up a program to
10917 analyse, and analyses only these sources.
10918
10919 After a full successful build of the main subprogram @code{gnatelim} can be
10920 called without  specifying sources to analyse, in this case it computes
10921 the source closure of the main unit from the @file{ALI} files.
10922
10923 The following command will create the set of @file{ALI} files needed for
10924 @code{gnatelim}:
10925
10926 @smallexample
10927 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
10928 @end smallexample
10929
10930 Note that @code{gnatelim} does not need object files.
10931
10932 @node Running gnatelim
10933 @subsection Running @code{gnatelim}
10934
10935 @noindent
10936 @code{gnatelim} has the following command-line interface:
10937
10938 @smallexample
10939 $ gnatelim [@var{switches}] ^-main^?MAIN^=@var{main_unit_name} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
10940 @end smallexample
10941
10942 @noindent
10943 @var{main_unit_name} should be a name of a source file that contains the main
10944 subprogram of a program (partition).
10945
10946 Each @var{filename} is the name (including the extension) of a source
10947 file to process. ``Wildcards'' are allowed, and
10948 the file name may contain path information.
10949
10950 @samp{@var{gcc_switches}} is a list of switches for
10951 @command{gcc}. They will be passed on to all compiler invocations made by
10952 @command{gnatelim} to generate the ASIS trees. Here you can provide
10953 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
10954 use the @option{-gnatec} switch to set the configuration file,
10955 use the @option{-gnat05} switch if sources should be compiled in
10956 Ada 2005 mode etc.
10957
10958 @code{gnatelim} has the following switches:
10959
10960 @table @option
10961 @c !sort!
10962 @item ^-files^/FILES^=@var{filename}
10963 @cindex @option{^-files^/FILES^} (@code{gnatelim})
10964 Take the argument source files from the specified file. This file should be an
10965 ordinary text file containing file names separated by spaces or
10966 line breaks. You can use this switch more than once in the same call to
10967 @command{gnatelim}. You also can combine this switch with
10968 an explicit list of files.
10969
10970 @item ^-log^/LOG^
10971 @cindex @option{^-log^/LOG^} (@command{gnatelim})
10972 Duplicate all the output sent to @file{stderr} into a log file. The log file
10973 is named @file{gnatelim.log} and is located in the current directory.
10974
10975 @item ^-log^/LOGFILE^=@var{filename}
10976 @cindex @option{^-log^/LOGFILE^} (@command{gnatelim})
10977 Duplicate all the output sent to @file{stderr} into a specified log file.
10978
10979 @cindex @option{^--no-elim-dispatch^/NO_DISPATCH^} (@command{gnatelim})
10980 @item ^--no-elim-dispatch^/NO_DISPATCH^
10981 Do not generate pragmas for dispatching operations.
10982
10983 @item ^--ignore^/IGNORE^=@var{filename}
10984 @cindex @option{^--ignore^/IGNORE^} (@command{gnatelim})
10985 Do not generate pragmas for subprograms declared in the sources
10986 listed in a specified file
10987
10988 @cindex @option{^-o^/OUTPUT^} (@command{gnatelim})
10989 @item ^-o^/OUTPUT^=@var{report_file}
10990 Put @command{gnatelim} output into a specified file. If this file already exists,
10991 it is overridden. If this switch is not used, @command{gnatelim} outputs its results
10992 into @file{stderr}
10993
10994 @item ^-q^/QUIET^
10995 @cindex @option{^-q^/QUIET^} (@command{gnatelim})
10996 Quiet mode: by default @code{gnatelim} outputs to the standard error
10997 stream the number of program units left to be processed. This option turns
10998 this trace off.
10999
11000 @cindex @option{^-t^/TIME^} (@command{gnatelim})
11001 @item ^-t^/TIME^
11002 Print out execution time.
11003
11004 @item ^-v^/VERBOSE^
11005 @cindex @option{^-v^/VERBOSE^} (@command{gnatelim})
11006 Verbose mode: @code{gnatelim} version information is printed as Ada
11007 comments to the standard output stream. Also, in addition to the number of
11008 program units left @code{gnatelim} will output the name of the current unit
11009 being processed.
11010
11011 @item ^-wq^/WARNINGS=QUIET^
11012 @cindex @option{^-wq^/WARNINGS=QUIET^} (@command{gnatelim})
11013 Quiet warning mode - some warnings are suppressed. In particular warnings that
11014 indicate that the analysed set of sources is incomplete to make up a
11015 partition and that some subprogram bodies are missing are not generated.
11016 @end table
11017
11018 @noindent
11019 Note: to invoke @command{gnatelim} with a project file, use the @code{gnat}
11020 driver (see @ref{The GNAT Driver and Project Files}).
11021
11022 @node Processing Precompiled Libraries
11023 @subsection Processing Precompiled Libraries
11024
11025 @noindent
11026 If some program uses a precompiled Ada library, it can be processed by
11027 @code{gnatelim} in a usual way. @code{gnatelim} will newer generate an
11028 Eliminate pragma for a subprogram if the body of this subprogram has not
11029 been analysed, this is a typical case for subprograms from precompiled
11030 libraries. Switch @option{^-wq^/WARNINGS=QUIET^} may be used to suppress
11031 warnings about missing source files and non-analyzed subprogram bodies
11032 that can be generated when processing precompiled Ada libraries.
11033
11034 @node Correcting the List of Eliminate Pragmas
11035 @subsection Correcting the List of Eliminate Pragmas
11036
11037 @noindent
11038 In some rare cases @code{gnatelim} may try to eliminate
11039 subprograms that are actually called in the program. In this case, the
11040 compiler will generate an error message of the form:
11041
11042 @smallexample
11043 main.adb:4:08: cannot reference subprogram "P" eliminated at elim.out:5
11044 @end smallexample
11045
11046 @noindent
11047 You will need to manually remove the wrong @code{Eliminate} pragmas from
11048 the configuration file indicated in the error message. You should recompile
11049 your program from scratch after that, because you need a consistent
11050 configuration file(s) during the entire compilation.
11051
11052 @node Making Your Executables Smaller
11053 @subsection Making Your Executables Smaller
11054
11055 @noindent
11056 In order to get a smaller executable for your program you now have to
11057 recompile the program completely with the configuration file containing
11058 pragmas Eliminate generated by gnatelim. If these pragmas are placed in
11059 @file{gnat.adc} file located in your current directory, just do:
11060
11061 @smallexample
11062 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
11063 @end smallexample
11064
11065 @noindent
11066 (Use the @option{^-f^/FORCE_COMPILE^} option for @command{gnatmake} to
11067 recompile everything
11068 with the set of pragmas @code{Eliminate} that you have obtained with
11069 @command{gnatelim}).
11070
11071 Be aware that the set of @code{Eliminate} pragmas is specific to each
11072 program. It is not recommended to merge sets of @code{Eliminate}
11073 pragmas created for different programs in one configuration file.
11074
11075 @node Summary of the gnatelim Usage Cycle
11076 @subsection Summary of the @code{gnatelim} Usage Cycle
11077
11078 @noindent
11079 Here is a quick summary of the steps to be taken in order to reduce
11080 the size of your executables with @code{gnatelim}. You may use
11081 other GNAT options to control the optimization level,
11082 to produce the debugging information, to set search path, etc.
11083
11084 @enumerate
11085 @item
11086 Create a complete set of @file{ALI} files (if the program has not been
11087 built already)
11088
11089 @smallexample
11090 $ gnatmake ^-c main_prog^/ACTIONS=COMPILE MAIN_PROG^
11091 @end smallexample
11092
11093 @item
11094 Generate a list of @code{Eliminate} pragmas in default configuration file
11095 @file{gnat.adc} in the current directory
11096 @smallexample
11097 @ifset vms
11098 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
11099 @end ifset
11100 @ifclear vms
11101 $ gnatelim main_prog >@r{[}>@r{]} gnat.adc
11102 @end ifclear
11103 @end smallexample
11104
11105 @item
11106 Recompile the application
11107
11108 @smallexample
11109 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
11110 @end smallexample
11111
11112 @end enumerate
11113
11114 @node Reducing Size of Executables with unused subprogram/data elimination
11115 @section Reducing Size of Executables with Unused Subprogram/Data Elimination
11116 @findex unused subprogram/data elimination
11117
11118 @noindent
11119 This section describes how you can eliminate unused subprograms and data from
11120 your executable just by setting options at compilation time.
11121
11122 @menu
11123 * About unused subprogram/data elimination::
11124 * Compilation options::
11125 * Example of unused subprogram/data elimination::
11126 @end menu
11127
11128 @node About unused subprogram/data elimination
11129 @subsection About unused subprogram/data elimination
11130
11131 @noindent
11132 By default, an executable contains all code and data of its composing objects
11133 (directly linked or coming from statically linked libraries), even data or code
11134 never used by this executable.
11135
11136 This feature will allow you to eliminate such unused code from your
11137 executable, making it smaller (in disk and in memory).
11138
11139 This functionality is available on all Linux platforms except for the IA-64
11140 architecture and on all cross platforms using the ELF binary file format.
11141 In both cases GNU binutils version 2.16 or later are required to enable it.
11142
11143 @node Compilation options
11144 @subsection Compilation options
11145
11146 @noindent
11147 The operation of eliminating the unused code and data from the final executable
11148 is directly performed by the linker.
11149
11150 In order to do this, it has to work with objects compiled with the
11151 following options:
11152 @option{-ffunction-sections} @option{-fdata-sections}.
11153 @cindex @option{-ffunction-sections} (@command{gcc})
11154 @cindex @option{-fdata-sections} (@command{gcc})
11155 These options are usable with C and Ada files.
11156 They will place respectively each
11157 function or data in a separate section in the resulting object file.
11158
11159 Once the objects and static libraries are created with these options, the
11160 linker can perform the dead code elimination. You can do this by setting
11161 the @option{-Wl,--gc-sections} option to gcc command or in the
11162 @option{-largs} section of @command{gnatmake}. This will perform a
11163 garbage collection of code and data never referenced.
11164
11165 If the linker performs a partial link (@option{-r} ld linker option), then you
11166 will need to provide one or several entry point using the
11167 @option{-e} / @option{--entry} ld option.
11168
11169 Note that objects compiled without the @option{-ffunction-sections} and
11170 @option{-fdata-sections} options can still be linked with the executable.
11171 However, no dead code elimination will be performed on those objects (they will
11172 be linked as is).
11173
11174 The GNAT static library is now compiled with -ffunction-sections and
11175 -fdata-sections on some platforms. This allows you to eliminate the unused code
11176 and data of the GNAT library from your executable.
11177
11178 @node Example of unused subprogram/data elimination
11179 @subsection Example of unused subprogram/data elimination
11180
11181 @noindent
11182 Here is a simple example:
11183
11184 @smallexample @c ada
11185 with Aux;
11186
11187 procedure Test is
11188 begin
11189    Aux.Used (10);
11190 end Test;
11191
11192 package Aux is
11193    Used_Data   : Integer;
11194    Unused_Data : Integer;
11195
11196    procedure Used   (Data : Integer);
11197    procedure Unused (Data : Integer);
11198 end Aux;
11199
11200 package body Aux is
11201    procedure Used (Data : Integer) is
11202    begin
11203       Used_Data := Data;
11204    end Used;
11205
11206    procedure Unused (Data : Integer) is
11207    begin
11208       Unused_Data := Data;
11209    end Unused;
11210 end Aux;
11211 @end smallexample
11212
11213 @noindent
11214 @code{Unused} and @code{Unused_Data} are never referenced in this code
11215 excerpt, and hence they may be safely removed from the final executable.
11216
11217 @smallexample
11218 $ gnatmake test
11219
11220 $ nm test | grep used
11221 020015f0 T aux__unused
11222 02005d88 B aux__unused_data
11223 020015cc T aux__used
11224 02005d84 B aux__used_data
11225
11226 $ gnatmake test -cargs -fdata-sections -ffunction-sections \
11227      -largs -Wl,--gc-sections
11228
11229 $ nm test | grep used
11230 02005350 T aux__used
11231 0201ffe0 B aux__used_data
11232 @end smallexample
11233
11234 @noindent
11235 It can be observed that the procedure @code{Unused} and the object
11236 @code{Unused_Data} are removed by the linker when using the
11237 appropriate options.
11238
11239 @c ********************************
11240 @node Renaming Files Using gnatchop
11241 @chapter Renaming Files Using @code{gnatchop}
11242 @findex gnatchop
11243
11244 @noindent
11245 This chapter discusses how to handle files with multiple units by using
11246 the @code{gnatchop} utility. This utility is also useful in renaming
11247 files to meet the standard GNAT default file naming conventions.
11248
11249 @menu
11250 * Handling Files with Multiple Units::
11251 * Operating gnatchop in Compilation Mode::
11252 * Command Line for gnatchop::
11253 * Switches for gnatchop::
11254 * Examples of gnatchop Usage::
11255 @end menu
11256
11257 @node Handling Files with Multiple Units
11258 @section Handling Files with Multiple Units
11259
11260 @noindent
11261 The basic compilation model of GNAT requires that a file submitted to the
11262 compiler have only one unit and there be a strict correspondence
11263 between the file name and the unit name.
11264
11265 The @code{gnatchop} utility allows both of these rules to be relaxed,
11266 allowing GNAT to process files which contain multiple compilation units
11267 and files with arbitrary file names. @code{gnatchop}
11268 reads the specified file and generates one or more output files,
11269 containing one unit per file. The unit and the file name correspond,
11270 as required by GNAT.
11271
11272 If you want to permanently restructure a set of ``foreign'' files so that
11273 they match the GNAT rules, and do the remaining development using the
11274 GNAT structure, you can simply use @command{gnatchop} once, generate the
11275 new set of files and work with them from that point on.
11276
11277 Alternatively, if you want to keep your files in the ``foreign'' format,
11278 perhaps to maintain compatibility with some other Ada compilation
11279 system, you can set up a procedure where you use @command{gnatchop} each
11280 time you compile, regarding the source files that it writes as temporary
11281 files that you throw away.
11282
11283 Note that if your file containing multiple units starts with a byte order
11284 mark (BOM) specifying UTF-8 encoding, then the files generated by gnatchop
11285 will each start with a copy of this BOM, meaning that they can be compiled
11286 automatically in UTF-8 mode without needing to specify an explicit encoding.
11287
11288 @node Operating gnatchop in Compilation Mode
11289 @section Operating gnatchop in Compilation Mode
11290
11291 @noindent
11292 The basic function of @code{gnatchop} is to take a file with multiple units
11293 and split it into separate files. The boundary between files is reasonably
11294 clear, except for the issue of comments and pragmas. In default mode, the
11295 rule is that any pragmas between units belong to the previous unit, except
11296 that configuration pragmas always belong to the following unit. Any comments
11297 belong to the following unit. These rules
11298 almost always result in the right choice of
11299 the split point without needing to mark it explicitly and most users will
11300 find this default to be what they want. In this default mode it is incorrect to
11301 submit a file containing only configuration pragmas, or one that ends in
11302 configuration pragmas, to @code{gnatchop}.
11303
11304 However, using a special option to activate ``compilation mode'',
11305 @code{gnatchop}
11306 can perform another function, which is to provide exactly the semantics
11307 required by the RM for handling of configuration pragmas in a compilation.
11308 In the absence of configuration pragmas (at the main file level), this
11309 option has no effect, but it causes such configuration pragmas to be handled
11310 in a quite different manner.
11311
11312 First, in compilation mode, if @code{gnatchop} is given a file that consists of
11313 only configuration pragmas, then this file is appended to the
11314 @file{gnat.adc} file in the current directory. This behavior provides
11315 the required behavior described in the RM for the actions to be taken
11316 on submitting such a file to the compiler, namely that these pragmas
11317 should apply to all subsequent compilations in the same compilation
11318 environment. Using GNAT, the current directory, possibly containing a
11319 @file{gnat.adc} file is the representation
11320 of a compilation environment. For more information on the
11321 @file{gnat.adc} file, see @ref{Handling of Configuration Pragmas}.
11322
11323 Second, in compilation mode, if @code{gnatchop}
11324 is given a file that starts with
11325 configuration pragmas, and contains one or more units, then these
11326 configuration pragmas are prepended to each of the chopped files. This
11327 behavior provides the required behavior described in the RM for the
11328 actions to be taken on compiling such a file, namely that the pragmas
11329 apply to all units in the compilation, but not to subsequently compiled
11330 units.
11331
11332 Finally, if configuration pragmas appear between units, they are appended
11333 to the previous unit. This results in the previous unit being illegal,
11334 since the compiler does not accept configuration pragmas that follow
11335 a unit. This provides the required RM behavior that forbids configuration
11336 pragmas other than those preceding the first compilation unit of a
11337 compilation.
11338
11339 For most purposes, @code{gnatchop} will be used in default mode. The
11340 compilation mode described above is used only if you need exactly
11341 accurate behavior with respect to compilations, and you have files
11342 that contain multiple units and configuration pragmas. In this
11343 circumstance the use of @code{gnatchop} with the compilation mode
11344 switch provides the required behavior, and is for example the mode
11345 in which GNAT processes the ACVC tests.
11346
11347 @node Command Line for gnatchop
11348 @section Command Line for @code{gnatchop}
11349
11350 @noindent
11351 The @code{gnatchop} command has the form:
11352
11353 @smallexample
11354 @c $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11355 @c      @ovar{directory}
11356 @c Expanding @ovar macro inline (explanation in macro def comments)
11357 $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11358       @r{[}@var{directory}@r{]}
11359 @end smallexample
11360
11361 @noindent
11362 The only required argument is the file name of the file to be chopped.
11363 There are no restrictions on the form of this file name. The file itself
11364 contains one or more Ada units, in normal GNAT format, concatenated
11365 together. As shown, more than one file may be presented to be chopped.
11366
11367 When run in default mode, @code{gnatchop} generates one output file in
11368 the current directory for each unit in each of the files.
11369
11370 @var{directory}, if specified, gives the name of the directory to which
11371 the output files will be written. If it is not specified, all files are
11372 written to the current directory.
11373
11374 For example, given a
11375 file called @file{hellofiles} containing
11376
11377 @smallexample @c ada
11378 @group
11379 @cartouche
11380 procedure hello;
11381
11382 with Text_IO; use Text_IO;
11383 procedure hello is
11384 begin
11385    Put_Line ("Hello");
11386 end hello;
11387 @end cartouche
11388 @end group
11389 @end smallexample
11390
11391 @noindent
11392 the command
11393
11394 @smallexample
11395 $ gnatchop ^hellofiles^HELLOFILES.^
11396 @end smallexample
11397
11398 @noindent
11399 generates two files in the current directory, one called
11400 @file{hello.ads} containing the single line that is the procedure spec,
11401 and the other called @file{hello.adb} containing the remaining text. The
11402 original file is not affected. The generated files can be compiled in
11403 the normal manner.
11404
11405 @noindent
11406 When gnatchop is invoked on a file that is empty or that contains only empty
11407 lines and/or comments, gnatchop will not fail, but will not produce any
11408 new sources.
11409
11410 For example, given a
11411 file called @file{toto.txt} containing
11412
11413 @smallexample @c ada
11414 @group
11415 @cartouche
11416 --  Just a comment
11417 @end cartouche
11418 @end group
11419 @end smallexample
11420
11421 @noindent
11422 the command
11423
11424 @smallexample
11425 $ gnatchop ^toto.txt^TOT.TXT^
11426 @end smallexample
11427
11428 @noindent
11429 will not produce any new file and will result in the following warnings:
11430
11431 @smallexample
11432 toto.txt:1:01: warning: empty file, contains no compilation units
11433 no compilation units found
11434 no source files written
11435 @end smallexample
11436
11437 @node Switches for gnatchop
11438 @section Switches for @code{gnatchop}
11439
11440 @noindent
11441 @command{gnatchop} recognizes the following switches:
11442
11443 @table @option
11444 @c !sort!
11445
11446 @item --version
11447 @cindex @option{--version} @command{gnatchop}
11448 Display Copyright and version, then exit disregarding all other options.
11449
11450 @item --help
11451 @cindex @option{--help} @command{gnatchop}
11452 If @option{--version} was not used, display usage, then exit disregarding
11453 all other options.
11454
11455 @item ^-c^/COMPILATION^
11456 @cindex @option{^-c^/COMPILATION^} (@code{gnatchop})
11457 Causes @code{gnatchop} to operate in compilation mode, in which
11458 configuration pragmas are handled according to strict RM rules. See
11459 previous section for a full description of this mode.
11460
11461 @ifclear vms
11462 @item -gnat@var{xxx}
11463 This passes the given @option{-gnat@var{xxx}} switch to @code{gnat} which is
11464 used to parse the given file. Not all @var{xxx} options make sense,
11465 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
11466 process a source file that uses Latin-2 coding for identifiers.
11467 @end ifclear
11468
11469 @item ^-h^/HELP^
11470 Causes @code{gnatchop} to generate a brief help summary to the standard
11471 output file showing usage information.
11472
11473 @item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^
11474 @cindex @option{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop})
11475 Limit generated file names to the specified number @code{mm}
11476 of characters.
11477 This is useful if the
11478 resulting set of files is required to be interoperable with systems
11479 which limit the length of file names.
11480 @ifset vms
11481 If no value is given, or
11482 if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given,
11483 a default of 39, suitable for OpenVMS Alpha
11484 Systems, is assumed
11485 @end ifset
11486 @ifclear vms
11487 No space is allowed between the @option{-k} and the numeric value. The numeric
11488 value may be omitted in which case a default of @option{-k8},
11489 suitable for use
11490 with DOS-like file systems, is used. If no @option{-k} switch
11491 is present then
11492 there is no limit on the length of file names.
11493 @end ifclear
11494
11495 @item ^-p^/PRESERVE^
11496 @cindex @option{^-p^/PRESERVE^} (@code{gnatchop})
11497 Causes the file ^modification^creation^ time stamp of the input file to be
11498 preserved and used for the time stamp of the output file(s). This may be
11499 useful for preserving coherency of time stamps in an environment where
11500 @code{gnatchop} is used as part of a standard build process.
11501
11502 @item ^-q^/QUIET^
11503 @cindex @option{^-q^/QUIET^} (@code{gnatchop})
11504 Causes output of informational messages indicating the set of generated
11505 files to be suppressed. Warnings and error messages are unaffected.
11506
11507 @item ^-r^/REFERENCE^
11508 @cindex @option{^-r^/REFERENCE^} (@code{gnatchop})
11509 @findex Source_Reference
11510 Generate @code{Source_Reference} pragmas. Use this switch if the output
11511 files are regarded as temporary and development is to be done in terms
11512 of the original unchopped file. This switch causes
11513 @code{Source_Reference} pragmas to be inserted into each of the
11514 generated files to refers back to the original file name and line number.
11515 The result is that all error messages refer back to the original
11516 unchopped file.
11517 In addition, the debugging information placed into the object file (when
11518 the @option{^-g^/DEBUG^} switch of @command{gcc} or @command{gnatmake} is
11519 specified)
11520 also refers back to this original file so that tools like profilers and
11521 debuggers will give information in terms of the original unchopped file.
11522
11523 If the original file to be chopped itself contains
11524 a @code{Source_Reference}
11525 pragma referencing a third file, then gnatchop respects
11526 this pragma, and the generated @code{Source_Reference} pragmas
11527 in the chopped file refer to the original file, with appropriate
11528 line numbers. This is particularly useful when @code{gnatchop}
11529 is used in conjunction with @code{gnatprep} to compile files that
11530 contain preprocessing statements and multiple units.
11531
11532 @item ^-v^/VERBOSE^
11533 @cindex @option{^-v^/VERBOSE^} (@code{gnatchop})
11534 Causes @code{gnatchop} to operate in verbose mode. The version
11535 number and copyright notice are output, as well as exact copies of
11536 the gnat1 commands spawned to obtain the chop control information.
11537
11538 @item ^-w^/OVERWRITE^
11539 @cindex @option{^-w^/OVERWRITE^} (@code{gnatchop})
11540 Overwrite existing file names. Normally @code{gnatchop} regards it as a
11541 fatal error if there is already a file with the same name as a
11542 file it would otherwise output, in other words if the files to be
11543 chopped contain duplicated units. This switch bypasses this
11544 check, and causes all but the last instance of such duplicated
11545 units to be skipped.
11546
11547 @ifclear vms
11548 @item --GCC=@var{xxxx}
11549 @cindex @option{--GCC=} (@code{gnatchop})
11550 Specify the path of the GNAT parser to be used. When this switch is used,
11551 no attempt is made to add the prefix to the GNAT parser executable.
11552 @end ifclear
11553 @end table
11554
11555 @node Examples of gnatchop Usage
11556 @section Examples of @code{gnatchop} Usage
11557
11558 @table @code
11559 @ifset vms
11560 @item gnatchop /OVERWRITE HELLO_S.ADA [PRERELEASE.FILES]
11561 @end ifset
11562 @ifclear vms
11563 @item gnatchop -w hello_s.ada prerelease/files
11564 @end ifclear
11565
11566 Chops the source file @file{hello_s.ada}. The output files will be
11567 placed in the directory @file{^prerelease/files^[PRERELEASE.FILES]^},
11568 overwriting any
11569 files with matching names in that directory (no files in the current
11570 directory are modified).
11571
11572 @item gnatchop ^archive^ARCHIVE.^
11573 Chops the source file @file{^archive^ARCHIVE.^}
11574 into the current directory. One
11575 useful application of @code{gnatchop} is in sending sets of sources
11576 around, for example in email messages. The required sources are simply
11577 concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^
11578 command), and then
11579 @command{gnatchop} is used at the other end to reconstitute the original
11580 file names.
11581
11582 @item gnatchop file1 file2 file3 direc
11583 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
11584 the resulting files in the directory @file{direc}. Note that if any units
11585 occur more than once anywhere within this set of files, an error message
11586 is generated, and no files are written. To override this check, use the
11587 @option{^-w^/OVERWRITE^} switch,
11588 in which case the last occurrence in the last file will
11589 be the one that is output, and earlier duplicate occurrences for a given
11590 unit will be skipped.
11591 @end table
11592
11593 @node Configuration Pragmas
11594 @chapter Configuration Pragmas
11595 @cindex Configuration pragmas
11596 @cindex Pragmas, configuration
11597
11598 @noindent
11599 Configuration pragmas include those pragmas described as
11600 such in the Ada Reference Manual, as well as
11601 implementation-dependent pragmas that are configuration pragmas.
11602 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
11603 for details on these additional GNAT-specific configuration pragmas.
11604 Most notably, the pragma @code{Source_File_Name}, which allows
11605 specifying non-default names for source files, is a configuration
11606 pragma. The following is a complete list of configuration pragmas
11607 recognized by GNAT:
11608
11609 @smallexample
11610    Ada_83
11611    Ada_95
11612    Ada_05
11613    Ada_2005
11614    Ada_12
11615    Ada_2012
11616    Annotate
11617    Assertion_Policy
11618    Assume_No_Invalid_Values
11619    C_Pass_By_Copy
11620    Check_Name
11621    Check_Policy
11622    Compile_Time_Error
11623    Compile_Time_Warning
11624    Compiler_Unit
11625    Component_Alignment
11626    Convention_Identifier
11627    Debug_Policy
11628    Detect_Blocking
11629    Default_Storage_Pool
11630    Discard_Names
11631    Elaboration_Checks
11632    Eliminate
11633    Extend_System
11634    Extensions_Allowed
11635    External_Name_Casing
11636    Fast_Math
11637    Favor_Top_Level
11638    Float_Representation
11639    Implicit_Packing
11640    Initialize_Scalars
11641    Interrupt_State
11642    License
11643    Locking_Policy
11644    Long_Float
11645    No_Run_Time
11646    No_Strict_Aliasing
11647    Normalize_Scalars
11648    Optimize_Alignment
11649    Persistent_BSS
11650    Polling
11651    Priority_Specific_Dispatching
11652    Profile
11653    Profile_Warnings
11654    Propagate_Exceptions
11655    Queuing_Policy
11656    Ravenscar
11657    Restricted_Run_Time
11658    Restrictions
11659    Restrictions_Warnings
11660    Reviewable
11661    Short_Circuit_And_Or
11662    Source_File_Name
11663    Source_File_Name_Project
11664    Style_Checks
11665    Suppress
11666    Suppress_Exception_Locations
11667    Task_Dispatching_Policy
11668    Universal_Data
11669    Unsuppress
11670    Use_VADS_Size
11671    Validity_Checks
11672    Warnings
11673    Wide_Character_Encoding
11674
11675 @end smallexample
11676
11677 @menu
11678 * Handling of Configuration Pragmas::
11679 * The Configuration Pragmas Files::
11680 @end menu
11681
11682 @node Handling of Configuration Pragmas
11683 @section Handling of Configuration Pragmas
11684
11685 Configuration pragmas may either appear at the start of a compilation
11686 unit, in which case they apply only to that unit, or they may apply to
11687 all compilations performed in a given compilation environment.
11688
11689 GNAT also provides the @code{gnatchop} utility to provide an automatic
11690 way to handle configuration pragmas following the semantics for
11691 compilations (that is, files with multiple units), described in the RM.
11692 See @ref{Operating gnatchop in Compilation Mode} for details.
11693 However, for most purposes, it will be more convenient to edit the
11694 @file{gnat.adc} file that contains configuration pragmas directly,
11695 as described in the following section.
11696
11697 @node The Configuration Pragmas Files
11698 @section The Configuration Pragmas Files
11699 @cindex @file{gnat.adc}
11700
11701 @noindent
11702 In GNAT a compilation environment is defined by the current
11703 directory at the time that a compile command is given. This current
11704 directory is searched for a file whose name is @file{gnat.adc}. If
11705 this file is present, it is expected to contain one or more
11706 configuration pragmas that will be applied to the current compilation.
11707 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
11708 considered.
11709
11710 Configuration pragmas may be entered into the @file{gnat.adc} file
11711 either by running @code{gnatchop} on a source file that consists only of
11712 configuration pragmas, or more conveniently  by
11713 direct editing of the @file{gnat.adc} file, which is a standard format
11714 source file.
11715
11716 In addition to @file{gnat.adc}, additional files containing configuration
11717 pragmas may be applied to the current compilation using the switch
11718 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
11719 contains only configuration pragmas. These configuration pragmas are
11720 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
11721 is present and switch @option{-gnatA} is not used).
11722
11723 It is allowed to specify several switches @option{-gnatec}, all of which
11724 will be taken into account.
11725
11726 If you are using project file, a separate mechanism is provided using
11727 project attributes, see @ref{Specifying Configuration Pragmas} for more
11728 details.
11729
11730 @ifset vms
11731 Of special interest to GNAT OpenVMS Alpha is the following
11732 configuration pragma:
11733
11734 @smallexample @c ada
11735 @cartouche
11736 pragma Extend_System (Aux_DEC);
11737 @end cartouche
11738 @end smallexample
11739
11740 @noindent
11741 In the presence of this pragma, GNAT adds to the definition of the
11742 predefined package SYSTEM all the additional types and subprograms that are
11743 defined in HP Ada. See @ref{Compatibility with HP Ada} for details.
11744 @end ifset
11745
11746 @node Handling Arbitrary File Naming Conventions Using gnatname
11747 @chapter Handling Arbitrary File Naming Conventions Using @code{gnatname}
11748 @cindex Arbitrary File Naming Conventions
11749
11750 @menu
11751 * Arbitrary File Naming Conventions::
11752 * Running gnatname::
11753 * Switches for gnatname::
11754 * Examples of gnatname Usage::
11755 @end menu
11756
11757 @node Arbitrary File Naming Conventions
11758 @section Arbitrary File Naming Conventions
11759
11760 @noindent
11761 The GNAT compiler must be able to know the source file name of a compilation
11762 unit.  When using the standard GNAT default file naming conventions
11763 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
11764 does not need additional information.
11765
11766 @noindent
11767 When the source file names do not follow the standard GNAT default file naming
11768 conventions, the GNAT compiler must be given additional information through
11769 a configuration pragmas file (@pxref{Configuration Pragmas})
11770 or a project file.
11771 When the non-standard file naming conventions are well-defined,
11772 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
11773 (@pxref{Alternative File Naming Schemes}) may be sufficient. However,
11774 if the file naming conventions are irregular or arbitrary, a number
11775 of pragma @code{Source_File_Name} for individual compilation units
11776 must be defined.
11777 To help maintain the correspondence between compilation unit names and
11778 source file names within the compiler,
11779 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
11780 set of files.
11781
11782 @node Running gnatname
11783 @section Running @code{gnatname}
11784
11785 @noindent
11786 The usual form of the @code{gnatname} command is
11787
11788 @smallexample
11789 @c $ gnatname @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}
11790 @c       @r{[}--and @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}@r{]}
11791 @c Expanding @ovar macro inline (explanation in macro def comments)
11792 $ gnatname @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}
11793       @r{[}--and @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}@r{]}
11794 @end smallexample
11795
11796 @noindent
11797 All of the arguments are optional. If invoked without any argument,
11798 @code{gnatname} will display its usage.
11799
11800 @noindent
11801 When used with at least one naming pattern, @code{gnatname} will attempt to
11802 find all the compilation units in files that follow at least one of the
11803 naming patterns. To find these compilation units,
11804 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
11805 regular files.
11806
11807 @noindent
11808 One or several Naming Patterns may be given as arguments to @code{gnatname}.
11809 Each Naming Pattern is enclosed between double quotes (or single
11810 quotes on Windows).
11811 A Naming Pattern is a regular expression similar to the wildcard patterns
11812 used in file names by the Unix shells or the DOS prompt.
11813
11814 @noindent
11815 @code{gnatname} may be called with several sections of directories/patterns.
11816 Sections are separated by switch @code{--and}. In each section, there must be
11817 at least one pattern. If no directory is specified in a section, the current
11818 directory (or the project directory is @code{-P} is used) is implied.
11819 The options other that the directory switches and the patterns apply globally
11820 even if they are in different sections.
11821
11822 @noindent
11823 Examples of Naming Patterns are
11824
11825 @smallexample
11826    "*.[12].ada"
11827    "*.ad[sb]*"
11828    "body_*"    "spec_*"
11829 @end smallexample
11830
11831 @noindent
11832 For a more complete description of the syntax of Naming Patterns,
11833 see the second kind of regular expressions described in @file{g-regexp.ads}
11834 (the ``Glob'' regular expressions).
11835
11836 @noindent
11837 When invoked with no switch @code{-P}, @code{gnatname} will create a
11838 configuration pragmas file @file{gnat.adc} in the current working directory,
11839 with pragmas @code{Source_File_Name} for each file that contains a valid Ada
11840 unit.
11841
11842 @node Switches for gnatname
11843 @section Switches for @code{gnatname}
11844
11845 @noindent
11846 Switches for @code{gnatname} must precede any specified Naming Pattern.
11847
11848 @noindent
11849 You may specify any of the following switches to @code{gnatname}:
11850
11851 @table @option
11852 @c !sort!
11853
11854 @item --version
11855 @cindex @option{--version} @command{gnatname}
11856 Display Copyright and version, then exit disregarding all other options.
11857
11858 @item --help
11859 @cindex @option{--help} @command{gnatname}
11860 If @option{--version} was not used, display usage, then exit disregarding
11861 all other options.
11862
11863 @item --and
11864 Start another section of directories/patterns.
11865
11866 @item ^-c^/CONFIG_FILE=^@file{file}
11867 @cindex @option{^-c^/CONFIG_FILE^} (@code{gnatname})
11868 Create a configuration pragmas file @file{file} (instead of the default
11869 @file{gnat.adc}).
11870 @ifclear vms
11871 There may be zero, one or more space between @option{-c} and
11872 @file{file}.
11873 @end ifclear
11874 @file{file} may include directory information. @file{file} must be
11875 writable. There may be only one switch @option{^-c^/CONFIG_FILE^}.
11876 When a switch @option{^-c^/CONFIG_FILE^} is
11877 specified, no switch @option{^-P^/PROJECT_FILE^} may be specified (see below).
11878
11879 @item ^-d^/SOURCE_DIRS=^@file{dir}
11880 @cindex @option{^-d^/SOURCE_DIRS^} (@code{gnatname})
11881 Look for source files in directory @file{dir}. There may be zero, one or more
11882 spaces between @option{^-d^/SOURCE_DIRS=^} and @file{dir}.
11883 When a switch @option{^-d^/SOURCE_DIRS^}
11884 is specified, the current working directory will not be searched for source
11885 files, unless it is explicitly specified with a @option{^-d^/SOURCE_DIRS^}
11886 or @option{^-D^/DIR_FILES^} switch.
11887 Several switches @option{^-d^/SOURCE_DIRS^} may be specified.
11888 If @file{dir} is a relative path, it is relative to the directory of
11889 the configuration pragmas file specified with switch
11890 @option{^-c^/CONFIG_FILE^},
11891 or to the directory of the project file specified with switch
11892 @option{^-P^/PROJECT_FILE^} or,
11893 if neither switch @option{^-c^/CONFIG_FILE^}
11894 nor switch @option{^-P^/PROJECT_FILE^} are specified, it is relative to the
11895 current working directory. The directory
11896 specified with switch @option{^-d^/SOURCE_DIRS^} must exist and be readable.
11897
11898 @item ^-D^/DIRS_FILE=^@file{file}
11899 @cindex @option{^-D^/DIRS_FILE^} (@code{gnatname})
11900 Look for source files in all directories listed in text file @file{file}.
11901 There may be zero, one or more spaces between @option{^-D^/DIRS_FILE=^}
11902 and @file{file}.
11903 @file{file} must be an existing, readable text file.
11904 Each nonempty line in @file{file} must be a directory.
11905 Specifying switch @option{^-D^/DIRS_FILE^} is equivalent to specifying as many
11906 switches @option{^-d^/SOURCE_DIRS^} as there are nonempty lines in
11907 @file{file}.
11908
11909 @item ^-f^/FOREIGN_PATTERN=^@file{pattern}
11910 @cindex @option{^-f^/FOREIGN_PATTERN^} (@code{gnatname})
11911 Foreign patterns. Using this switch, it is possible to add sources of languages
11912 other than Ada to the list of sources of a project file.
11913 It is only useful if a ^-P^/PROJECT_FILE^ switch is used.
11914 For example,
11915 @smallexample
11916 gnatname ^-Pprj -f"*.c"^/PROJECT_FILE=PRJ /FOREIGN_PATTERN=*.C^ "*.ada"
11917 @end smallexample
11918 @noindent
11919 will look for Ada units in all files with the @file{.ada} extension,
11920 and will add to the list of file for project @file{prj.gpr} the C files
11921 with extension @file{.^c^C^}.
11922
11923 @item ^-h^/HELP^
11924 @cindex @option{^-h^/HELP^} (@code{gnatname})
11925 Output usage (help) information. The output is written to @file{stdout}.
11926
11927 @item ^-P^/PROJECT_FILE=^@file{proj}
11928 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatname})
11929 Create or update project file @file{proj}. There may be zero, one or more space
11930 between @option{-P} and @file{proj}. @file{proj} may include directory
11931 information. @file{proj} must be writable.
11932 There may be only one switch @option{^-P^/PROJECT_FILE^}.
11933 When a switch @option{^-P^/PROJECT_FILE^} is specified,
11934 no switch @option{^-c^/CONFIG_FILE^} may be specified.
11935
11936 @item ^-v^/VERBOSE^
11937 @cindex @option{^-v^/VERBOSE^} (@code{gnatname})
11938 Verbose mode. Output detailed explanation of behavior to @file{stdout}.
11939 This includes name of the file written, the name of the directories to search
11940 and, for each file in those directories whose name matches at least one of
11941 the Naming Patterns, an indication of whether the file contains a unit,
11942 and if so the name of the unit.
11943
11944 @item ^-v -v^/VERBOSE /VERBOSE^
11945 @cindex @option{^-v -v^/VERBOSE /VERBOSE^} (@code{gnatname})
11946 Very Verbose mode. In addition to the output produced in verbose mode,
11947 for each file in the searched directories whose name matches none of
11948 the Naming Patterns, an indication is given that there is no match.
11949
11950 @item ^-x^/EXCLUDED_PATTERN=^@file{pattern}
11951 @cindex @option{^-x^/EXCLUDED_PATTERN^} (@code{gnatname})
11952 Excluded patterns. Using this switch, it is possible to exclude some files
11953 that would match the name patterns. For example,
11954 @smallexample
11955 gnatname ^-x "*_nt.ada"^/EXCLUDED_PATTERN=*_nt.ada^ "*.ada"
11956 @end smallexample
11957 @noindent
11958 will look for Ada units in all files with the @file{.ada} extension,
11959 except those whose names end with @file{_nt.ada}.
11960
11961 @end table
11962
11963 @node Examples of gnatname Usage
11964 @section Examples of @code{gnatname} Usage
11965
11966 @ifset vms
11967 @smallexample
11968 $ gnatname /CONFIG_FILE=[HOME.ME]NAMES.ADC /SOURCE_DIRS=SOURCES "[a-z]*.ada*"
11969 @end smallexample
11970 @end ifset
11971
11972 @ifclear vms
11973 @smallexample
11974 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
11975 @end smallexample
11976 @end ifclear
11977
11978 @noindent
11979 In this example, the directory @file{^/home/me^[HOME.ME]^} must already exist
11980 and be writable. In addition, the directory
11981 @file{^/home/me/sources^[HOME.ME.SOURCES]^} (specified by
11982 @option{^-d sources^/SOURCE_DIRS=SOURCES^}) must exist and be readable.
11983
11984 @ifclear vms
11985 Note the optional spaces after @option{-c} and @option{-d}.
11986 @end ifclear
11987
11988 @smallexample
11989 @ifclear vms
11990 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
11991   -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
11992 @end ifclear
11993 @ifset vms
11994 $ gnatname  /PROJECT_FILE=[HOME.ME]PROJ
11995   /EXCLUDED_PATTERN=*_nt_body.ada
11996   /SOURCE_DIRS=(SOURCES,[SOURCES.PLUS])
11997   /DIRS_FILE=COMMON_DIRS.TXT "body_*" "spec_*"
11998 @end ifset
11999 @end smallexample
12000
12001 Note that several switches @option{^-d^/SOURCE_DIRS^} may be used,
12002 even in conjunction with one or several switches
12003 @option{^-D^/DIRS_FILE^}. Several Naming Patterns and one excluded pattern
12004 are used in this example.
12005
12006 @c *****************************************
12007 @c * G N A T  P r o j e c t  M a n a g e r *
12008 @c *****************************************
12009
12010 @c ------ macros for projects.texi
12011 @c These macros are needed when building the gprbuild documentation, but
12012 @c should have no effect in the gnat user's guide
12013
12014 @macro CODESAMPLE{TXT}
12015 @smallexample
12016 @group
12017 \TXT\
12018 @end group
12019 @end smallexample
12020 @end macro
12021
12022 @macro PROJECTFILE{TXT}
12023 @CODESAMPLE{\TXT\}
12024 @end macro
12025
12026 @c simulates a newline when in a @CODESAMPLE
12027 @macro NL{}
12028 @end macro
12029
12030 @macro TIP{TXT}
12031 @quotation
12032 @noindent
12033 \TXT\
12034 @end quotation
12035 @end macro
12036
12037 @macro TIPHTML{TXT}
12038 \TXT\
12039 @end macro
12040
12041 @macro IMPORTANT{TXT}
12042 @quotation
12043 @noindent
12044 \TXT\
12045 @end quotation
12046
12047 @end macro
12048
12049 @macro NOTE{TXT}
12050 @quotation
12051 @noindent
12052 \TXT\
12053 @end quotation
12054 @end macro
12055
12056 @include projects.texi
12057
12058 @c *****************************************
12059 @c * Cross-referencing tools
12060 @c *****************************************
12061
12062 @node The Cross-Referencing Tools gnatxref and gnatfind
12063 @chapter  The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
12064 @findex gnatxref
12065 @findex gnatfind
12066
12067 @noindent
12068 The compiler generates cross-referencing information (unless
12069 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
12070 This information indicates where in the source each entity is declared and
12071 referenced. Note that entities in package Standard are not included, but
12072 entities in all other predefined units are included in the output.
12073
12074 Before using any of these two tools, you need to compile successfully your
12075 application, so that GNAT gets a chance to generate the cross-referencing
12076 information.
12077
12078 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
12079 information to provide the user with the capability to easily locate the
12080 declaration and references to an entity. These tools are quite similar,
12081 the difference being that @code{gnatfind} is intended for locating
12082 definitions and/or references to a specified entity or entities, whereas
12083 @code{gnatxref} is oriented to generating a full report of all
12084 cross-references.
12085
12086 To use these tools, you must not compile your application using the
12087 @option{-gnatx} switch on the @command{gnatmake} command line
12088 (@pxref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
12089 information will not be generated.
12090
12091 Note: to invoke @code{gnatxref} or @code{gnatfind} with a project file,
12092 use the @code{gnat} driver (see @ref{The GNAT Driver and Project Files}).
12093
12094 @menu
12095 * Switches for gnatxref::
12096 * Switches for gnatfind::
12097 * Project Files for gnatxref and gnatfind::
12098 * Regular Expressions in gnatfind and gnatxref::
12099 * Examples of gnatxref Usage::
12100 * Examples of gnatfind Usage::
12101 @end menu
12102
12103 @node Switches for gnatxref
12104 @section @code{gnatxref} Switches
12105
12106 @noindent
12107 The command invocation for @code{gnatxref} is:
12108 @smallexample
12109 @c $ gnatxref @ovar{switches} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
12110 @c Expanding @ovar macro inline (explanation in macro def comments)
12111 $ gnatxref @r{[}@var{switches}@r{]} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
12112 @end smallexample
12113
12114 @noindent
12115 where
12116
12117 @table @var
12118 @item sourcefile1
12119 @itemx sourcefile2
12120 identifies the source files for which a report is to be generated. The
12121 ``with''ed units will be processed too. You must provide at least one file.
12122
12123 These file names are considered to be regular expressions, so for instance
12124 specifying @file{source*.adb} is the same as giving every file in the current
12125 directory whose name starts with @file{source} and whose extension is
12126 @file{adb}.
12127
12128 You shouldn't specify any directory name, just base names. @command{gnatxref}
12129 and @command{gnatfind} will be able to locate these files by themselves using
12130 the source path. If you specify directories, no result is produced.
12131
12132 @end table
12133
12134 @noindent
12135 The switches can be:
12136 @table @option
12137 @c !sort!
12138 @item --version
12139 @cindex @option{--version} @command{gnatxref}
12140 Display Copyright and version, then exit disregarding all other options.
12141
12142 @item --help
12143 @cindex @option{--help} @command{gnatxref}
12144 If @option{--version} was not used, display usage, then exit disregarding
12145 all other options.
12146
12147 @item ^-a^/ALL_FILES^
12148 @cindex @option{^-a^/ALL_FILES^} (@command{gnatxref})
12149 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
12150 the read-only files found in the library search path. Otherwise, these files
12151 will be ignored. This option can be used to protect Gnat sources or your own
12152 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
12153 much faster, and their output much smaller. Read-only here refers to access
12154 or permissions status in the file system for the current user.
12155
12156 @item -aIDIR
12157 @cindex @option{-aIDIR} (@command{gnatxref})
12158 When looking for source files also look in directory DIR. The order in which
12159 source file search is undertaken is the same as for @command{gnatmake}.
12160
12161 @item -aODIR
12162 @cindex @option{-aODIR} (@command{gnatxref})
12163 When searching for library and object files, look in directory
12164 DIR. The order in which library files are searched is the same as for
12165 @command{gnatmake}.
12166
12167 @item -nostdinc
12168 @cindex @option{-nostdinc} (@command{gnatxref})
12169 Do not look for sources in the system default directory.
12170
12171 @item -nostdlib
12172 @cindex @option{-nostdlib} (@command{gnatxref})
12173 Do not look for library files in the system default directory.
12174
12175 @item --ext=@var{extension}
12176 @cindex @option{--ext} (@command{gnatxref})
12177 Specify an alternate ali file extension. The default is @code{ali} and other
12178 extensions (e.g. @code{sli} for SPARK library files) may be specified via this
12179 switch. Note that if this switch overrides the default, which means that only
12180 the new extension will be considered.
12181
12182 @item --RTS=@var{rts-path}
12183 @cindex @option{--RTS} (@command{gnatxref})
12184 Specifies the default location of the runtime library. Same meaning as the
12185 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
12186
12187 @item ^-d^/DERIVED_TYPES^
12188 @cindex @option{^-d^/DERIVED_TYPES^} (@command{gnatxref})
12189 If this switch is set @code{gnatxref} will output the parent type
12190 reference for each matching derived types.
12191
12192 @item ^-f^/FULL_PATHNAME^
12193 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatxref})
12194 If this switch is set, the output file names will be preceded by their
12195 directory (if the file was found in the search path). If this switch is
12196 not set, the directory will not be printed.
12197
12198 @item ^-g^/IGNORE_LOCALS^
12199 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatxref})
12200 If this switch is set, information is output only for library-level
12201 entities, ignoring local entities. The use of this switch may accelerate
12202 @code{gnatfind} and @code{gnatxref}.
12203
12204 @item -IDIR
12205 @cindex @option{-IDIR} (@command{gnatxref})
12206 Equivalent to @samp{-aODIR -aIDIR}.
12207
12208 @item -pFILE
12209 @cindex @option{-pFILE} (@command{gnatxref})
12210 Specify a project file to use @xref{GNAT Project Manager}.
12211 If you need to use the @file{.gpr}
12212 project files, you should use gnatxref through the GNAT driver
12213 (@command{gnat xref -Pproject}).
12214
12215 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
12216 project file in the current directory.
12217
12218 If a project file is either specified or found by the tools, then the content
12219 of the source directory and object directory lines are added as if they
12220 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^}
12221 and @samp{^-aO^OBJECT_SEARCH^}.
12222 @item ^-u^/UNUSED^
12223 Output only unused symbols. This may be really useful if you give your
12224 main compilation unit on the command line, as @code{gnatxref} will then
12225 display every unused entity and 'with'ed package.
12226
12227 @ifclear vms
12228 @item -v
12229 Instead of producing the default output, @code{gnatxref} will generate a
12230 @file{tags} file that can be used by vi. For examples how to use this
12231 feature, see @ref{Examples of gnatxref Usage}. The tags file is output
12232 to the standard output, thus you will have to redirect it to a file.
12233 @end ifclear
12234
12235 @end table
12236
12237 @noindent
12238 All these switches may be in any order on the command line, and may even
12239 appear after the file names. They need not be separated by spaces, thus
12240 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
12241 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
12242
12243 @node Switches for gnatfind
12244 @section @code{gnatfind} Switches
12245
12246 @noindent
12247 The command line for @code{gnatfind} is:
12248
12249 @smallexample
12250 @c $ gnatfind @ovar{switches} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
12251 @c       @r{[}@var{file1} @var{file2} @dots{}]
12252 @c Expanding @ovar macro inline (explanation in macro def comments)
12253 $ gnatfind @r{[}@var{switches}@r{]} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
12254       @r{[}@var{file1} @var{file2} @dots{}@r{]}
12255 @end smallexample
12256
12257 @noindent
12258 where
12259
12260 @table @var
12261 @item pattern
12262 An entity will be output only if it matches the regular expression found
12263 in @var{pattern}, see @ref{Regular Expressions in gnatfind and gnatxref}.
12264
12265 Omitting the pattern is equivalent to specifying @samp{*}, which
12266 will match any entity. Note that if you do not provide a pattern, you
12267 have to provide both a sourcefile and a line.
12268
12269 Entity names are given in Latin-1, with uppercase/lowercase equivalence
12270 for matching purposes. At the current time there is no support for
12271 8-bit codes other than Latin-1, or for wide characters in identifiers.
12272
12273 @item sourcefile
12274 @code{gnatfind} will look for references, bodies or declarations
12275 of symbols referenced in @file{@var{sourcefile}}, at line @var{line}
12276 and column @var{column}. See @ref{Examples of gnatfind Usage}
12277 for syntax examples.
12278
12279 @item line
12280 is a decimal integer identifying the line number containing
12281 the reference to the entity (or entities) to be located.
12282
12283 @item column
12284 is a decimal integer identifying the exact location on the
12285 line of the first character of the identifier for the
12286 entity reference. Columns are numbered from 1.
12287
12288 @item file1 file2 @dots{}
12289 The search will be restricted to these source files. If none are given, then
12290 the search will be done for every library file in the search path.
12291 These file must appear only after the pattern or sourcefile.
12292
12293 These file names are considered to be regular expressions, so for instance
12294 specifying @file{source*.adb} is the same as giving every file in the current
12295 directory whose name starts with @file{source} and whose extension is
12296 @file{adb}.
12297
12298 The location of the spec of the entity will always be displayed, even if it
12299 isn't in one of @file{@var{file1}}, @file{@var{file2}},@enddots{}  The
12300 occurrences of the entity in the separate units of the ones given on the
12301 command line will also be displayed.
12302
12303 Note that if you specify at least one file in this part, @code{gnatfind} may
12304 sometimes not be able to find the body of the subprograms.
12305
12306 @end table
12307
12308 @noindent
12309 At least one of 'sourcefile' or 'pattern' has to be present on
12310 the command line.
12311
12312 The following switches are available:
12313 @table @option
12314 @c !sort!
12315
12316 @cindex @option{--version} @command{gnatfind}
12317 Display Copyright and version, then exit disregarding all other options.
12318
12319 @item --help
12320 @cindex @option{--help} @command{gnatfind}
12321 If @option{--version} was not used, display usage, then exit disregarding
12322 all other options.
12323
12324 @item ^-a^/ALL_FILES^
12325 @cindex @option{^-a^/ALL_FILES^} (@command{gnatfind})
12326 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
12327 the read-only files found in the library search path. Otherwise, these files
12328 will be ignored. This option can be used to protect Gnat sources or your own
12329 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
12330 much faster, and their output much smaller. Read-only here refers to access
12331 or permission status in the file system for the current user.
12332
12333 @item -aIDIR
12334 @cindex @option{-aIDIR} (@command{gnatfind})
12335 When looking for source files also look in directory DIR. The order in which
12336 source file search is undertaken is the same as for @command{gnatmake}.
12337
12338 @item -aODIR
12339 @cindex @option{-aODIR} (@command{gnatfind})
12340 When searching for library and object files, look in directory
12341 DIR. The order in which library files are searched is the same as for
12342 @command{gnatmake}.
12343
12344 @item -nostdinc
12345 @cindex @option{-nostdinc} (@command{gnatfind})
12346 Do not look for sources in the system default directory.
12347
12348 @item -nostdlib
12349 @cindex @option{-nostdlib} (@command{gnatfind})
12350 Do not look for library files in the system default directory.
12351
12352 @item --ext=@var{extension}
12353 @cindex @option{--ext} (@command{gnatfind})
12354 Specify an alternate ali file extension. The default is @code{ali} and other
12355 extensions (e.g. @code{sli} for SPARK library files) may be specified via this
12356 switch. Note that if this switch overrides the default, which means that only
12357 the new extension will be considered.
12358
12359 @item --RTS=@var{rts-path}
12360 @cindex @option{--RTS} (@command{gnatfind})
12361 Specifies the default location of the runtime library. Same meaning as the
12362 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
12363
12364 @item ^-d^/DERIVED_TYPE_INFORMATION^
12365 @cindex @option{^-d^/DERIVED_TYPE_INFORMATION^} (@code{gnatfind})
12366 If this switch is set, then @code{gnatfind} will output the parent type
12367 reference for each matching derived types.
12368
12369 @item ^-e^/EXPRESSIONS^
12370 @cindex @option{^-e^/EXPRESSIONS^} (@command{gnatfind})
12371 By default, @code{gnatfind} accept the simple regular expression set for
12372 @samp{pattern}. If this switch is set, then the pattern will be
12373 considered as full Unix-style regular expression.
12374
12375 @item ^-f^/FULL_PATHNAME^
12376 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatfind})
12377 If this switch is set, the output file names will be preceded by their
12378 directory (if the file was found in the search path). If this switch is
12379 not set, the directory will not be printed.
12380
12381 @item ^-g^/IGNORE_LOCALS^
12382 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatfind})
12383 If this switch is set, information is output only for library-level
12384 entities, ignoring local entities. The use of this switch may accelerate
12385 @code{gnatfind} and @code{gnatxref}.
12386
12387 @item -IDIR
12388 @cindex @option{-IDIR} (@command{gnatfind})
12389 Equivalent to @samp{-aODIR -aIDIR}.
12390
12391 @item -pFILE
12392 @cindex @option{-pFILE} (@command{gnatfind})
12393 Specify a project file (@pxref{GNAT Project Manager}) to use.
12394 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
12395 project file in the current directory.
12396
12397 If a project file is either specified or found by the tools, then the content
12398 of the source directory and object directory lines are added as if they
12399 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and
12400 @samp{^-aO^/OBJECT_SEARCH^}.
12401
12402 @item ^-r^/REFERENCES^
12403 @cindex @option{^-r^/REFERENCES^} (@command{gnatfind})
12404 By default, @code{gnatfind} will output only the information about the
12405 declaration, body or type completion of the entities. If this switch is
12406 set, the @code{gnatfind} will locate every reference to the entities in
12407 the files specified on the command line (or in every file in the search
12408 path if no file is given on the command line).
12409
12410 @item ^-s^/PRINT_LINES^
12411 @cindex @option{^-s^/PRINT_LINES^} (@command{gnatfind})
12412 If this switch is set, then @code{gnatfind} will output the content
12413 of the Ada source file lines were the entity was found.
12414
12415 @item ^-t^/TYPE_HIERARCHY^
12416 @cindex @option{^-t^/TYPE_HIERARCHY^} (@command{gnatfind})
12417 If this switch is set, then @code{gnatfind} will output the type hierarchy for
12418 the specified type. It act like -d option but recursively from parent
12419 type to parent type. When this switch is set it is not possible to
12420 specify more than one file.
12421
12422 @end table
12423
12424 @noindent
12425 All these switches may be in any order on the command line, and may even
12426 appear after the file names. They need not be separated by spaces, thus
12427 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
12428 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
12429
12430 As stated previously, gnatfind will search in every directory in the
12431 search path. You can force it to look only in the current directory if
12432 you specify @code{*} at the end of the command line.
12433
12434 @node Project Files for gnatxref and gnatfind
12435 @section Project Files for @command{gnatxref} and @command{gnatfind}
12436
12437 @noindent
12438 Project files allow a programmer to specify how to compile its
12439 application, where to find sources, etc.  These files are used
12440 @ifclear vms
12441 primarily by GPS, but they can also be used
12442 @end ifclear
12443 by the two tools
12444 @code{gnatxref} and @code{gnatfind}.
12445
12446 A project file name must end with @file{.gpr}. If a single one is
12447 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
12448 extract the information from it. If multiple project files are found, none of
12449 them is read, and you have to use the @samp{-p} switch to specify the one
12450 you want to use.
12451
12452 The following lines can be included, even though most of them have default
12453 values which can be used in most cases.
12454 The lines can be entered in any order in the file.
12455 Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
12456 each line. If you have multiple instances, only the last one is taken into
12457 account.
12458
12459 @table @code
12460 @item src_dir=DIR
12461 [default: @code{"^./^[]^"}]
12462 specifies a directory where to look for source files. Multiple @code{src_dir}
12463 lines can be specified and they will be searched in the order they
12464 are specified.
12465
12466 @item obj_dir=DIR
12467 [default: @code{"^./^[]^"}]
12468 specifies a directory where to look for object and library files. Multiple
12469 @code{obj_dir} lines can be specified, and they will be searched in the order
12470 they are specified
12471
12472 @item comp_opt=SWITCHES
12473 [default: @code{""}]
12474 creates a variable which can be referred to subsequently by using
12475 the @code{$@{comp_opt@}} notation. This is intended to store the default
12476 switches given to @command{gnatmake} and @command{gcc}.
12477
12478 @item bind_opt=SWITCHES
12479 [default: @code{""}]
12480 creates a variable which can be referred to subsequently by using
12481 the @samp{$@{bind_opt@}} notation. This is intended to store the default
12482 switches given to @command{gnatbind}.
12483
12484 @item link_opt=SWITCHES
12485 [default: @code{""}]
12486 creates a variable which can be referred to subsequently by using
12487 the @samp{$@{link_opt@}} notation. This is intended to store the default
12488 switches given to @command{gnatlink}.
12489
12490 @item main=EXECUTABLE
12491 [default: @code{""}]
12492 specifies the name of the executable for the application. This variable can
12493 be referred to in the following lines by using the @samp{$@{main@}} notation.
12494
12495 @ifset vms
12496 @item comp_cmd=COMMAND
12497 [default: @code{"GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"}]
12498 @end ifset
12499 @ifclear vms
12500 @item comp_cmd=COMMAND
12501 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
12502 @end ifclear
12503 specifies the command used to compile a single file in the application.
12504
12505 @ifset vms
12506 @item make_cmd=COMMAND
12507 [default: @code{"GNAT MAKE $@{main@}
12508 /SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@}
12509 /DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@}
12510 /BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"}]
12511 @end ifset
12512 @ifclear vms
12513 @item make_cmd=COMMAND
12514 [default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
12515 -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
12516 -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
12517 @end ifclear
12518 specifies the command used to recompile the whole application.
12519
12520 @item run_cmd=COMMAND
12521 [default: @code{"$@{main@}"}]
12522 specifies the command used to run the application.
12523
12524 @item debug_cmd=COMMAND
12525 [default: @code{"gdb $@{main@}"}]
12526 specifies the command used to debug the application
12527
12528 @end table
12529
12530 @noindent
12531 @command{gnatxref} and @command{gnatfind} only take into account the
12532 @code{src_dir} and @code{obj_dir} lines, and ignore the others.
12533
12534 @node Regular Expressions in gnatfind and gnatxref
12535 @section  Regular Expressions in @code{gnatfind} and @code{gnatxref}
12536
12537 @noindent
12538 As specified in the section about @command{gnatfind}, the pattern can be a
12539 regular expression. Actually, there are to set of regular expressions
12540 which are recognized by the program:
12541
12542 @table @code
12543 @item globbing patterns
12544 These are the most usual regular expression. They are the same that you
12545 generally used in a Unix shell command line, or in a DOS session.
12546
12547 Here is a more formal grammar:
12548 @smallexample
12549 @group
12550 @iftex
12551 @leftskip=.5cm
12552 @end iftex
12553 regexp ::= term
12554 term   ::= elmt            -- matches elmt
12555 term   ::= elmt elmt       -- concatenation (elmt then elmt)
12556 term   ::= *               -- any string of 0 or more characters
12557 term   ::= ?               -- matches any character
12558 term   ::= [char @{char@}]   -- matches any character listed
12559 term   ::= [char - char]   -- matches any character in range
12560 @end group
12561 @end smallexample
12562
12563 @item full regular expression
12564 The second set of regular expressions is much more powerful. This is the
12565 type of regular expressions recognized by utilities such a @file{grep}.
12566
12567 The following is the form of a regular expression, expressed in Ada
12568 reference manual style BNF is as follows
12569
12570 @smallexample
12571 @iftex
12572 @leftskip=.5cm
12573 @end iftex
12574 @group
12575 regexp ::= term @{| term@}   -- alternation (term or term @dots{})
12576
12577 term ::= item @{item@}       -- concatenation (item then item)
12578
12579 item ::= elmt              -- match elmt
12580 item ::= elmt *            -- zero or more elmt's
12581 item ::= elmt +            -- one or more elmt's
12582 item ::= elmt ?            -- matches elmt or nothing
12583 @end group
12584 @group
12585 elmt ::= nschar            -- matches given character
12586 elmt ::= [nschar @{nschar@}]   -- matches any character listed
12587 elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed
12588 elmt ::= [char - char]     -- matches chars in given range
12589 elmt ::= \ char            -- matches given character
12590 elmt ::= .                 -- matches any single character
12591 elmt ::= ( regexp )        -- parens used for grouping
12592
12593 char ::= any character, including special characters
12594 nschar ::= any character except ()[].*+?^^^
12595 @end group
12596 @end smallexample
12597
12598 Following are a few examples:
12599
12600 @table @samp
12601 @item abcde|fghi
12602 will match any of the two strings @samp{abcde} and @samp{fghi},
12603
12604 @item abc*d
12605 will match any string like @samp{abd}, @samp{abcd}, @samp{abccd},
12606 @samp{abcccd}, and so on,
12607
12608 @item [a-z]+
12609 will match any string which has only lowercase characters in it (and at
12610 least one character.
12611
12612 @end table
12613 @end table
12614
12615 @node Examples of gnatxref Usage
12616 @section Examples of @code{gnatxref} Usage
12617
12618 @subsection General Usage
12619
12620 @noindent
12621 For the following examples, we will consider the following units:
12622
12623 @smallexample @c ada
12624 @group
12625 @cartouche
12626 main.ads:
12627 1: with Bar;
12628 2: package Main is
12629 3:     procedure Foo (B : in Integer);
12630 4:     C : Integer;
12631 5: private
12632 6:     D : Integer;
12633 7: end Main;
12634
12635 main.adb:
12636 1: package body Main is
12637 2:     procedure Foo (B : in Integer) is
12638 3:     begin
12639 4:        C := B;
12640 5:        D := B;
12641 6:        Bar.Print (B);
12642 7:        Bar.Print (C);
12643 8:     end Foo;
12644 9: end Main;
12645
12646 bar.ads:
12647 1: package Bar is
12648 2:     procedure Print (B : Integer);
12649 3: end bar;
12650 @end cartouche
12651 @end group
12652 @end smallexample
12653
12654 @table @code
12655
12656 @noindent
12657 The first thing to do is to recompile your application (for instance, in
12658 that case just by doing a @samp{gnatmake main}, so that GNAT generates
12659 the cross-referencing information.
12660 You can then issue any of the following commands:
12661
12662 @item gnatxref main.adb
12663 @code{gnatxref} generates cross-reference information for main.adb
12664 and every unit 'with'ed by main.adb.
12665
12666 The output would be:
12667 @smallexample
12668 @iftex
12669 @leftskip=0cm
12670 @end iftex
12671 B                                                      Type: Integer
12672   Decl: bar.ads           2:22
12673 B                                                      Type: Integer
12674   Decl: main.ads          3:20
12675   Body: main.adb          2:20
12676   Ref:  main.adb          4:13     5:13     6:19
12677 Bar                                                    Type: Unit
12678   Decl: bar.ads           1:9
12679   Ref:  main.adb          6:8      7:8
12680        main.ads           1:6
12681 C                                                      Type: Integer
12682   Decl: main.ads          4:5
12683   Modi: main.adb          4:8
12684   Ref:  main.adb          7:19
12685 D                                                      Type: Integer
12686   Decl: main.ads          6:5
12687   Modi: main.adb          5:8
12688 Foo                                                    Type: Unit
12689   Decl: main.ads          3:15
12690   Body: main.adb          2:15
12691 Main                                                    Type: Unit
12692   Decl: main.ads          2:9
12693   Body: main.adb          1:14
12694 Print                                                   Type: Unit
12695   Decl: bar.ads           2:15
12696   Ref:  main.adb          6:12     7:12
12697 @end smallexample
12698
12699 @noindent
12700 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
12701 its body is in main.adb, line 1, column 14 and is not referenced any where.
12702
12703 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
12704 is referenced in main.adb, line 6 column 12 and line 7 column 12.
12705
12706 @item gnatxref package1.adb package2.ads
12707 @code{gnatxref} will generates cross-reference information for
12708 package1.adb, package2.ads and any other package 'with'ed by any
12709 of these.
12710
12711 @end table
12712
12713 @ifclear vms
12714 @subsection Using gnatxref with vi
12715
12716 @code{gnatxref} can generate a tags file output, which can be used
12717 directly from @command{vi}. Note that the standard version of @command{vi}
12718 will not work properly with overloaded symbols. Consider using another
12719 free implementation of @command{vi}, such as @command{vim}.
12720
12721 @smallexample
12722 $ gnatxref -v gnatfind.adb > tags
12723 @end smallexample
12724
12725 @noindent
12726 will generate the tags file for @code{gnatfind} itself (if the sources
12727 are in the search path!).
12728
12729 From @command{vi}, you can then use the command @samp{:tag @var{entity}}
12730 (replacing @var{entity} by whatever you are looking for), and vi will
12731 display a new file with the corresponding declaration of entity.
12732 @end ifclear
12733
12734 @node Examples of gnatfind Usage
12735 @section Examples of @code{gnatfind} Usage
12736
12737 @table @code
12738
12739 @item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb
12740 Find declarations for all entities xyz referenced at least once in
12741 main.adb. The references are search in every library file in the search
12742 path.
12743
12744 The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
12745 switch is set)
12746
12747 The output will look like:
12748 @smallexample
12749 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
12750 ^directory/^[directory]^main.adb:24:10: xyz <= body
12751 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
12752 @end smallexample
12753
12754 @noindent
12755 that is to say, one of the entities xyz found in main.adb is declared at
12756 line 12 of main.ads (and its body is in main.adb), and another one is
12757 declared at line 45 of foo.ads
12758
12759 @item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb
12760 This is the same command as the previous one, instead @code{gnatfind} will
12761 display the content of the Ada source file lines.
12762
12763 The output will look like:
12764
12765 @smallexample
12766 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
12767    procedure xyz;
12768 ^directory/^[directory]^main.adb:24:10: xyz <= body
12769    procedure xyz is
12770 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
12771    xyz : Integer;
12772 @end smallexample
12773
12774 @noindent
12775 This can make it easier to find exactly the location your are looking
12776 for.
12777
12778 @item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb
12779 Find references to all entities containing an x that are
12780 referenced on line 123 of main.ads.
12781 The references will be searched only in main.ads and foo.adb.
12782
12783 @item gnatfind main.ads:123
12784 Find declarations and bodies for all entities that are referenced on
12785 line 123 of main.ads.
12786
12787 This is the same as @code{gnatfind "*":main.adb:123}.
12788
12789 @item gnatfind ^mydir/^[mydir]^main.adb:123:45
12790 Find the declaration for the entity referenced at column 45 in
12791 line 123 of file main.adb in directory mydir. Note that it
12792 is usual to omit the identifier name when the column is given,
12793 since the column position identifies a unique reference.
12794
12795 The column has to be the beginning of the identifier, and should not
12796 point to any character in the middle of the identifier.
12797
12798 @end table
12799
12800 @c *********************************
12801 @node The GNAT Pretty-Printer gnatpp
12802 @chapter The GNAT Pretty-Printer @command{gnatpp}
12803 @findex gnatpp
12804 @cindex Pretty-Printer
12805
12806 @noindent
12807 ^The @command{gnatpp} tool^GNAT PRETTY^ is an ASIS-based utility
12808 for source reformatting / pretty-printing.
12809 It takes an Ada source file as input and generates a reformatted
12810 version as output.
12811 You can specify various style directives via switches; e.g.,
12812 identifier case conventions, rules of indentation, and comment layout.
12813
12814 To produce a reformatted file, @command{gnatpp} generates and uses the ASIS
12815 tree for the input source and thus requires the input to be syntactically and
12816 semantically legal.
12817 If this condition is not met, @command{gnatpp} will terminate with an
12818 error message; no output file will be generated.
12819
12820 If the source files presented to @command{gnatpp} contain
12821 preprocessing directives, then the output file will
12822 correspond to the generated source after all
12823 preprocessing is carried out. There is no way
12824 using @command{gnatpp} to obtain pretty printed files that
12825 include the preprocessing directives.
12826
12827 If the compilation unit
12828 contained in the input source depends semantically upon units located
12829 outside the current directory, you have to provide the source search path
12830 when invoking @command{gnatpp}, if these units are contained in files with
12831 names that do not follow the GNAT file naming rules, you have to provide
12832 the configuration file describing the corresponding naming scheme;
12833 see the description of the @command{gnatpp}
12834 switches below. Another possibility is to use a project file and to
12835 call @command{gnatpp} through the @command{gnat} driver
12836 (see @ref{The GNAT Driver and Project Files}).
12837
12838 The @command{gnatpp} command has the form
12839
12840 @smallexample
12841 @c $ gnatpp @ovar{switches} @var{filename}
12842 @c Expanding @ovar macro inline (explanation in macro def comments)
12843 $ gnatpp @r{[}@var{switches}@r{]} @var{filename} @r{[}-cargs @var{gcc_switches}@r{]}
12844 @end smallexample
12845
12846 @noindent
12847 where
12848 @itemize @bullet
12849 @item
12850 @var{switches} is an optional sequence of switches defining such properties as
12851 the formatting rules, the source search path, and the destination for the
12852 output source file
12853
12854 @item
12855 @var{filename} is the name (including the extension) of the source file to
12856 reformat; ``wildcards'' or several file names on the same gnatpp command are
12857 allowed.  The file name may contain path information; it does not have to
12858 follow the GNAT file naming rules
12859
12860 @item
12861 @samp{@var{gcc_switches}} is a list of switches for
12862 @command{gcc}. They will be passed on to all compiler invocations made by
12863 @command{gnatelim} to generate the ASIS trees. Here you can provide
12864 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
12865 use the @option{-gnatec} switch to set the configuration file,
12866 use the @option{-gnat05} switch if sources should be compiled in
12867 Ada 2005 mode  etc.
12868 @end itemize
12869
12870 @menu
12871 * Switches for gnatpp::
12872 * Formatting Rules::
12873 @end menu
12874
12875 @node Switches for gnatpp
12876 @section Switches for @command{gnatpp}
12877
12878 @noindent
12879 The following subsections describe the various switches accepted by
12880 @command{gnatpp}, organized by category.
12881
12882 @ifclear vms
12883 You specify a switch by supplying a name and generally also a value.
12884 In many cases the values for a switch with a given name are incompatible with
12885 each other
12886 (for example the switch that controls the casing of a reserved word may have
12887 exactly one value: upper case, lower case, or
12888 mixed case) and thus exactly one such switch can be in effect for an
12889 invocation of @command{gnatpp}.
12890 If more than one is supplied, the last one is used.
12891 However, some values for the same switch are mutually compatible.
12892 You may supply several such switches to @command{gnatpp}, but then
12893 each must be specified in full, with both the name and the value.
12894 Abbreviated forms (the name appearing once, followed by each value) are
12895 not permitted.
12896 For example, to set
12897 the alignment of the assignment delimiter both in declarations and in
12898 assignment statements, you must write @option{-A2A3}
12899 (or @option{-A2 -A3}), but not @option{-A23}.
12900 @end ifclear
12901
12902 @ifset vms
12903 In many cases the set of options for a given qualifier are incompatible with
12904 each other (for example the qualifier that controls the casing of a reserved
12905 word may have exactly one option, which specifies either upper case, lower
12906 case, or mixed case), and thus exactly one such option can be in effect for
12907 an invocation of @command{gnatpp}.
12908 If more than one is supplied, the last one is used.
12909 However, some qualifiers have options that are mutually compatible,
12910 and then you may then supply several such options when invoking
12911 @command{gnatpp}.
12912 @end ifset
12913
12914 In most cases, it is obvious whether or not the
12915 ^values for a switch with a given name^options for a given qualifier^
12916 are compatible with each other.
12917 When the semantics might not be evident, the summaries below explicitly
12918 indicate the effect.
12919
12920 @menu
12921 * Alignment Control::
12922 * Casing Control::
12923 * Construct Layout Control::
12924 * General Text Layout Control::
12925 * Other Formatting Options::
12926 * Setting the Source Search Path::
12927 * Output File Control::
12928 * Other gnatpp Switches::
12929 @end menu
12930
12931 @node Alignment Control
12932 @subsection Alignment Control
12933 @cindex Alignment control in @command{gnatpp}
12934
12935 @noindent
12936 Programs can be easier to read if certain constructs are vertically aligned.
12937 By default all alignments are set ON.
12938 Through the @option{^-A0^/ALIGN=OFF^} switch you may reset the default to
12939 OFF, and then use one or more of the other
12940 ^@option{-A@var{n}} switches^@option{/ALIGN} options^
12941 to activate alignment for specific constructs.
12942
12943 @table @option
12944 @cindex @option{^-A@var{n}^/ALIGN^} (@command{gnatpp})
12945
12946 @ifset vms
12947 @item /ALIGN=ON
12948 Set all alignments to ON
12949 @end ifset
12950
12951 @item ^-A0^/ALIGN=OFF^
12952 Set all alignments to OFF
12953
12954 @item ^-A1^/ALIGN=COLONS^
12955 Align @code{:} in declarations
12956
12957 @item ^-A2^/ALIGN=DECLARATIONS^
12958 Align @code{:=} in initializations in declarations
12959
12960 @item ^-A3^/ALIGN=STATEMENTS^
12961 Align @code{:=} in assignment statements
12962
12963 @item ^-A4^/ALIGN=ARROWS^
12964 Align @code{=>} in associations
12965
12966 @item ^-A5^/ALIGN=COMPONENT_CLAUSES^
12967 Align @code{at} keywords in the component clauses in record
12968 representation clauses
12969 @end table
12970
12971 @noindent
12972 The @option{^-A^/ALIGN^} switches are mutually compatible; any combination
12973 is allowed.
12974
12975 @node Casing Control
12976 @subsection Casing Control
12977 @cindex Casing control in @command{gnatpp}
12978
12979 @noindent
12980 @command{gnatpp} allows you to specify the casing for reserved words,
12981 pragma names, attribute designators and identifiers.
12982 For identifiers you may define a
12983 general rule for name casing but also override this rule
12984 via a set of dictionary files.
12985
12986 Three types of casing are supported: lower case, upper case, and mixed case.
12987 Lower and upper case are self-explanatory (but since some letters in
12988 Latin1 and other GNAT-supported character sets
12989 exist only in lower-case form, an upper case conversion will have no
12990 effect on them.)
12991 ``Mixed case'' means that the first letter, and also each letter immediately
12992 following an underscore, are converted to their uppercase forms;
12993 all the other letters are converted to their lowercase forms.
12994
12995 @table @option
12996 @cindex @option{^-a@var{x}^/ATTRIBUTE^} (@command{gnatpp})
12997 @item ^-aL^/ATTRIBUTE_CASING=LOWER_CASE^
12998 Attribute designators are lower case
12999
13000 @item ^-aU^/ATTRIBUTE_CASING=UPPER_CASE^
13001 Attribute designators are upper case
13002
13003 @item ^-aM^/ATTRIBUTE_CASING=MIXED_CASE^
13004 Attribute designators are mixed case (this is the default)
13005
13006 @cindex @option{^-k@var{x}^/KEYWORD_CASING^} (@command{gnatpp})
13007 @item ^-kL^/KEYWORD_CASING=LOWER_CASE^
13008 Keywords (technically, these are known in Ada as @emph{reserved words}) are
13009 lower case (this is the default)
13010
13011 @item ^-kU^/KEYWORD_CASING=UPPER_CASE^
13012 Keywords are upper case
13013
13014 @cindex @option{^-n@var{x}^/NAME_CASING^} (@command{gnatpp})
13015 @item ^-nD^/NAME_CASING=AS_DECLARED^
13016 Name casing for defining occurrences are as they appear in the source file
13017 (this is the default)
13018
13019 @item ^-nU^/NAME_CASING=UPPER_CASE^
13020 Names are in upper case
13021
13022 @item ^-nL^/NAME_CASING=LOWER_CASE^
13023 Names are in lower case
13024
13025 @item ^-nM^/NAME_CASING=MIXED_CASE^
13026 Names are in mixed case
13027
13028 @cindex @option{^-ne@var{x}^/ENUM_CASING^} (@command{gnatpp})
13029 @item ^-neD^/ENUM_CASING=AS_DECLARED^
13030 Enumeration literal casing for defining occurrences are as they appear in the
13031 source file. Overrides ^-n^/NAME_CASING^ casing setting.
13032
13033 @item ^-neU^/ENUM_CASING=UPPER_CASE^
13034 Enumeration literals are in upper case.  Overrides ^-n^/NAME_CASING^ casing
13035 setting.
13036
13037 @item ^-neL^/ENUM_CASING=LOWER_CASE^
13038 Enumeration literals are in lower case. Overrides ^-n^/NAME_CASING^ casing
13039 setting.
13040
13041 @item ^-neM^/ENUM_CASING=MIXED_CASE^
13042 Enumeration literals are in mixed case. Overrides ^-n^/NAME_CASING^ casing
13043 setting.
13044
13045 @cindex @option{^-p@var{x}^/PRAGMA_CASING^} (@command{gnatpp})
13046 @item ^-pL^/PRAGMA_CASING=LOWER_CASE^
13047 Pragma names are lower case
13048
13049 @item ^-pU^/PRAGMA_CASING=UPPER_CASE^
13050 Pragma names are upper case
13051
13052 @item ^-pM^/PRAGMA_CASING=MIXED_CASE^
13053 Pragma names are mixed case (this is the default)
13054
13055 @item ^-D@var{file}^/DICTIONARY=@var{file}^
13056 @cindex @option{^-D^/DICTIONARY^} (@command{gnatpp})
13057 Use @var{file} as a @emph{dictionary file} that defines
13058 the casing for a set of specified names,
13059 thereby overriding the effect on these names by
13060 any explicit or implicit
13061 ^-n^/NAME_CASING^ switch.
13062 To supply more than one dictionary file,
13063 use ^several @option{-D} switches^a list of files as options^.
13064
13065 @noindent
13066 @option{gnatpp} implicitly uses a @emph{default dictionary file}
13067 to define the casing for the Ada predefined names and
13068 the names declared in the GNAT libraries.
13069
13070 @item ^-D-^/SPECIFIC_CASING^
13071 @cindex @option{^-D-^/SPECIFIC_CASING^} (@command{gnatpp})
13072 Do not use the default dictionary file;
13073 instead, use the casing
13074 defined by a @option{^-n^/NAME_CASING^} switch and any explicit
13075 dictionary file(s)
13076 @end table
13077
13078 @noindent
13079 The structure of a dictionary file, and details on the conventions
13080 used in the default dictionary file, are defined in @ref{Name Casing}.
13081
13082 The @option{^-D-^/SPECIFIC_CASING^} and
13083 @option{^-D@var{file}^/DICTIONARY=@var{file}^} switches are mutually
13084 compatible.
13085
13086 @node Construct Layout Control
13087 @subsection Construct Layout Control
13088 @cindex Layout control in @command{gnatpp}
13089
13090 @noindent
13091 This group of @command{gnatpp} switches controls the layout of comments and
13092 complex syntactic constructs.  See @ref{Formatting Comments} for details
13093 on their effect.
13094
13095 @table @option
13096 @cindex @option{^-c@var{n}^/COMMENTS_LAYOUT^} (@command{gnatpp})
13097 @item ^-c0^/COMMENTS_LAYOUT=UNTOUCHED^
13098 All the comments remain unchanged
13099
13100 @item ^-c1^/COMMENTS_LAYOUT=DEFAULT^
13101 GNAT-style comment line indentation (this is the default).
13102
13103 @item ^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^
13104 Reference-manual comment line indentation.
13105
13106 @item ^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^
13107 GNAT-style comment beginning
13108
13109 @item ^-c4^/COMMENTS_LAYOUT=REFORMAT^
13110 Reformat comment blocks
13111
13112 @item ^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^
13113 Keep unchanged special form comments
13114
13115 @cindex @option{^-l@var{n}^/CONSTRUCT_LAYOUT^} (@command{gnatpp})
13116 @item ^-l1^/CONSTRUCT_LAYOUT=GNAT^
13117 GNAT-style layout (this is the default)
13118
13119 @item ^-l2^/CONSTRUCT_LAYOUT=COMPACT^
13120 Compact layout
13121
13122 @item ^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^
13123 Uncompact layout
13124
13125 @cindex @option{^-N^/NOTABS^} (@command{gnatpp})
13126 @item ^-N^/NOTABS^
13127 All the VT characters are removed from the comment text. All the HT characters
13128 are expanded with the sequences of space characters to get to the next tab
13129 stops.
13130
13131 @cindex @option{^--no-separate-is^/NO_SEPARATE_IS^} (@command{gnatpp})
13132 @item ^--no-separate-is^/NO_SEPARATE_IS^
13133 Do not place the keyword @code{is} on a separate line in a subprogram body in
13134 case if the spec occupies more then one line.
13135
13136 @cindex @option{^--separate-label^/SEPARATE_LABEL^} (@command{gnatpp})
13137 @item ^--separate-label^/SEPARATE_LABEL^
13138 Place statement label(s) on a separate line, with the following statement
13139 on the next line.
13140
13141 @cindex @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} (@command{gnatpp})
13142 @item ^--separate-loop-then^/SEPARATE_LOOP_THEN^
13143 Place the keyword @code{loop} in FOR and WHILE loop statements and the
13144 keyword @code{then} in IF statements on a separate line.
13145
13146 @cindex @option{^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^} (@command{gnatpp})
13147 @item ^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^
13148 Do not place the keyword @code{loop} in FOR and WHILE loop statements and the
13149 keyword @code{then} in IF statements on a separate line. This option is
13150 incompatible with @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} option.
13151
13152 @cindex @option{^--use-on-new-line^/USE_ON_NEW_LINE^} (@command{gnatpp})
13153 @item ^--use-on-new-line^/USE_ON_NEW_LINE^
13154 Start each USE clause in a context clause from a separate line.
13155
13156 @cindex @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^} (@command{gnatpp})
13157 @item ^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^
13158 Use a separate line for a loop or block statement name, but do not use an extra
13159 indentation level for the statement itself.
13160
13161 @end table
13162
13163 @ifclear vms
13164 @noindent
13165 The @option{-c1} and @option{-c2} switches are incompatible.
13166 The @option{-c3} and @option{-c4} switches are compatible with each other and
13167 also with @option{-c1} and @option{-c2}. The @option{-c0} switch disables all
13168 the other comment formatting switches.
13169
13170 The @option{-l1}, @option{-l2}, and @option{-l3} switches are incompatible.
13171 @end ifclear
13172
13173 @ifset vms
13174 @noindent
13175 For the @option{/COMMENTS_LAYOUT} qualifier:
13176 @itemize @bullet
13177 @item
13178 The @option{DEFAULT} and @option{STANDARD_INDENT} options are incompatible.
13179 @item
13180 The @option{GNAT_BEGINNING} and @option{REFORMAT} options are compatible with
13181 each other and also with @option{DEFAULT} and @option{STANDARD_INDENT}.
13182 @end itemize
13183
13184 @noindent
13185 The @option{GNAT}, @option{COMPACT}, and @option{UNCOMPACT} options for the
13186 @option{/CONSTRUCT_LAYOUT} qualifier are incompatible.
13187 @end ifset
13188
13189 @node General Text Layout Control
13190 @subsection General Text Layout Control
13191
13192 @noindent
13193 These switches allow control over line length and indentation.
13194
13195 @table @option
13196 @item ^-M@var{nnn}^/LINE_LENGTH_MAX=@var{nnn}^
13197 @cindex @option{^-M^/LINE_LENGTH^} (@command{gnatpp})
13198 Maximum line length, @var{nnn} from 32@dots{}256, the default value is 79
13199
13200 @item ^-i@var{nnn}^/INDENTATION_LEVEL=@var{nnn}^
13201 @cindex @option{^-i^/INDENTATION_LEVEL^} (@command{gnatpp})
13202 Indentation level, @var{nnn} from 1@dots{}9, the default value is 3
13203
13204 @item ^-cl@var{nnn}^/CONTINUATION_INDENT=@var{nnn}^
13205 @cindex @option{^-cl^/CONTINUATION_INDENT^} (@command{gnatpp})
13206 Indentation level for continuation lines (relative to the line being
13207 continued), @var{nnn} from 1@dots{}9.
13208 The default
13209 value is one less then the (normal) indentation level, unless the
13210 indentation is set to 1 (in which case the default value for continuation
13211 line indentation is also 1)
13212 @end table
13213
13214 @node Other Formatting Options
13215 @subsection Other Formatting Options
13216
13217 @noindent
13218 These switches control the inclusion of missing end/exit labels, and
13219 the indentation level in @b{case} statements.
13220
13221 @table @option
13222 @item ^-e^/NO_MISSED_LABELS^
13223 @cindex @option{^-e^/NO_MISSED_LABELS^} (@command{gnatpp})
13224 Do not insert missing end/exit labels. An end label is the name of
13225 a construct that may optionally be repeated at the end of the
13226 construct's declaration;
13227 e.g., the names of packages, subprograms, and tasks.
13228 An exit label is the name of a loop that may appear as target
13229 of an exit statement within the loop.
13230 By default, @command{gnatpp} inserts these end/exit labels when
13231 they are absent from the original source. This option suppresses such
13232 insertion, so that the formatted source reflects the original.
13233
13234 @item ^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^
13235 @cindex @option{^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^} (@command{gnatpp})
13236 Insert a Form Feed character after a pragma Page.
13237
13238 @item ^-T@var{nnn}^/MAX_INDENT=@var{nnn}^
13239 @cindex @option{^-T^/MAX_INDENT^} (@command{gnatpp})
13240 Do not use an additional indentation level for @b{case} alternatives
13241 and variants if there are @var{nnn} or more (the default
13242 value is 10).
13243 If @var{nnn} is 0, an additional indentation level is
13244 used for @b{case} alternatives and variants regardless of their number.
13245 @end table
13246
13247 @node Setting the Source Search Path
13248 @subsection Setting the Source Search Path
13249
13250 @noindent
13251 To define the search path for the input source file, @command{gnatpp}
13252 uses the same switches as the GNAT compiler, with the same effects.
13253
13254 @table @option
13255 @item ^-I^/SEARCH=^@var{dir}
13256 @cindex @option{^-I^/SEARCH^} (@code{gnatpp})
13257 The same as the corresponding gcc switch
13258
13259 @item ^-I-^/NOCURRENT_DIRECTORY^
13260 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatpp})
13261 The same as the corresponding gcc switch
13262
13263 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE^=@var{path}
13264 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@code{gnatpp})
13265 The same as the corresponding gcc switch
13266
13267 @item ^--RTS^/RUNTIME_SYSTEM^=@var{path}
13268 @cindex @option{^--RTS^/RUNTIME_SYSTEM^} (@code{gnatpp})
13269 The same as the corresponding gcc switch
13270
13271 @end table
13272
13273 @node Output File Control
13274 @subsection Output File Control
13275
13276 @noindent
13277 By default the output is sent to the file whose name is obtained by appending
13278 the ^@file{.pp}^@file{$PP}^ suffix to the name of the input file
13279 (if the file with this name already exists, it is unconditionally overwritten).
13280 Thus if the input file is @file{^my_ada_proc.adb^MY_ADA_PROC.ADB^} then
13281 @command{gnatpp} will produce @file{^my_ada_proc.adb.pp^MY_ADA_PROC.ADB$PP^}
13282 as output file.
13283 The output may be redirected by the following switches:
13284
13285 @table @option
13286 @item ^-pipe^/STANDARD_OUTPUT^
13287 @cindex @option{^-pipe^/STANDARD_OUTPUT^} (@code{gnatpp})
13288 Send the output to @code{Standard_Output}
13289
13290 @item ^-o @var{output_file}^/OUTPUT=@var{output_file}^
13291 @cindex @option{^-o^/OUTPUT^} (@code{gnatpp})
13292 Write the output into @var{output_file}.
13293 If @var{output_file} already exists, @command{gnatpp} terminates without
13294 reading or processing the input file.
13295
13296 @item ^-of ^/FORCED_OUTPUT=^@var{output_file}
13297 @cindex @option{^-of^/FORCED_OUTPUT^} (@code{gnatpp})
13298 Write the output into @var{output_file}, overwriting the existing file
13299 (if one is present).
13300
13301 @item ^-r^/REPLACE^
13302 @cindex @option{^-r^/REPLACE^} (@code{gnatpp})
13303 Replace the input source file with the reformatted output, and copy the
13304 original input source into the file whose name is obtained by appending the
13305 ^@file{.npp}^@file{$NPP}^ suffix to the name of the input file.
13306 If a file with this name already exists, @command{gnatpp} terminates without
13307 reading or processing the input file.
13308
13309 @item ^-rf^/OVERRIDING_REPLACE^
13310 @cindex @option{^-rf^/OVERRIDING_REPLACE^} (@code{gnatpp})
13311 Like @option{^-r^/REPLACE^} except that if the file with the specified name
13312 already exists, it is overwritten.
13313
13314 @item ^-rnb^/REPLACE_NO_BACKUP^
13315 @cindex @option{^-rnb^/REPLACE_NO_BACKUP^} (@code{gnatpp})
13316 Replace the input source file with the reformatted output without
13317 creating any backup copy of the input source.
13318
13319 @item ^--eol=@var{xxx}^/END_OF_LINE=@var{xxx}^
13320 @cindex @option{^--eol^/END_OF_LINE^} (@code{gnatpp})
13321 Specifies the format of the reformatted output file. The @var{xxx}
13322 ^string specified with the switch^option^ may be either
13323 @itemize @bullet
13324 @item ``@option{^dos^DOS^}'' MS DOS style, lines end with CR LF characters
13325 @item ``@option{^crlf^CRLF^}''
13326 the same as @option{^crlf^CRLF^}
13327 @item ``@option{^unix^UNIX^}'' UNIX style, lines end with LF character
13328 @item ``@option{^lf^LF^}''
13329 the same as @option{^unix^UNIX^}
13330 @end itemize
13331
13332 @item ^-W^/RESULT_ENCODING=^@var{e}
13333 @cindex @option{^-W^/RESULT_ENCODING=^} (@command{gnatpp})
13334 Specify the wide character encoding method used to write the code in the
13335 result file
13336 @var{e} is one of the following:
13337
13338 @itemize @bullet
13339
13340 @item ^h^HEX^
13341 Hex encoding
13342
13343 @item ^u^UPPER^
13344 Upper half encoding
13345
13346 @item ^s^SHIFT_JIS^
13347 Shift/JIS encoding
13348
13349 @item ^e^EUC^
13350 EUC encoding
13351
13352 @item ^8^UTF8^
13353 UTF-8 encoding
13354
13355 @item ^b^BRACKETS^
13356 Brackets encoding (default value)
13357 @end itemize
13358
13359 @end table
13360
13361 @noindent
13362 Options @option{^-pipe^/STANDARD_OUTPUT^},
13363 @option{^-o^/OUTPUT^} and
13364 @option{^-of^/FORCED_OUTPUT^} are allowed only if the call to gnatpp
13365 contains only one file to reformat.
13366 Option
13367 @option{^--eol^/END_OF_LINE^}
13368 and
13369 @option{^-W^/RESULT_ENCODING^}
13370 cannot be used together
13371 with @option{^-pipe^/STANDARD_OUTPUT^} option.
13372
13373 @node Other gnatpp Switches
13374 @subsection Other @code{gnatpp} Switches
13375
13376 @noindent
13377 The additional @command{gnatpp} switches are defined in this subsection.
13378
13379 @table @option
13380 @item ^-files @var{filename}^/FILES=@var{filename}^
13381 @cindex @option{^-files^/FILES^} (@code{gnatpp})
13382 Take the argument source files from the specified file. This file should be an
13383 ordinary text file containing file names separated by spaces or
13384 line breaks. You can use this switch more than once in the same call to
13385 @command{gnatpp}. You also can combine this switch with an explicit list of
13386 files.
13387
13388 @item ^-v^/VERBOSE^
13389 @cindex @option{^-v^/VERBOSE^} (@code{gnatpp})
13390 Verbose mode;
13391 @command{gnatpp} generates version information and then
13392 a trace of the actions it takes to produce or obtain the ASIS tree.
13393
13394 @item ^-w^/WARNINGS^
13395 @cindex @option{^-w^/WARNINGS^} (@code{gnatpp})
13396 Warning mode;
13397 @command{gnatpp} generates a warning whenever it cannot provide
13398 a required layout in the result source.
13399 @end table
13400
13401 @node Formatting Rules
13402 @section Formatting Rules
13403
13404 @noindent
13405 The following subsections show how @command{gnatpp} treats ``white space'',
13406 comments, program layout, and name casing.
13407 They provide the detailed descriptions of the switches shown above.
13408
13409 @menu
13410 * White Space and Empty Lines::
13411 * Formatting Comments::
13412 * Construct Layout::
13413 * Name Casing::
13414 @end menu
13415
13416 @node White Space and Empty Lines
13417 @subsection White Space and Empty Lines
13418
13419 @noindent
13420 @command{gnatpp} does not have an option to control space characters.
13421 It will add or remove spaces according to the style illustrated by the
13422 examples in the @cite{Ada Reference Manual}.
13423
13424 The only format effectors
13425 (see @cite{Ada Reference Manual}, paragraph 2.1(13))
13426 that will appear in the output file are platform-specific line breaks,
13427 and also format effectors within (but not at the end of) comments.
13428 In particular, each horizontal tab character that is not inside
13429 a comment will be treated as a space and thus will appear in the
13430 output file as zero or more spaces depending on
13431 the reformatting of the line in which it appears.
13432 The only exception is a Form Feed character, which is inserted after a
13433 pragma @code{Page} when @option{-ff} is set.
13434
13435 The output file will contain no lines with trailing ``white space'' (spaces,
13436 format effectors).
13437
13438 Empty lines in the original source are preserved
13439 only if they separate declarations or statements.
13440 In such contexts, a
13441 sequence of two or more empty lines is replaced by exactly one empty line.
13442 Note that a blank line will be removed if it separates two ``comment blocks''
13443 (a comment block is a sequence of whole-line comments).
13444 In order to preserve a visual separation between comment blocks, use an
13445 ``empty comment'' (a line comprising only hyphens) rather than an empty line.
13446 Likewise, if for some reason you wish to have a sequence of empty lines,
13447 use a sequence of empty comments instead.
13448
13449 @node Formatting Comments
13450 @subsection Formatting Comments
13451
13452 @noindent
13453 Comments in Ada code are of two kinds:
13454 @itemize @bullet
13455 @item
13456 a @emph{whole-line comment}, which appears by itself (possibly preceded by
13457 ``white space'') on a line
13458
13459 @item
13460 an @emph{end-of-line comment}, which follows some other Ada lexical element
13461 on the same line.
13462 @end itemize
13463
13464 @noindent
13465 The indentation of a whole-line comment is that of either
13466 the preceding or following line in
13467 the formatted source, depending on switch settings as will be described below.
13468
13469 For an end-of-line comment, @command{gnatpp} leaves the same number of spaces
13470 between the end of the preceding Ada lexical element and the beginning
13471 of the comment as appear in the original source,
13472 unless either the comment has to be split to
13473 satisfy the line length limitation, or else the next line contains a
13474 whole line comment that is considered a continuation of this end-of-line
13475 comment (because it starts at the same position).
13476 In the latter two
13477 cases, the start of the end-of-line comment is moved right to the nearest
13478 multiple of the indentation level.
13479 This may result in a ``line overflow'' (the right-shifted comment extending
13480 beyond the maximum line length), in which case the comment is split as
13481 described below.
13482
13483 There is a difference between @option{^-c1^/COMMENTS_LAYOUT=DEFAULT^}
13484 (GNAT-style comment line indentation)
13485 and @option{^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^}
13486 (reference-manual comment line indentation).
13487 With reference-manual style, a whole-line comment is indented as if it
13488 were a declaration or statement at the same place
13489 (i.e., according to the indentation of the preceding line(s)).
13490 With GNAT style, a whole-line comment that is immediately followed by an
13491 @b{if} or @b{case} statement alternative, a record variant, or the reserved
13492 word @b{begin}, is indented based on the construct that follows it.
13493
13494 For example:
13495 @smallexample @c ada
13496 @cartouche
13497 if A then
13498     null;
13499        -- some comment
13500 else
13501    null;
13502 end if;
13503 @end cartouche
13504 @end smallexample
13505
13506 @noindent
13507 Reference-manual indentation produces:
13508
13509 @smallexample @c ada
13510 @cartouche
13511 if A then
13512    null;
13513    --  some comment
13514 else
13515    null;
13516 end if;
13517 @end cartouche
13518 @end smallexample
13519
13520 @noindent
13521 while GNAT-style indentation produces:
13522
13523 @smallexample @c ada
13524 @cartouche
13525 if A then
13526    null;
13527 --  some comment
13528 else
13529    null;
13530 end if;
13531 @end cartouche
13532 @end smallexample
13533
13534 @noindent
13535 The @option{^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^} switch
13536 (GNAT style comment beginning) has the following
13537 effect:
13538
13539 @itemize @bullet
13540 @item
13541 For each whole-line comment that does not end with two hyphens,
13542 @command{gnatpp} inserts spaces if necessary after the starting two hyphens
13543 to ensure that there are at least two spaces between these hyphens and the
13544 first non-blank character of the comment.
13545 @end itemize
13546
13547 @noindent
13548 For an end-of-line comment, if in the original source the next line is a
13549 whole-line comment that starts at the same position
13550 as the end-of-line comment,
13551 then the whole-line comment (and all whole-line comments
13552 that follow it and that start at the same position)
13553 will start at this position in the output file.
13554
13555 @noindent
13556 That is, if in the original source we have:
13557
13558 @smallexample @c ada
13559 @cartouche
13560 begin
13561 A := B + C;            --  B must be in the range Low1..High1
13562                        --  C must be in the range Low2..High2
13563              --B+C will be in the range Low1+Low2..High1+High2
13564 X := X + 1;
13565 @end cartouche
13566 @end smallexample
13567
13568 @noindent
13569 Then in the formatted source we get
13570
13571 @smallexample @c ada
13572 @cartouche
13573 begin
13574    A := B + C;            --  B must be in the range Low1..High1
13575                           --  C must be in the range Low2..High2
13576    --  B+C will be in the range Low1+Low2..High1+High2
13577    X := X + 1;
13578 @end cartouche
13579 @end smallexample
13580
13581 @noindent
13582 A comment that exceeds the line length limit will be split.
13583 Unless switch
13584 @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} (reformat comment blocks) is set and
13585 the line belongs to a reformattable block, splitting the line generates a
13586 @command{gnatpp} warning.
13587 The @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} switch specifies that whole-line
13588 comments may be reformatted in typical
13589 word processor style (that is, moving words between lines and putting as
13590 many words in a line as possible).
13591
13592 @noindent
13593 The @option{^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^} switch specifies, that comments
13594 that has a special format (that is, a character that is neither a letter nor digit
13595 not white space nor line break immediately following the leading @code{--} of
13596 the comment) should be without any change moved from the argument source
13597 into reformatted source. This switch allows to preserve comments that are used
13598 as a special marks in the code (e.g.@: SPARK annotation).
13599
13600 @node Construct Layout
13601 @subsection Construct Layout
13602
13603 @noindent
13604 In several cases the suggested layout in the Ada Reference Manual includes
13605 an extra level of indentation that many programmers prefer to avoid. The
13606 affected cases include:
13607
13608 @itemize @bullet
13609
13610 @item Record type declaration (RM 3.8)
13611
13612 @item Record representation clause (RM 13.5.1)
13613
13614 @item Loop statement in case if a loop has a statement identifier (RM 5.6)
13615
13616 @item Block statement in case if a block has a statement identifier (RM 5.6)
13617 @end itemize
13618
13619 @noindent
13620 In compact mode (when GNAT style layout or compact layout is set),
13621 the pretty printer uses one level of indentation instead
13622 of two. This is achieved in the record definition and record representation
13623 clause cases by putting the @code{record} keyword on the same line as the
13624 start of the declaration or representation clause, and in the block and loop
13625 case by putting the block or loop header on the same line as the statement
13626 identifier.
13627
13628 @noindent
13629 The difference between GNAT style @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^}
13630 and compact @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^}
13631 layout on the one hand, and uncompact layout
13632 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} on the other hand,
13633 can be illustrated by the following examples:
13634
13635 @iftex
13636 @cartouche
13637 @multitable @columnfractions .5 .5
13638 @item @i{GNAT style, compact layout} @tab @i{Uncompact layout}
13639
13640 @item
13641 @smallexample @c ada
13642 type q is record
13643    a : integer;
13644    b : integer;
13645 end record;
13646 @end smallexample
13647 @tab
13648 @smallexample @c ada
13649 type q is
13650    record
13651       a : integer;
13652       b : integer;
13653    end record;
13654 @end smallexample
13655
13656 @item
13657 @smallexample @c ada
13658 for q use record
13659    a at 0 range  0 .. 31;
13660    b at 4 range  0 .. 31;
13661 end record;
13662 @end smallexample
13663 @tab
13664 @smallexample @c ada
13665 for q use
13666    record
13667       a at 0 range  0 .. 31;
13668       b at 4 range  0 .. 31;
13669    end record;
13670 @end smallexample
13671
13672 @item
13673 @smallexample @c ada
13674 Block : declare
13675    A : Integer := 3;
13676 begin
13677    Proc (A, A);
13678 end Block;
13679 @end smallexample
13680 @tab
13681 @smallexample @c ada
13682 Block :
13683    declare
13684       A : Integer := 3;
13685    begin
13686       Proc (A, A);
13687    end Block;
13688 @end smallexample
13689
13690 @item
13691 @smallexample @c ada
13692 Clear : for J in 1 .. 10 loop
13693    A (J) := 0;
13694 end loop Clear;
13695 @end smallexample
13696 @tab
13697 @smallexample @c ada
13698 Clear :
13699    for J in 1 .. 10 loop
13700       A (J) := 0;
13701    end loop Clear;
13702 @end smallexample
13703 @end multitable
13704 @end cartouche
13705 @end iftex
13706
13707 @ifnottex
13708 @smallexample
13709 @cartouche
13710 GNAT style, compact layout              Uncompact layout
13711
13712 type q is record                        type q is
13713    a : integer;                            record
13714    b : integer;                               a : integer;
13715 end record;                                   b : integer;
13716                                            end record;
13717
13718 for q use record                        for q use
13719    a at 0 range  0 .. 31;                  record
13720    b at 4 range  0 .. 31;                     a at 0 range  0 .. 31;
13721 end record;                                   b at 4 range  0 .. 31;
13722                                            end record;
13723
13724 Block : declare                         Block :
13725    A : Integer := 3;                       declare
13726 begin                                         A : Integer := 3;
13727    Proc (A, A);                            begin
13728 end Block;                                    Proc (A, A);
13729                                            end Block;
13730
13731 Clear : for J in 1 .. 10 loop           Clear :
13732    A (J) := 0;                             for J in 1 .. 10 loop
13733 end loop Clear;                               A (J) := 0;
13734                                            end loop Clear;
13735 @end cartouche
13736 @end smallexample
13737 @end ifnottex
13738
13739 @noindent
13740 A further difference between GNAT style layout and compact layout is that
13741 GNAT style layout inserts empty lines as separation for
13742 compound statements, return statements and bodies.
13743
13744 Note that the layout specified by
13745 @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^}
13746 for named block and loop statements overrides the layout defined by these
13747 constructs by @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^},
13748 @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^} or
13749 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} option.
13750
13751 @node Name Casing
13752 @subsection Name Casing
13753
13754 @noindent
13755 @command{gnatpp} always converts the usage occurrence of a (simple) name to
13756 the same casing as the corresponding defining identifier.
13757
13758 You control the casing for defining occurrences via the
13759 @option{^-n^/NAME_CASING^} switch.
13760 @ifclear vms
13761 With @option{-nD} (``as declared'', which is the default),
13762 @end ifclear
13763 @ifset vms
13764 With @option{/NAME_CASING=AS_DECLARED}, which is the default,
13765 @end ifset
13766 defining occurrences appear exactly as in the source file
13767 where they are declared.
13768 The other ^values for this switch^options for this qualifier^ ---
13769 @option{^-nU^UPPER_CASE^},
13770 @option{^-nL^LOWER_CASE^},
13771 @option{^-nM^MIXED_CASE^} ---
13772 result in
13773 ^upper, lower, or mixed case, respectively^the corresponding casing^.
13774 If @command{gnatpp} changes the casing of a defining
13775 occurrence, it analogously changes the casing of all the
13776 usage occurrences of this name.
13777
13778 If the defining occurrence of a name is not in the source compilation unit
13779 currently being processed by @command{gnatpp}, the casing of each reference to
13780 this name is changed according to the value of the @option{^-n^/NAME_CASING^}
13781 switch (subject to the dictionary file mechanism described below).
13782 Thus @command{gnatpp} acts as though the @option{^-n^/NAME_CASING^} switch
13783 had affected the
13784 casing for the defining occurrence of the name.
13785
13786 Some names may need to be spelled with casing conventions that are not
13787 covered by the upper-, lower-, and mixed-case transformations.
13788 You can arrange correct casing by placing such names in a
13789 @emph{dictionary file},
13790 and then supplying a @option{^-D^/DICTIONARY^} switch.
13791 The casing of names from dictionary files overrides
13792 any @option{^-n^/NAME_CASING^} switch.
13793
13794 To handle the casing of Ada predefined names and the names from GNAT libraries,
13795 @command{gnatpp} assumes a default dictionary file.
13796 The name of each predefined entity is spelled with the same casing as is used
13797 for the entity in the @cite{Ada Reference Manual}.
13798 The name of each entity in the GNAT libraries is spelled with the same casing
13799 as is used in the declaration of that entity.
13800
13801 The @w{@option{^-D-^/SPECIFIC_CASING^}} switch suppresses the use of the
13802 default dictionary file.
13803 Instead, the casing for predefined and GNAT-defined names will be established
13804 by the @option{^-n^/NAME_CASING^} switch or explicit dictionary files.
13805 For example, by default the names @code{Ada.Text_IO} and @code{GNAT.OS_Lib}
13806 will appear as just shown,
13807 even in the presence of a @option{^-nU^/NAME_CASING=UPPER_CASE^} switch.
13808 To ensure that even such names are rendered in uppercase,
13809 additionally supply the @w{@option{^-D-^/SPECIFIC_CASING^}} switch
13810 (or else, less conveniently, place these names in upper case in a dictionary
13811 file).
13812
13813 A dictionary file is
13814 a plain text file; each line in this file can be either a blank line
13815 (containing only space characters and ASCII.HT characters), an Ada comment
13816 line, or the specification of exactly one @emph{casing schema}.
13817
13818 A casing schema is a string that has the following syntax:
13819
13820 @smallexample
13821 @cartouche
13822   @var{casing_schema} ::= @var{identifier} | *@var{simple_identifier}*
13823
13824   @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
13825 @end cartouche
13826 @end smallexample
13827
13828 @noindent
13829 (See @cite{Ada Reference Manual}, Section 2.3) for the definition of the
13830 @var{identifier} lexical element and the @var{letter_or_digit} category.)
13831
13832 The casing schema string can be followed by white space and/or an Ada-style
13833 comment; any amount of white space is allowed before the string.
13834
13835 If a dictionary file is passed as
13836 @ifclear vms
13837 the value of a @option{-D@var{file}} switch
13838 @end ifclear
13839 @ifset vms
13840 an option to the @option{/DICTIONARY} qualifier
13841 @end ifset
13842 then for every
13843 simple name and every identifier, @command{gnatpp} checks if the dictionary
13844 defines the casing for the name or for some of its parts (the term ``subword''
13845 is used below to denote the part of a name which is delimited by ``_'' or by
13846 the beginning or end of the word and which does not contain any ``_'' inside):
13847
13848 @itemize @bullet
13849 @item
13850 if the whole name is in the dictionary, @command{gnatpp} uses for this name
13851 the casing defined by the dictionary; no subwords are checked for this word
13852
13853 @item
13854 for every subword @command{gnatpp} checks if the dictionary contains the
13855 corresponding string of the form @code{*@var{simple_identifier}*},
13856 and if it does, the casing of this @var{simple_identifier} is used
13857 for this subword
13858
13859 @item
13860 if the whole name does not contain any ``_'' inside, and if for this name
13861 the dictionary contains two entries - one of the form @var{identifier},
13862 and another - of the form *@var{simple_identifier}*, then the first one
13863 is applied to define the casing of this name
13864
13865 @item
13866 if more than one dictionary file is passed as @command{gnatpp} switches, each
13867 dictionary adds new casing exceptions and overrides all the existing casing
13868 exceptions set by the previous dictionaries
13869
13870 @item
13871 when @command{gnatpp} checks if the word or subword is in the dictionary,
13872 this check is not case sensitive
13873 @end itemize
13874
13875 @noindent
13876 For example, suppose we have the following source to reformat:
13877
13878 @smallexample @c ada
13879 @cartouche
13880 procedure test is
13881    name1 : integer := 1;
13882    name4_name3_name2 : integer := 2;
13883    name2_name3_name4 : Boolean;
13884    name1_var : Float;
13885 begin
13886    name2_name3_name4 := name4_name3_name2 > name1;
13887 end;
13888 @end cartouche
13889 @end smallexample
13890
13891 @noindent
13892 And suppose we have two dictionaries:
13893
13894 @smallexample
13895 @cartouche
13896 @i{dict1:}
13897    NAME1
13898    *NaMe3*
13899    *Name1*
13900 @end cartouche
13901
13902 @cartouche
13903 @i{dict2:}
13904   *NAME3*
13905 @end cartouche
13906 @end smallexample
13907
13908 @noindent
13909 If @command{gnatpp} is called with the following switches:
13910
13911 @smallexample
13912 @ifclear vms
13913 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
13914 @end ifclear
13915 @ifset vms
13916 @command{gnatpp test.adb /NAME_CASING=MIXED_CASE /DICTIONARY=(dict1, dict2)}
13917 @end ifset
13918 @end smallexample
13919
13920 @noindent
13921 then we will get the following name casing in the @command{gnatpp} output:
13922
13923 @smallexample @c ada
13924 @cartouche
13925 procedure Test is
13926    NAME1             : Integer := 1;
13927    Name4_NAME3_Name2 : Integer := 2;
13928    Name2_NAME3_Name4 : Boolean;
13929    Name1_Var         : Float;
13930 begin
13931    Name2_NAME3_Name4 := Name4_NAME3_Name2 > NAME1;
13932 end Test;
13933 @end cartouche
13934 @end smallexample
13935
13936 @c *********************************
13937 @node The GNAT Metric Tool gnatmetric
13938 @chapter The GNAT Metric Tool @command{gnatmetric}
13939 @findex gnatmetric
13940 @cindex Metric tool
13941
13942 @noindent
13943 ^The @command{gnatmetric} tool^@command{GNAT METRIC}^ is an ASIS-based utility
13944 for computing various program metrics.
13945 It takes an Ada source file as input and generates a file containing the
13946 metrics data as output. Various switches control which
13947 metrics are computed and output.
13948
13949 @command{gnatmetric} generates and uses the ASIS
13950 tree for the input source and thus requires the input to be syntactically and
13951 semantically legal.
13952 If this condition is not met, @command{gnatmetric} will generate
13953 an error message; no metric information for this file will be
13954 computed and reported.
13955
13956 If the compilation unit contained in the input source depends semantically
13957 upon units in files located outside the current directory, you have to provide
13958 the source search path when invoking @command{gnatmetric}.
13959 If it depends semantically upon units that are contained
13960 in files with names that do not follow the GNAT file naming rules, you have to
13961 provide the configuration file describing the corresponding naming scheme (see
13962 the description of the @command{gnatmetric} switches below.)
13963 Alternatively, you may use a project file and invoke @command{gnatmetric}
13964 through the @command{gnat} driver (see @ref{The GNAT Driver and Project Files}).
13965
13966 The @command{gnatmetric} command has the form
13967
13968 @smallexample
13969 @c $ gnatmetric @ovar{switches} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
13970 @c Expanding @ovar macro inline (explanation in macro def comments)
13971 $ gnatmetric @r{[}@var{switches}@r{]} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
13972 @end smallexample
13973
13974 @noindent
13975 where
13976 @itemize @bullet
13977 @item
13978 @var{switches} specify the metrics to compute and define the destination for
13979 the output
13980
13981 @item
13982 Each @var{filename} is the name (including the extension) of a source
13983 file to process. ``Wildcards'' are allowed, and
13984 the file name may contain path information.
13985 If no @var{filename} is supplied, then the @var{switches} list must contain
13986 at least one
13987 @option{-files} switch (@pxref{Other gnatmetric Switches}).
13988 Including both a @option{-files} switch and one or more
13989 @var{filename} arguments is permitted.
13990
13991 @item
13992 @samp{@var{gcc_switches}} is a list of switches for
13993 @command{gcc}. They will be passed on to all compiler invocations made by
13994 @command{gnatmetric} to generate the ASIS trees. Here you can provide
13995 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
13996 and use the @option{-gnatec} switch to set the configuration file,
13997 use the @option{-gnat05} switch if sources should be compiled in
13998 Ada 2005 mode etc.
13999 @end itemize
14000
14001 @menu
14002 * Switches for gnatmetric::
14003 @end menu
14004
14005 @node Switches for gnatmetric
14006 @section Switches for @command{gnatmetric}
14007
14008 @noindent
14009 The following subsections describe the various switches accepted by
14010 @command{gnatmetric}, organized by category.
14011
14012 @menu
14013 * Output Files Control::
14014 * Disable Metrics For Local Units::
14015 * Specifying a set of metrics to compute::
14016 * Other gnatmetric Switches::
14017 * Generate project-wide metrics::
14018 @end menu
14019
14020 @node Output Files Control
14021 @subsection Output File Control
14022 @cindex Output file control in @command{gnatmetric}
14023
14024 @noindent
14025 @command{gnatmetric} has two output formats. It can generate a
14026 textual (human-readable) form, and also XML. By default only textual
14027 output is generated.
14028
14029 When generating the output in textual form, @command{gnatmetric} creates
14030 for each Ada source file a corresponding text file
14031 containing the computed metrics, except for the case when the set of metrics
14032 specified by gnatmetric parameters consists only of metrics that are computed
14033 for the whole set of analyzed sources, but not for each Ada source.
14034 By default, this file is placed in the same directory as where the source
14035 file is located, and its name is obtained
14036 by appending the ^@file{.metrix}^@file{$METRIX}^ suffix to the name of the
14037 input file.
14038
14039 All the output information generated in XML format is placed in a single
14040 file. By default this file is placed in the current directory and has the
14041 name ^@file{metrix.xml}^@file{METRIX$XML}^.
14042
14043 Some of the computed metrics are summed over the units passed to
14044 @command{gnatmetric}; for example, the total number of lines of code.
14045 By default this information is sent to @file{stdout}, but a file
14046 can be specified with the @option{-og} switch.
14047
14048 The following switches control the @command{gnatmetric} output:
14049
14050 @table @option
14051 @cindex @option{^-x^/XML^} (@command{gnatmetric})
14052 @item ^-x^/XML^
14053 Generate the XML output
14054
14055 @cindex @option{^-xs^/XSD^} (@command{gnatmetric})
14056 @item ^-xs^/XSD^
14057 Generate the XML output and the XML schema file that describes the structure
14058 of the XML metric report, this schema is assigned to the XML file. The schema
14059 file has the same name as the XML output file with @file{.xml} suffix replaced
14060 with @file{.xsd}
14061
14062 @cindex @option{^-nt^/NO_TEXT^} (@command{gnatmetric})
14063 @item ^-nt^/NO_TEXT^
14064 Do not generate the output in text form (implies @option{^-x^/XML^})
14065
14066 @cindex @option{^-d^/DIRECTORY^} (@command{gnatmetric})
14067 @item ^-d @var{output_dir}^/DIRECTORY=@var{output_dir}^
14068 Put text files with detailed metrics into @var{output_dir}
14069
14070 @cindex @option{^-o^/SUFFIX_DETAILS^} (@command{gnatmetric})
14071 @item ^-o @var{file_suffix}^/SUFFIX_DETAILS=@var{file_suffix}^
14072 Use @var{file_suffix}, instead of ^@file{.metrix}^@file{$METRIX}^
14073 in the name of the output file.
14074
14075 @cindex @option{^-og^/GLOBAL_OUTPUT^} (@command{gnatmetric})
14076 @item ^-og @var{file_name}^/GLOBAL_OUTPUT=@var{file_name}^
14077 Put global metrics into @var{file_name}
14078
14079 @cindex @option{^-ox^/XML_OUTPUT^} (@command{gnatmetric})
14080 @item ^-ox @var{file_name}^/XML_OUTPUT=@var{file_name}^
14081 Put the XML output into @var{file_name} (also implies @option{^-x^/XML^})
14082
14083 @cindex @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} (@command{gnatmetric})
14084 @item ^-sfn^/SHORT_SOURCE_FILE_NAME^
14085 Use ``short'' source file names in the output.  (The @command{gnatmetric}
14086 output includes the name(s) of the Ada source file(s) from which the metrics
14087 are computed.  By default each name includes the absolute path. The
14088 @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} switch causes @command{gnatmetric}
14089 to exclude all directory information from the file names that are output.)
14090
14091 @end table
14092
14093 @node Disable Metrics For Local Units
14094 @subsection Disable Metrics For Local Units
14095 @cindex Disable Metrics For Local Units in @command{gnatmetric}
14096
14097 @noindent
14098 @command{gnatmetric} relies on the GNAT compilation model @minus{}
14099 one compilation
14100 unit per one source file. It computes line metrics for the whole source
14101 file, and it also computes syntax
14102 and complexity metrics for the file's outermost unit.
14103
14104 By default, @command{gnatmetric} will also compute all metrics for certain
14105 kinds of locally declared program units:
14106
14107 @itemize @bullet
14108 @item
14109 subprogram (and generic subprogram) bodies;
14110
14111 @item
14112 package (and generic package) specs and bodies;
14113
14114 @item
14115 task object and type specifications and bodies;
14116
14117 @item
14118 protected object and type specifications and bodies.
14119 @end itemize
14120
14121 @noindent
14122 These kinds of entities will be referred to as
14123 @emph{eligible local program units}, or simply @emph{eligible local units},
14124 @cindex Eligible local unit (for @command{gnatmetric})
14125 in the discussion below.
14126
14127 Note that a subprogram declaration, generic instantiation,
14128 or renaming declaration only receives metrics
14129 computation when it appear as the outermost entity
14130 in a source file.
14131
14132 Suppression of metrics computation for eligible local units can be
14133 obtained via the following switch:
14134
14135 @table @option
14136 @cindex @option{^-n@var{x}^/SUPPRESS^} (@command{gnatmetric})
14137 @item ^-nolocal^/SUPPRESS=LOCAL_DETAILS^
14138 Do not compute detailed metrics for eligible local program units
14139
14140 @end table
14141
14142 @node Specifying a set of metrics to compute
14143 @subsection Specifying a set of metrics to compute
14144
14145 @noindent
14146 By default all the metrics are computed and reported. The switches
14147 described in this subsection allow you to control, on an individual
14148 basis, whether metrics are computed and
14149 reported. If at least one positive metric
14150 switch is specified (that is, a switch that defines that a given
14151 metric or set of metrics is to be computed), then only
14152 explicitly specified metrics are reported.
14153
14154 @menu
14155 * Line Metrics Control::
14156 * Syntax Metrics Control::
14157 * Complexity Metrics Control::
14158 * Coupling Metrics Control::
14159 @end menu
14160
14161 @node Line Metrics Control
14162 @subsubsection Line Metrics Control
14163 @cindex Line metrics control in @command{gnatmetric}
14164
14165 @noindent
14166 For any (legal) source file, and for each of its
14167 eligible local program units, @command{gnatmetric} computes the following
14168 metrics:
14169
14170 @itemize @bullet
14171 @item
14172 the total number of lines;
14173
14174 @item
14175 the total number of code lines (i.e., non-blank lines that are not comments)
14176
14177 @item
14178 the number of comment lines
14179
14180 @item
14181 the number of code lines containing end-of-line comments;
14182
14183 @item
14184 the comment percentage: the ratio between the number of lines that contain
14185 comments and the number of all non-blank lines, expressed as a percentage;
14186
14187 @item
14188 the number of empty lines and lines containing only space characters and/or
14189 format effectors (blank lines)
14190
14191 @item
14192 the average number of code lines in subprogram bodies, task bodies, entry
14193 bodies and statement sequences in package bodies (this metric is only computed
14194 across the whole set of the analyzed units)
14195
14196 @end itemize
14197
14198 @noindent
14199 @command{gnatmetric} sums the values of the line metrics for all the
14200 files being processed and then generates the cumulative results. The tool
14201 also computes for all the files being processed the average number of code
14202 lines in bodies.
14203
14204 You can use the following switches to select the specific line metrics
14205 to be computed and reported.
14206
14207 @table @option
14208 @cindex @option{^--lines@var{x}^/LINE_COUNT_METRICS^} (@command{gnatmetric})
14209
14210 @ifclear vms
14211 @cindex @option{--no-lines@var{x}}
14212 @end ifclear
14213
14214 @item ^--lines-all^/LINE_COUNT_METRICS=ALL^
14215 Report all the line metrics
14216
14217 @item ^--no-lines-all^/LINE_COUNT_METRICS=NONE^
14218 Do not report any of line metrics
14219
14220 @item ^--lines^/LINE_COUNT_METRICS=ALL_LINES^
14221 Report the number of all lines
14222
14223 @item ^--no-lines^/LINE_COUNT_METRICS=NOALL_LINES^
14224 Do not report the number of all lines
14225
14226 @item ^--lines-code^/LINE_COUNT_METRICS=CODE_LINES^
14227 Report the number of code lines
14228
14229 @item ^--no-lines-code^/LINE_COUNT_METRICS=NOCODE_LINES^
14230 Do not report the number of code lines
14231
14232 @item ^--lines-comment^/LINE_COUNT_METRICS=COMMENT_LINES^
14233 Report the number of comment lines
14234
14235 @item ^--no-lines-comment^/LINE_COUNT_METRICS=NOCOMMENT_LINES^
14236 Do not report the number of comment lines
14237
14238 @item ^--lines-eol-comment^/LINE_COUNT_METRICS=CODE_COMMENT_LINES^
14239 Report the number of code lines containing
14240 end-of-line comments
14241
14242 @item ^--no-lines-eol-comment^/LINE_COUNT_METRICS=NOCODE_COMMENT_LINES^
14243 Do not report the number of code lines containing
14244 end-of-line comments
14245
14246 @item ^--lines-ratio^/LINE_COUNT_METRICS=COMMENT_PERCENTAGE^
14247 Report the comment percentage in the program text
14248
14249 @item ^--no-lines-ratio^/LINE_COUNT_METRICS=NOCOMMENT_PERCENTAGE^
14250 Do not report the comment percentage in the program text
14251
14252 @item ^--lines-blank^/LINE_COUNT_METRICS=BLANK_LINES^
14253 Report the number of blank lines
14254
14255 @item ^--no-lines-blank^/LINE_COUNT_METRICS=NOBLANK_LINES^
14256 Do not report the number of blank lines
14257
14258 @item ^--lines-average^/LINE_COUNT_METRICS=AVERAGE_BODY_LINES^
14259 Report the average number of code lines in subprogram bodies, task bodies,
14260 entry bodies and statement sequences in package bodies. The metric is computed
14261 and reported for the whole set of processed Ada sources only.
14262
14263 @item ^--no-lines-average^/LINE_COUNT_METRICS=NOAVERAGE_BODY_LINES^
14264 Do not report the average number of code lines in subprogram bodies,
14265 task bodies, entry bodies and statement sequences in package bodies.
14266
14267 @end table
14268
14269 @node Syntax Metrics Control
14270 @subsubsection Syntax Metrics Control
14271 @cindex Syntax metrics control in @command{gnatmetric}
14272
14273 @noindent
14274 @command{gnatmetric} computes various syntactic metrics for the
14275 outermost unit and for each eligible local unit:
14276
14277 @table @emph
14278 @item LSLOC (``Logical Source Lines Of Code'')
14279 The total number of declarations and the total number of statements. Note
14280 that the definition of declarations is the one given in the reference
14281 manual:
14282
14283 @noindent
14284 ``Each of the following is defined to be a declaration: any basic_declaration;
14285 an enumeration_literal_specification; a discriminant_specification;
14286 a component_declaration; a loop_parameter_specification; a
14287 parameter_specification; a subprogram_body; an entry_declaration;
14288 an entry_index_specification; a choice_parameter_specification;
14289 a generic_formal_parameter_declaration.''
14290
14291 This means for example that each enumeration literal adds one to the count,
14292 as well as each subprogram parameter.
14293
14294 Thus the results from this metric will be significantly greater than might
14295 be expected from a naive view of counting semicolons.
14296
14297 @item Maximal static nesting level of inner program units
14298 According to
14299 @cite{Ada Reference Manual}, 10.1(1), ``A program unit is either a
14300 package, a task unit, a protected unit, a
14301 protected entry, a generic unit, or an explicitly declared subprogram other
14302 than an enumeration literal.''
14303
14304 @item Maximal nesting level of composite syntactic constructs
14305 This corresponds to the notion of the
14306 maximum nesting level in the GNAT built-in style checks
14307 (@pxref{Style Checking})
14308 @end table
14309
14310 @noindent
14311 For the outermost unit in the file, @command{gnatmetric} additionally computes
14312 the following metrics:
14313
14314 @table @emph
14315 @item Public subprograms
14316 This metric is computed for package specs. It is the
14317 number of subprograms and generic subprograms declared in the visible
14318 part (including the visible part of nested packages, protected objects, and
14319 protected types).
14320
14321 @item All subprograms
14322 This metric is computed for bodies and subunits. The
14323 metric is equal to a total number of subprogram bodies in the compilation
14324 unit.
14325 Neither generic instantiations nor renamings-as-a-body nor body stubs
14326 are counted. Any subprogram body is counted, independently of its nesting
14327 level and enclosing constructs. Generic bodies and bodies of protected
14328 subprograms are counted in the same way as ``usual'' subprogram bodies.
14329
14330 @item Public types
14331 This metric is computed for package specs and
14332 generic package declarations. It is the total number of types
14333 that can be referenced from outside this compilation unit, plus the
14334 number of types from all the visible parts of all the visible generic
14335 packages. Generic formal types are not counted.  Only types, not subtypes,
14336 are included.
14337
14338 @noindent
14339 Along with the total number of public types, the following
14340 types are counted and reported separately:
14341
14342 @itemize @bullet
14343 @item
14344 Abstract types
14345
14346 @item
14347 Root tagged types (abstract, non-abstract, private, non-private). Type
14348 extensions are @emph{not} counted
14349
14350 @item
14351 Private types (including private extensions)
14352
14353 @item
14354 Task types
14355
14356 @item
14357 Protected types
14358
14359 @end itemize
14360
14361 @item All types
14362 This metric is computed for any compilation unit. It is equal to the total
14363 number of the declarations of different types given in the compilation unit.
14364 The private and the corresponding full type declaration are counted as one
14365 type declaration. Incomplete type declarations and generic formal types
14366 are not counted.
14367 No distinction is made among different kinds of types (abstract,
14368 private etc.); the total number of types is computed and reported.
14369
14370 @end table
14371
14372 @noindent
14373 By default, all the syntax metrics are computed and reported. You can use the
14374 following switches to select specific syntax metrics.
14375
14376 @table @option
14377
14378 @cindex @option{^--syntax@var{x}^/SYNTAX_METRICS^} (@command{gnatmetric})
14379
14380 @ifclear vms
14381 @cindex @option{--no-syntax@var{x}} (@command{gnatmetric})
14382 @end ifclear
14383
14384 @item ^--syntax-all^/SYNTAX_METRICS=ALL^
14385 Report all the syntax metrics
14386
14387 @item ^--no-syntax-all^/SYNTAX_METRICS=NONE^
14388 Do not report any of syntax metrics
14389
14390 @item ^--declarations^/SYNTAX_METRICS=DECLARATIONS^
14391 Report the total number of declarations
14392
14393 @item ^--no-declarations^/SYNTAX_METRICS=NODECLARATIONS^
14394 Do not report the total number of declarations
14395
14396 @item ^--statements^/SYNTAX_METRICS=STATEMENTS^
14397 Report the total number of statements
14398
14399 @item ^--no-statements^/SYNTAX_METRICS=NOSTATEMENTS^
14400 Do not report the total number of statements
14401
14402 @item ^--public-subprograms^/SYNTAX_METRICS=PUBLIC_SUBPROGRAMS^
14403 Report the number of public subprograms in a compilation unit
14404
14405 @item ^--no-public-subprograms^/SYNTAX_METRICS=NOPUBLIC_SUBPROGRAMS^
14406 Do not report the number of public subprograms in a compilation unit
14407
14408 @item ^--all-subprograms^/SYNTAX_METRICS=ALL_SUBPROGRAMS^
14409 Report the number of all the subprograms in a compilation unit
14410
14411 @item ^--no-all-subprograms^/SYNTAX_METRICS=NOALL_SUBPROGRAMS^
14412 Do not report the number of all the subprograms in a compilation unit
14413
14414 @item ^--public-types^/SYNTAX_METRICS=PUBLIC_TYPES^
14415 Report the number of public types in a compilation unit
14416
14417 @item ^--no-public-types^/SYNTAX_METRICS=NOPUBLIC_TYPES^
14418 Do not report the number of public types in a compilation unit
14419
14420 @item ^--all-types^/SYNTAX_METRICS=ALL_TYPES^
14421 Report the number of all the types in a compilation unit
14422
14423 @item ^--no-all-types^/SYNTAX_METRICS=NOALL_TYPES^
14424 Do not report the number of all the types in a compilation unit
14425
14426 @item ^--unit-nesting^/SYNTAX_METRICS=UNIT_NESTING^
14427 Report the maximal program unit nesting level
14428
14429 @item ^--no-unit-nesting^/SYNTAX_METRICS=UNIT_NESTING_OFF^
14430 Do not report the maximal program unit nesting level
14431
14432 @item ^--construct-nesting^/SYNTAX_METRICS=CONSTRUCT_NESTING^
14433 Report the maximal construct nesting level
14434
14435 @item ^--no-construct-nesting^/SYNTAX_METRICS=NOCONSTRUCT_NESTING^
14436 Do not report the maximal construct nesting level
14437
14438 @end table
14439
14440 @node Complexity Metrics Control
14441 @subsubsection Complexity Metrics Control
14442 @cindex Complexity metrics control in @command{gnatmetric}
14443
14444 @noindent
14445 For a program unit that is an executable body (a subprogram body (including
14446 generic bodies), task body, entry body or a package body containing
14447 its own statement sequence) @command{gnatmetric} computes the following
14448 complexity metrics:
14449
14450 @itemize @bullet
14451 @item
14452 McCabe cyclomatic complexity;
14453
14454 @item
14455 McCabe essential complexity;
14456
14457 @item
14458 maximal loop nesting level;
14459
14460 @item
14461 extra exit points (for subprograms);
14462 @end itemize
14463
14464 @noindent
14465 The McCabe cyclomatic complexity metric is defined
14466 in @url{http://www.mccabe.com/pdf/mccabe-nist235r.pdf}
14467
14468 According to McCabe, both control statements and short-circuit control forms
14469 should be taken into account when computing cyclomatic complexity. For each
14470 body, we compute three metric values:
14471
14472 @itemize @bullet
14473 @item
14474 the complexity introduced by control
14475 statements only, without taking into account short-circuit forms,
14476
14477 @item
14478 the complexity introduced by short-circuit control forms only, and
14479
14480 @item
14481 the total
14482 cyclomatic complexity, which is the sum of these two values.
14483 @end itemize
14484
14485 @noindent
14486
14487 The origin of cyclomatic complexity metric is the need to estimate the number
14488 of independent paths in the control flow graph that in turn gives the number
14489 of tests needed to satisfy paths coverage testing completeness criterion.
14490 Considered from the testing point of view, a static Ada @code{loop} (that is,
14491 the @code{loop} statement having static subtype in loop parameter
14492 specification) does not add to cyclomatic complexity. By providing
14493 @option{^--no-static-loop^NO_STATIC_LOOP^} option a user
14494 may specify that such loops should not be counted when computing the
14495 cyclomatic complexity metric
14496
14497 The Ada essential complexity metric is a McCabe cyclomatic complexity metric
14498 counted for the code that is reduced by excluding all the pure structural Ada
14499 control statements. An compound statement is considered as a non-structural
14500 if it contains a @code{raise} or @code{return} statement as it subcomponent,
14501 or if it contains a @code{goto} statement that transfers the control outside
14502 the operator. A selective accept statement with @code{terminate} alternative
14503 is considered as non-structural statement. When computing this metric,
14504 @code{exit} statements are treated in the same way as @code{goto}
14505 statements unless @option{^-ne^NO_EXITS_AS_GOTOS^} option is specified.
14506
14507 The Ada essential complexity metric defined here is intended to quantify
14508 the extent to which the software is unstructured. It is adapted from
14509 the McCabe essential complexity metric defined in
14510 http://www.mccabe.com/pdf/nist235r.pdf but is modified to be more
14511 suitable for typical Ada usage. For example, short circuit forms
14512 are not penalized as unstructured in the Ada essential complexity metric.
14513
14514 When computing cyclomatic and essential complexity, @command{gnatmetric} skips
14515 the code in the exception handlers and in all the nested program units.
14516
14517 By default, all the complexity metrics are computed and reported.
14518 For more fine-grained control you can use
14519 the following switches:
14520
14521 @table @option
14522 @cindex @option{^-complexity@var{x}^/COMPLEXITY_METRICS^} (@command{gnatmetric})
14523
14524 @ifclear vms
14525 @cindex @option{--no-complexity@var{x}}
14526 @end ifclear
14527
14528 @item ^--complexity-all^/COMPLEXITY_METRICS=ALL^
14529 Report all the complexity metrics
14530
14531 @item ^--no-complexity-all^/COMPLEXITY_METRICS=NONE^
14532 Do not report any of complexity metrics
14533
14534 @item ^--complexity-cyclomatic^/COMPLEXITY_METRICS=CYCLOMATIC^
14535 Report the McCabe Cyclomatic Complexity
14536
14537 @item ^--no-complexity-cyclomatic^/COMPLEXITY_METRICS=NOCYCLOMATIC^
14538 Do not report the McCabe Cyclomatic Complexity
14539
14540 @item ^--complexity-essential^/COMPLEXITY_METRICS=ESSENTIAL^
14541 Report the Essential Complexity
14542
14543 @item ^--no-complexity-essential^/COMPLEXITY_METRICS=NOESSENTIAL^
14544 Do not report the Essential Complexity
14545
14546 @item ^--loop-nesting^/COMPLEXITY_METRICS=LOOP_NESTING_ON^
14547 Report maximal loop nesting level
14548
14549 @item ^--no-loop-nesting^/COMPLEXITY_METRICS=NOLOOP_NESTING^
14550 Do not report maximal loop nesting level
14551
14552 @item ^--complexity-average^/COMPLEXITY_METRICS=AVERAGE_COMPLEXITY^
14553 Report the average McCabe Cyclomatic Complexity for all the subprogram bodies,
14554 task bodies, entry bodies and statement sequences in package bodies.
14555 The metric is computed and reported for whole set of processed Ada sources
14556 only.
14557
14558 @item ^--no-complexity-average^/COMPLEXITY_METRICS=NOAVERAGE_COMPLEXITY^
14559 Do not report the average McCabe Cyclomatic Complexity for all the subprogram
14560 bodies, task bodies, entry bodies and statement sequences in package bodies
14561
14562 @cindex @option{^-ne^/NO_EXITS_AS_GOTOS^} (@command{gnatmetric})
14563 @item ^-ne^/NO_EXITS_AS_GOTOS^
14564 Do not consider @code{exit} statements as @code{goto}s when
14565 computing Essential Complexity
14566
14567 @cindex @option{^--no-static-loop^/NO_STATIC_LOOP^} (@command{gnatmetric})
14568 @item ^--no-static-loop^/NO_STATIC_LOOP^
14569 Do not consider static loops when computing cyclomatic complexity
14570
14571 @item ^--extra-exit-points^/EXTRA_EXIT_POINTS^
14572 Report the extra exit points for subprogram bodies. As an exit point, this
14573 metric counts @code{return} statements and raise statements in case when the
14574 raised exception is not handled in the same body. In case of a function this
14575 metric subtracts 1 from the number of exit points, because a function body
14576 must contain at least one @code{return} statement.
14577
14578 @item ^--no-extra-exit-points^/NOEXTRA_EXIT_POINTS^
14579 Do not report the extra exit points for subprogram bodies
14580 @end table
14581
14582
14583 @node Coupling Metrics Control
14584 @subsubsection Coupling Metrics Control
14585 @cindex Coupling metrics control in @command{gnatmetric}
14586
14587 @noindent
14588 @cindex Coupling metrics (in in @command{gnatmetric})
14589 Coupling metrics measure the dependencies between a given entity and other
14590 entities the program consists of. The goal of these metrics is to estimate the
14591 stability of the whole program considered as the collection of entities
14592 (modules, classes etc.).
14593
14594 Gnatmetric computes the following coupling metrics:
14595
14596 @itemize @bullet
14597
14598 @item
14599 @emph{object-oriented coupling} - for classes in traditional object-oriented
14600 sense;
14601
14602 @item
14603 @emph{unit coupling} - for all the program units making up a program;
14604
14605 @item
14606 @emph{control coupling} - this metric counts dependencies between a unit and
14607 only those units that define subprograms;
14608 @end itemize
14609
14610 @noindent
14611 Two kinds of coupling metrics are computed:
14612
14613 @table @asis
14614 @item fan-out coupling (efferent coupling)
14615 @cindex fan-out coupling
14616 @cindex efferent coupling
14617 the number of entities the given entity depends upon. It
14618 estimates in what extent the given entity depends on the changes in
14619 ``external world''
14620
14621 @item fan-in coupling (afferent coupling)
14622 @cindex fan-in coupling
14623 @cindex afferent coupling
14624 the number of entities that depend on a given entity.
14625 It estimates in what extent the ``external world'' depends on the changes in a
14626 given entity
14627 @end table
14628
14629 @noindent
14630
14631 Object-oriented coupling metrics are metrics that measure the dependencies
14632 between a given class (or a group of classes) and the other classes in the
14633 program. In this subsection the term ``class'' is used in its traditional
14634 object-oriented programming sense (an instantiable module that contains data
14635 and/or method members). A @emph{category} (of classes) is a group of closely
14636 related classes that are reused and/or modified together.
14637
14638 A class @code{K}'s fan-out coupling is the number of classes
14639 that @code{K} depends upon.
14640 A category's fan-out coupling is the number of classes outside the
14641 category that the classes inside the category depend upon.
14642
14643 A class @code{K}'s fan-in coupling is the number of classes
14644 that depend upon @code{K}.
14645 A category's fan-in coupling is the number of classes outside the
14646 category that depend on classes belonging to the category.
14647
14648 Ada's implementation of the object-oriented paradigm does not use the
14649 traditional class notion, so the definition of the coupling
14650 metrics for Ada maps the class and class category notions
14651 onto Ada constructs.
14652
14653 For the coupling metrics, several kinds of modules -- a library package,
14654 a library generic package, and a library generic package instantiation --
14655 that define a tagged type or an interface type are
14656 considered to be a class. A category consists of a library package (or
14657 a library generic package) that defines a tagged or an interface type,
14658 together with all its descendant (generic) packages that define tagged
14659 or interface types. That is a
14660 category is an Ada hierarchy of library-level program units. So class coupling
14661 in case of Ada is called as tagged coupling, and category coupling - as
14662 hierarchy coupling.
14663
14664 For any package counted as a class, its body and subunits (if any) are
14665 considered together with its spec when counting the dependencies, and coupling
14666 metrics are reported for spec units only. For dependencies between classes,
14667 the Ada semantic dependencies are considered. For object-oriented coupling
14668 metrics, only dependencies on units that are considered as classes, are
14669 considered.
14670
14671 For unit and control coupling also not compilation units but program units are
14672 counted. That is, for a package, its spec, its body and its subunits (if any)
14673 are considered as making up one unit, and the dependencies that are counted
14674 are the dependencies of all these compilation units collected together as
14675 the dependencies as a (whole) unit. And metrics are reported for spec
14676 compilation units only (or for a subprogram body unit in case if there is no
14677 separate spec for the given subprogram).
14678
14679 For unit coupling, dependencies between all kinds of program units are
14680 considered. For control coupling, for each unit the dependencies of this unit
14681 upon units that define subprograms are counted, so control fan-out coupling
14682 is reported for all units, but control fan-in coupling - only for the units
14683 that define subprograms.
14684
14685
14686
14687
14688
14689
14690 When computing coupling metrics, @command{gnatmetric} counts only
14691 dependencies between units that are arguments of the gnatmetric call.
14692 Coupling metrics are program-wide (or project-wide) metrics, so to
14693 get a valid result, you should call @command{gnatmetric} for
14694 the whole set of sources that make up your program. It can be done
14695 by calling @command{gnatmetric} from the GNAT driver with @option{-U}
14696 option (see @ref{The GNAT Driver and Project Files} for details).
14697
14698 By default, all the coupling metrics are disabled. You can use the following
14699 switches to specify the coupling metrics to be computed and reported:
14700
14701 @table @option
14702
14703 @ifclear vms
14704 @cindex @option{--tagged-coupling@var{x}} (@command{gnatmetric})
14705 @cindex @option{--hierarchy-coupling@var{x}} (@command{gnatmetric})
14706 @cindex @option{--unit-coupling@var{x}} (@command{gnatmetric})
14707 @cindex @option{--control-coupling@var{x}} (@command{gnatmetric})
14708 @end ifclear
14709
14710 @ifset vms
14711 @cindex @option{/COUPLING_METRICS} (@command{gnatmetric})
14712 @end ifset
14713
14714 @item ^--coupling-all^/COUPLING_METRICS=ALL^
14715 Report all the coupling metrics
14716
14717 @item ^--tagged-coupling-out^/COUPLING_METRICS=TAGGED_OUT^
14718 Report tagged (class) fan-out coupling
14719
14720 @item ^--tagged-coupling-in^/COUPLING_METRICS=TAGGED_IN^
14721 Report tagged (class) fan-in coupling
14722
14723 @item ^--hierarchy-coupling-out^/COUPLING_METRICS=HIERARCHY_OUT^
14724 Report hierarchy (category) fan-out coupling
14725
14726 @item ^--hierarchy-coupling-in^/COUPLING_METRICS=HIERARCHY_IN^
14727 Report hierarchy (category) fan-in coupling
14728
14729 @item ^--unit-coupling-out^/COUPLING_METRICS=UNIT_OUT^
14730 Report unit fan-out coupling
14731
14732 @item ^--unit-coupling-in^/COUPLING_METRICS=UNIT_IN^
14733 Report unit fan-in coupling
14734
14735 @item ^--control-coupling-out^/COUPLING_METRICS=CONTROL_OUT^
14736 Report control fan-out coupling
14737
14738 @item ^--control-coupling-in^/COUPLING_METRICS=CONTROL_IN^
14739 Report control fan-in coupling
14740 @end table
14741
14742 @node Other gnatmetric Switches
14743 @subsection Other @code{gnatmetric} Switches
14744
14745 @noindent
14746 Additional @command{gnatmetric} switches are as follows:
14747
14748 @table @option
14749 @item ^-files @var{filename}^/FILES=@var{filename}^
14750 @cindex @option{^-files^/FILES^} (@code{gnatmetric})
14751 Take the argument source files from the specified file. This file should be an
14752 ordinary text file containing file names separated by spaces or
14753 line breaks. You can use this switch more than once in the same call to
14754 @command{gnatmetric}. You also can combine this switch with
14755 an explicit list of files.
14756
14757 @item ^-v^/VERBOSE^
14758 @cindex @option{^-v^/VERBOSE^} (@code{gnatmetric})
14759 Verbose mode;
14760 @command{gnatmetric} generates version information and then
14761 a trace of sources being processed.
14762
14763 @item ^-q^/QUIET^
14764 @cindex @option{^-q^/QUIET^} (@code{gnatmetric})
14765 Quiet mode.
14766 @end table
14767
14768 @node Generate project-wide metrics
14769 @subsection Generate project-wide metrics
14770
14771 In order to compute metrics on all units of a given project, you can use
14772 the @command{gnat} driver along with the @option{-P} option:
14773 @smallexample
14774    gnat metric -Pproj
14775 @end smallexample
14776
14777 @noindent
14778 If the project @code{proj} depends upon other projects, you can compute
14779 the metrics on the project closure using the @option{-U} option:
14780 @smallexample
14781    gnat metric -Pproj -U
14782 @end smallexample
14783
14784 @noindent
14785 Finally, if not all the units are relevant to a particular main
14786 program in the project closure, you can generate metrics for the set
14787 of units needed to create a given main program (unit closure) using
14788 the @option{-U} option followed by the name of the main unit:
14789 @smallexample
14790    gnat metric -Pproj -U main
14791 @end smallexample
14792
14793
14794 @c ***********************************
14795 @node File Name Krunching Using gnatkr
14796 @chapter File Name Krunching Using @code{gnatkr}
14797 @findex gnatkr
14798
14799 @noindent
14800 This chapter discusses the method used by the compiler to shorten
14801 the default file names chosen for Ada units so that they do not
14802 exceed the maximum length permitted. It also describes the
14803 @code{gnatkr} utility that can be used to determine the result of
14804 applying this shortening.
14805 @menu
14806 * About gnatkr::
14807 * Using gnatkr::
14808 * Krunching Method::
14809 * Examples of gnatkr Usage::
14810 @end menu
14811
14812 @node About gnatkr
14813 @section About @code{gnatkr}
14814
14815 @noindent
14816 The default file naming rule in GNAT
14817 is that the file name must be derived from
14818 the unit name. The exact default rule is as follows:
14819 @itemize @bullet
14820 @item
14821 Take the unit name and replace all dots by hyphens.
14822 @item
14823 If such a replacement occurs in the
14824 second character position of a name, and the first character is
14825 ^@samp{a}, @samp{g}, @samp{s}, or @samp{i}, ^@samp{A}, @samp{G}, @samp{S}, or @samp{I},^
14826 then replace the dot by the character
14827 ^@samp{~} (tilde)^@samp{$} (dollar sign)^
14828 instead of a minus.
14829 @end itemize
14830 The reason for this exception is to avoid clashes
14831 with the standard names for children of System, Ada, Interfaces,
14832 and GNAT, which use the prefixes
14833 ^@samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},^@samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},^
14834 respectively.
14835
14836 The @option{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}}
14837 switch of the compiler activates a ``krunching''
14838 circuit that limits file names to nn characters (where nn is a decimal
14839 integer). For example, using OpenVMS,
14840 where the maximum file name length is
14841 39, the value of nn is usually set to 39, but if you want to generate
14842 a set of files that would be usable if ported to a system with some
14843 different maximum file length, then a different value can be specified.
14844 The default value of 39 for OpenVMS need not be specified.
14845
14846 The @code{gnatkr} utility can be used to determine the krunched name for
14847 a given file, when krunched to a specified maximum length.
14848
14849 @node Using gnatkr
14850 @section Using @code{gnatkr}
14851
14852 @noindent
14853 The @code{gnatkr} command has the form
14854
14855 @ifclear vms
14856 @smallexample
14857 @c $ gnatkr @var{name} @ovar{length}
14858 @c Expanding @ovar macro inline (explanation in macro def comments)
14859 $ gnatkr @var{name} @r{[}@var{length}@r{]}
14860 @end smallexample
14861 @end ifclear
14862
14863 @ifset vms
14864 @smallexample
14865 $ gnatkr @var{name} /COUNT=nn
14866 @end smallexample
14867 @end ifset
14868
14869 @noindent
14870 @var{name} is the uncrunched file name, derived from the name of the unit
14871 in the standard manner described in the previous section (i.e., in particular
14872 all dots are replaced by hyphens). The file name may or may not have an
14873 extension (defined as a suffix of the form period followed by arbitrary
14874 characters other than period). If an extension is present then it will
14875 be preserved in the output. For example, when krunching @file{hellofile.ads}
14876 to eight characters, the result will be hellofil.ads.
14877
14878 Note: for compatibility with previous versions of @code{gnatkr} dots may
14879 appear in the name instead of hyphens, but the last dot will always be
14880 taken as the start of an extension. So if @code{gnatkr} is given an argument
14881 such as @file{Hello.World.adb} it will be treated exactly as if the first
14882 period had been a hyphen, and for example krunching to eight characters
14883 gives the result @file{hellworl.adb}.
14884
14885 Note that the result is always all lower case (except on OpenVMS where it is
14886 all upper case). Characters of the other case are folded as required.
14887
14888 @var{length} represents the length of the krunched name. The default
14889 when no argument is given is ^8^39^ characters. A length of zero stands for
14890 unlimited, in other words do not chop except for system files where the
14891 implied crunching length is always eight characters.
14892
14893 @noindent
14894 The output is the krunched name. The output has an extension only if the
14895 original argument was a file name with an extension.
14896
14897 @node Krunching Method
14898 @section Krunching Method
14899
14900 @noindent
14901 The initial file name is determined by the name of the unit that the file
14902 contains. The name is formed by taking the full expanded name of the
14903 unit and replacing the separating dots with hyphens and
14904 using ^lowercase^uppercase^
14905 for all letters, except that a hyphen in the second character position is
14906 replaced by a ^tilde^dollar sign^ if the first character is
14907 ^@samp{a}, @samp{i}, @samp{g}, or @samp{s}^@samp{A}, @samp{I}, @samp{G}, or @samp{S}^.
14908 The extension is @code{.ads} for a
14909 spec and @code{.adb} for a body.
14910 Krunching does not affect the extension, but the file name is shortened to
14911 the specified length by following these rules:
14912
14913 @itemize @bullet
14914 @item
14915 The name is divided into segments separated by hyphens, tildes or
14916 underscores and all hyphens, tildes, and underscores are
14917 eliminated. If this leaves the name short enough, we are done.
14918
14919 @item
14920 If the name is too long, the longest segment is located (left-most
14921 if there are two of equal length), and shortened by dropping
14922 its last character. This is repeated until the name is short enough.
14923
14924 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
14925 to fit the name into 8 characters as required by some operating systems.
14926
14927 @smallexample
14928 our-strings-wide_fixed 22
14929 our strings wide fixed 19
14930 our string  wide fixed 18
14931 our strin   wide fixed 17
14932 our stri    wide fixed 16
14933 our stri    wide fixe  15
14934 our str     wide fixe  14
14935 our str     wid  fixe  13
14936 our str     wid  fix   12
14937 ou  str     wid  fix   11
14938 ou  st      wid  fix   10
14939 ou  st      wi   fix   9
14940 ou  st      wi   fi    8
14941 Final file name: oustwifi.adb
14942 @end smallexample
14943
14944 @item
14945 The file names for all predefined units are always krunched to eight
14946 characters. The krunching of these predefined units uses the following
14947 special prefix replacements:
14948
14949 @table @file
14950 @item ada-
14951 replaced by @file{^a^A^-}
14952
14953 @item gnat-
14954 replaced by @file{^g^G^-}
14955
14956 @item interfaces-
14957 replaced by @file{^i^I^-}
14958
14959 @item system-
14960 replaced by @file{^s^S^-}
14961 @end table
14962
14963 These system files have a hyphen in the second character position. That
14964 is why normal user files replace such a character with a
14965 ^tilde^dollar sign^, to
14966 avoid confusion with system file names.
14967
14968 As an example of this special rule, consider
14969 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
14970
14971 @smallexample
14972 ada-strings-wide_fixed 22
14973 a-  strings wide fixed 18
14974 a-  string  wide fixed 17
14975 a-  strin   wide fixed 16
14976 a-  stri    wide fixed 15
14977 a-  stri    wide fixe  14
14978 a-  str     wide fixe  13
14979 a-  str     wid  fixe  12
14980 a-  str     wid  fix   11
14981 a-  st      wid  fix   10
14982 a-  st      wi   fix   9
14983 a-  st      wi   fi    8
14984 Final file name: a-stwifi.adb
14985 @end smallexample
14986 @end itemize
14987
14988 Of course no file shortening algorithm can guarantee uniqueness over all
14989 possible unit names, and if file name krunching is used then it is your
14990 responsibility to ensure that no name clashes occur. The utility
14991 program @code{gnatkr} is supplied for conveniently determining the
14992 krunched name of a file.
14993
14994 @node Examples of gnatkr Usage
14995 @section Examples of @code{gnatkr} Usage
14996
14997 @smallexample
14998 @iftex
14999 @leftskip=0cm
15000 @end iftex
15001 @ifclear vms
15002 $ gnatkr very_long_unit_name.ads      --> velounna.ads
15003 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
15004 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
15005 $ gnatkr grandparent-parent-child     --> grparchi
15006 @end ifclear
15007 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
15008 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
15009 @end smallexample
15010
15011 @node Preprocessing Using gnatprep
15012 @chapter Preprocessing Using @code{gnatprep}
15013 @findex gnatprep
15014
15015 @noindent
15016 This chapter discusses how to use GNAT's @code{gnatprep} utility for simple
15017 preprocessing.
15018 Although designed for use with GNAT, @code{gnatprep} does not depend on any
15019 special GNAT features.
15020 For further discussion of conditional compilation in general, see
15021 @ref{Conditional Compilation}.
15022
15023 @menu
15024 * Preprocessing Symbols::
15025 * Using gnatprep::
15026 * Switches for gnatprep::
15027 * Form of Definitions File::
15028 * Form of Input Text for gnatprep::
15029 @end menu
15030
15031 @node Preprocessing Symbols
15032 @section Preprocessing Symbols
15033
15034 @noindent
15035 Preprocessing symbols are defined in definition files and referred to in
15036 sources to be preprocessed. A Preprocessing symbol is an identifier, following
15037 normal Ada (case-insensitive) rules for its syntax, with the restriction that
15038 all characters need to be in the ASCII set (no accented letters).
15039
15040 @node Using gnatprep
15041 @section Using @code{gnatprep}
15042
15043 @noindent
15044 To call @code{gnatprep} use
15045
15046 @smallexample
15047 @c $ gnatprep @ovar{switches} @var{infile} @var{outfile} @ovar{deffile}
15048 @c Expanding @ovar macro inline (explanation in macro def comments)
15049 $ gnatprep @r{[}@var{switches}@r{]} @var{infile} @var{outfile} @r{[}@var{deffile}@r{]}
15050 @end smallexample
15051
15052 @noindent
15053 where
15054 @table @var
15055 @item switches
15056 is an optional sequence of switches as described in the next section.
15057
15058 @item infile
15059 is the full name of the input file, which is an Ada source
15060 file containing preprocessor directives.
15061
15062 @item outfile
15063 is the full name of the output file, which is an Ada source
15064 in standard Ada form. When used with GNAT, this file name will
15065 normally have an ads or adb suffix.
15066
15067 @item deffile
15068 is the full name of a text file containing definitions of
15069 preprocessing symbols to be referenced by the preprocessor. This argument is
15070 optional, and can be replaced by the use of the @option{-D} switch.
15071
15072 @end table
15073
15074 @node Switches for gnatprep
15075 @section Switches for @code{gnatprep}
15076
15077 @table @option
15078 @c !sort!
15079
15080 @item ^-b^/BLANK_LINES^
15081 @cindex @option{^-b^/BLANK_LINES^} (@command{gnatprep})
15082 Causes both preprocessor lines and the lines deleted by
15083 preprocessing to be replaced by blank lines in the output source file,
15084 preserving line numbers in the output file.
15085
15086 @item ^-c^/COMMENTS^
15087 @cindex @option{^-c^/COMMENTS^} (@command{gnatprep})
15088 Causes both preprocessor lines and the lines deleted
15089 by preprocessing to be retained in the output source as comments marked
15090 with the special string @code{"--! "}. This option will result in line numbers
15091 being preserved in the output file.
15092
15093 @item ^-C^/REPLACE_IN_COMMENTS^
15094 @cindex @option{^-C^/REPLACE_IN_COMMENTS^} (@command{gnatprep})
15095 Causes comments to be scanned. Normally comments are ignored by gnatprep.
15096 If this option is specified, then comments are scanned and any $symbol
15097 substitutions performed as in program text. This is particularly useful
15098 when structured comments are used (e.g., when writing programs in the
15099 SPARK dialect of Ada). Note that this switch is not available when
15100 doing integrated preprocessing (it would be useless in this context
15101 since comments are ignored by the compiler in any case).
15102
15103 @item ^-Dsymbol=value^/ASSOCIATE="symbol=value"^
15104 @cindex @option{^-D^/ASSOCIATE^} (@command{gnatprep})
15105 Defines a new preprocessing symbol, associated with value. If no value is given
15106 on the command line, then symbol is considered to be @code{True}. This switch
15107 can be used in place of a definition file.
15108
15109 @ifset vms
15110 @item /REMOVE
15111 @cindex @option{/REMOVE} (@command{gnatprep})
15112 This is the default setting which causes lines deleted by preprocessing
15113 to be entirely removed from the output file.
15114 @end ifset
15115
15116 @item ^-r^/REFERENCE^
15117 @cindex @option{^-r^/REFERENCE^} (@command{gnatprep})
15118 Causes a @code{Source_Reference} pragma to be generated that
15119 references the original input file, so that error messages will use
15120 the file name of this original file. The use of this switch implies
15121 that preprocessor lines are not to be removed from the file, so its
15122 use will force @option{^-b^/BLANK_LINES^} mode if
15123 @option{^-c^/COMMENTS^}
15124 has not been specified explicitly.
15125
15126 Note that if the file to be preprocessed contains multiple units, then
15127 it will be necessary to @code{gnatchop} the output file from
15128 @code{gnatprep}. If a @code{Source_Reference} pragma is present
15129 in the preprocessed file, it will be respected by
15130 @code{gnatchop ^-r^/REFERENCE^}
15131 so that the final chopped files will correctly refer to the original
15132 input source file for @code{gnatprep}.
15133
15134 @item ^-s^/SYMBOLS^
15135 @cindex @option{^-s^/SYMBOLS^} (@command{gnatprep})
15136 Causes a sorted list of symbol names and values to be
15137 listed on the standard output file.
15138
15139 @item ^-u^/UNDEFINED^
15140 @cindex @option{^-u^/UNDEFINED^} (@command{gnatprep})
15141 Causes undefined symbols to be treated as having the value FALSE in the context
15142 of a preprocessor test. In the absence of this option, an undefined symbol in
15143 a @code{#if} or @code{#elsif} test will be treated as an error.
15144
15145 @end table
15146
15147 @ifclear vms
15148 @noindent
15149 Note: if neither @option{-b} nor @option{-c} is present,
15150 then preprocessor lines and
15151 deleted lines are completely removed from the output, unless -r is
15152 specified, in which case -b is assumed.
15153 @end ifclear
15154
15155 @node Form of Definitions File
15156 @section Form of Definitions File
15157
15158 @noindent
15159 The definitions file contains lines of the form
15160
15161 @smallexample
15162 symbol := value
15163 @end smallexample
15164
15165 @noindent
15166 where symbol is a preprocessing symbol, and value is one of the following:
15167
15168 @itemize @bullet
15169 @item
15170 Empty, corresponding to a null substitution
15171 @item
15172 A string literal using normal Ada syntax
15173 @item
15174 Any sequence of characters from the set
15175 (letters, digits, period, underline).
15176 @end itemize
15177
15178 @noindent
15179 Comment lines may also appear in the definitions file, starting with
15180 the usual @code{--},
15181 and comments may be added to the definitions lines.
15182
15183 @node Form of Input Text for gnatprep
15184 @section Form of Input Text for @code{gnatprep}
15185
15186 @noindent
15187 The input text may contain preprocessor conditional inclusion lines,
15188 as well as general symbol substitution sequences.
15189
15190 The preprocessor conditional inclusion commands have the form
15191
15192 @smallexample
15193 @group
15194 @cartouche
15195 #if @i{expression} @r{[}then@r{]}
15196    lines
15197 #elsif @i{expression} @r{[}then@r{]}
15198    lines
15199 #elsif @i{expression} @r{[}then@r{]}
15200    lines
15201 @dots{}
15202 #else
15203    lines
15204 #end if;
15205 @end cartouche
15206 @end group
15207 @end smallexample
15208
15209 @noindent
15210 In this example, @i{expression} is defined by the following grammar:
15211 @smallexample
15212 @i{expression} ::=  <symbol>
15213 @i{expression} ::=  <symbol> = "<value>"
15214 @i{expression} ::=  <symbol> = <symbol>
15215 @i{expression} ::=  <symbol> 'Defined
15216 @i{expression} ::=  not @i{expression}
15217 @i{expression} ::=  @i{expression} and @i{expression}
15218 @i{expression} ::=  @i{expression} or @i{expression}
15219 @i{expression} ::=  @i{expression} and then @i{expression}
15220 @i{expression} ::=  @i{expression} or else @i{expression}
15221 @i{expression} ::=  ( @i{expression} )
15222 @end smallexample
15223
15224 The following restriction exists: it is not allowed to have "and" or "or"
15225 following "not" in the same expression without parentheses. For example, this
15226 is not allowed:
15227
15228 @smallexample
15229    not X or Y
15230 @end smallexample
15231
15232 This should be one of the following:
15233
15234 @smallexample
15235    (not X) or Y
15236    not (X or Y)
15237 @end smallexample
15238
15239 @noindent
15240 For the first test (@i{expression} ::= <symbol>) the symbol must have
15241 either the value true or false, that is to say the right-hand of the
15242 symbol definition must be one of the (case-insensitive) literals
15243 @code{True} or @code{False}. If the value is true, then the
15244 corresponding lines are included, and if the value is false, they are
15245 excluded.
15246
15247 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
15248 the symbol has been defined in the definition file or by a @option{-D}
15249 switch on the command line. Otherwise, the test is false.
15250
15251 The equality tests are case insensitive, as are all the preprocessor lines.
15252
15253 If the symbol referenced is not defined in the symbol definitions file,
15254 then the effect depends on whether or not switch @option{-u}
15255 is specified. If so, then the symbol is treated as if it had the value
15256 false and the test fails. If this switch is not specified, then
15257 it is an error to reference an undefined symbol. It is also an error to
15258 reference a symbol that is defined with a value other than @code{True}
15259 or @code{False}.
15260
15261 The use of the @code{not} operator inverts the sense of this logical test.
15262 The @code{not} operator cannot be combined with the @code{or} or @code{and}
15263 operators, without parentheses. For example, "if not X or Y then" is not
15264 allowed, but "if (not X) or Y then" and "if not (X or Y) then" are.
15265
15266 The @code{then} keyword is optional as shown
15267
15268 The @code{#} must be the first non-blank character on a line, but
15269 otherwise the format is free form. Spaces or tabs may appear between
15270 the @code{#} and the keyword. The keywords and the symbols are case
15271 insensitive as in normal Ada code. Comments may be used on a
15272 preprocessor line, but other than that, no other tokens may appear on a
15273 preprocessor line. Any number of @code{elsif} clauses can be present,
15274 including none at all. The @code{else} is optional, as in Ada.
15275
15276 The @code{#} marking the start of a preprocessor line must be the first
15277 non-blank character on the line, i.e., it must be preceded only by
15278 spaces or horizontal tabs.
15279
15280 Symbol substitution outside of preprocessor lines is obtained by using
15281 the sequence
15282
15283 @smallexample
15284 $symbol
15285 @end smallexample
15286
15287 @noindent
15288 anywhere within a source line, except in a comment or within a
15289 string literal. The identifier
15290 following the @code{$} must match one of the symbols defined in the symbol
15291 definition file, and the result is to substitute the value of the
15292 symbol in place of @code{$symbol} in the output file.
15293
15294 Note that although the substitution of strings within a string literal
15295 is not possible, it is possible to have a symbol whose defined value is
15296 a string literal. So instead of setting XYZ to @code{hello} and writing:
15297
15298 @smallexample
15299 Header : String := "$XYZ";
15300 @end smallexample
15301
15302 @noindent
15303 you should set XYZ to @code{"hello"} and write:
15304
15305 @smallexample
15306 Header : String := $XYZ;
15307 @end smallexample
15308
15309 @noindent
15310 and then the substitution will occur as desired.
15311
15312 @node The GNAT Library Browser gnatls
15313 @chapter The GNAT Library Browser @code{gnatls}
15314 @findex gnatls
15315 @cindex Library browser
15316
15317 @noindent
15318 @code{gnatls} is a tool that outputs information about compiled
15319 units. It gives the relationship between objects, unit names and source
15320 files. It can also be used to check the source dependencies of a unit
15321 as well as various characteristics.
15322
15323 Note: to invoke @code{gnatls} with a project file, use the @code{gnat}
15324 driver (see @ref{The GNAT Driver and Project Files}).
15325
15326 @menu
15327 * Running gnatls::
15328 * Switches for gnatls::
15329 * Examples of gnatls Usage::
15330 @end menu
15331
15332 @node Running gnatls
15333 @section Running @code{gnatls}
15334
15335 @noindent
15336 The @code{gnatls} command has the form
15337
15338 @smallexample
15339 $ gnatls switches @var{object_or_ali_file}
15340 @end smallexample
15341
15342 @noindent
15343 The main argument is the list of object or @file{ali} files
15344 (@pxref{The Ada Library Information Files})
15345 for which information is requested.
15346
15347 In normal mode, without additional option, @code{gnatls} produces a
15348 four-column listing. Each line represents information for a specific
15349 object. The first column gives the full path of the object, the second
15350 column gives the name of the principal unit in this object, the third
15351 column gives the status of the source and the fourth column gives the
15352 full path of the source representing this unit.
15353 Here is a simple example of use:
15354
15355 @smallexample
15356 $ gnatls *.o
15357 ^./^[]^demo1.o            demo1            DIF demo1.adb
15358 ^./^[]^demo2.o            demo2             OK demo2.adb
15359 ^./^[]^hello.o            h1                OK hello.adb
15360 ^./^[]^instr-child.o      instr.child      MOK instr-child.adb
15361 ^./^[]^instr.o            instr             OK instr.adb
15362 ^./^[]^tef.o              tef              DIF tef.adb
15363 ^./^[]^text_io_example.o  text_io_example   OK text_io_example.adb
15364 ^./^[]^tgef.o             tgef             DIF tgef.adb
15365 @end smallexample
15366
15367 @noindent
15368 The first line can be interpreted as follows: the main unit which is
15369 contained in
15370 object file @file{demo1.o} is demo1, whose main source is in
15371 @file{demo1.adb}. Furthermore, the version of the source used for the
15372 compilation of demo1 has been modified (DIF). Each source file has a status
15373 qualifier which can be:
15374
15375 @table @code
15376 @item OK (unchanged)
15377 The version of the source file used for the compilation of the
15378 specified unit corresponds exactly to the actual source file.
15379
15380 @item MOK (slightly modified)
15381 The version of the source file used for the compilation of the
15382 specified unit differs from the actual source file but not enough to
15383 require recompilation. If you use gnatmake with the qualifier
15384 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
15385 MOK will not be recompiled.
15386
15387 @item DIF (modified)
15388 No version of the source found on the path corresponds to the source
15389 used to build this object.
15390
15391 @item ??? (file not found)
15392 No source file was found for this unit.
15393
15394 @item HID (hidden,  unchanged version not first on PATH)
15395 The version of the source that corresponds exactly to the source used
15396 for compilation has been found on the path but it is hidden by another
15397 version of the same source that has been modified.
15398
15399 @end table
15400
15401 @node Switches for gnatls
15402 @section Switches for @code{gnatls}
15403
15404 @noindent
15405 @code{gnatls} recognizes the following switches:
15406
15407 @table @option
15408 @c !sort!
15409 @cindex @option{--version} @command{gnatls}
15410 Display Copyright and version, then exit disregarding all other options.
15411
15412 @item --help
15413 @cindex @option{--help} @command{gnatls}
15414 If @option{--version} was not used, display usage, then exit disregarding
15415 all other options.
15416
15417 @item ^-a^/ALL_UNITS^
15418 @cindex @option{^-a^/ALL_UNITS^} (@code{gnatls})
15419 Consider all units, including those of the predefined Ada library.
15420 Especially useful with @option{^-d^/DEPENDENCIES^}.
15421
15422 @item ^-d^/DEPENDENCIES^
15423 @cindex @option{^-d^/DEPENDENCIES^} (@code{gnatls})
15424 List sources from which specified units depend on.
15425
15426 @item ^-h^/OUTPUT=OPTIONS^
15427 @cindex @option{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
15428 Output the list of options.
15429
15430 @item ^-o^/OUTPUT=OBJECTS^
15431 @cindex @option{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
15432 Only output information about object files.
15433
15434 @item ^-s^/OUTPUT=SOURCES^
15435 @cindex @option{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
15436 Only output information about source files.
15437
15438 @item ^-u^/OUTPUT=UNITS^
15439 @cindex @option{^-u^/OUTPUT=UNITS^} (@code{gnatls})
15440 Only output information about compilation units.
15441
15442 @item ^-files^/FILES^=@var{file}
15443 @cindex @option{^-files^/FILES^} (@code{gnatls})
15444 Take as arguments the files listed in text file @var{file}.
15445 Text file @var{file} may contain empty lines that are ignored.
15446 Each nonempty line should contain the name of an existing file.
15447 Several such switches may be specified simultaneously.
15448
15449 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
15450 @itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
15451 @itemx ^-I^/SEARCH=^@var{dir}
15452 @itemx  ^-I-^/NOCURRENT_DIRECTORY^
15453 @itemx -nostdinc
15454 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatls})
15455 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatls})
15456 @cindex @option{^-I^/SEARCH^} (@code{gnatls})
15457 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatls})
15458 Source path manipulation. Same meaning as the equivalent @command{gnatmake}
15459 flags (@pxref{Switches for gnatmake}).
15460
15461 @item --RTS=@var{rts-path}
15462 @cindex @option{--RTS} (@code{gnatls})
15463 Specifies the default location of the runtime library. Same meaning as the
15464 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
15465
15466 @item ^-v^/OUTPUT=VERBOSE^
15467 @cindex @option{^-v^/OUTPUT=VERBOSE^} (@code{gnatls})
15468 Verbose mode. Output the complete source, object and project paths. Do not use
15469 the default column layout but instead use long format giving as much as
15470 information possible on each requested units, including special
15471 characteristics such as:
15472
15473 @table @code
15474 @item  Preelaborable
15475 The unit is preelaborable in the Ada sense.
15476
15477 @item No_Elab_Code
15478 No elaboration code has been produced by the compiler for this unit.
15479
15480 @item Pure
15481 The unit is pure in the Ada sense.
15482
15483 @item Elaborate_Body
15484 The unit contains a pragma Elaborate_Body.
15485
15486 @item Remote_Types
15487 The unit contains a pragma Remote_Types.
15488
15489 @item Shared_Passive
15490 The unit contains a pragma Shared_Passive.
15491
15492 @item Predefined
15493 This unit is part of the predefined environment and cannot be modified
15494 by the user.
15495
15496 @item Remote_Call_Interface
15497 The unit contains a pragma Remote_Call_Interface.
15498
15499 @end table
15500
15501 @end table
15502
15503 @node Examples of gnatls Usage
15504 @section Example of @code{gnatls} Usage
15505 @ifclear vms
15506
15507 @noindent
15508 Example of using the verbose switch. Note how the source and
15509 object paths are affected by the -I switch.
15510
15511 @smallexample
15512 $ gnatls -v -I.. demo1.o
15513
15514 GNATLS 5.03w (20041123-34)
15515 Copyright 1997-2004 Free Software Foundation, Inc.
15516
15517 Source Search Path:
15518    <Current_Directory>
15519    ../
15520    /home/comar/local/adainclude/
15521
15522 Object Search Path:
15523    <Current_Directory>
15524    ../
15525    /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
15526
15527 Project Search Path:
15528    <Current_Directory>
15529    /home/comar/local/lib/gnat/
15530
15531 ./demo1.o
15532    Unit =>
15533      Name   => demo1
15534      Kind   => subprogram body
15535      Flags  => No_Elab_Code
15536      Source => demo1.adb    modified
15537 @end smallexample
15538
15539 @noindent
15540 The following is an example of use of the dependency list.
15541 Note the use of the -s switch
15542 which gives a straight list of source files. This can be useful for
15543 building specialized scripts.
15544
15545 @smallexample
15546 $ gnatls -d demo2.o
15547 ./demo2.o   demo2        OK demo2.adb
15548                          OK gen_list.ads
15549                          OK gen_list.adb
15550                          OK instr.ads
15551                          OK instr-child.ads
15552
15553 $ gnatls -d -s -a demo1.o
15554 demo1.adb
15555 /home/comar/local/adainclude/ada.ads
15556 /home/comar/local/adainclude/a-finali.ads
15557 /home/comar/local/adainclude/a-filico.ads
15558 /home/comar/local/adainclude/a-stream.ads
15559 /home/comar/local/adainclude/a-tags.ads
15560 gen_list.ads
15561 gen_list.adb
15562 /home/comar/local/adainclude/gnat.ads
15563 /home/comar/local/adainclude/g-io.ads
15564 instr.ads
15565 /home/comar/local/adainclude/system.ads
15566 /home/comar/local/adainclude/s-exctab.ads
15567 /home/comar/local/adainclude/s-finimp.ads
15568 /home/comar/local/adainclude/s-finroo.ads
15569 /home/comar/local/adainclude/s-secsta.ads
15570 /home/comar/local/adainclude/s-stalib.ads
15571 /home/comar/local/adainclude/s-stoele.ads
15572 /home/comar/local/adainclude/s-stratt.ads
15573 /home/comar/local/adainclude/s-tasoli.ads
15574 /home/comar/local/adainclude/s-unstyp.ads
15575 /home/comar/local/adainclude/unchconv.ads
15576 @end smallexample
15577 @end ifclear
15578
15579 @ifset vms
15580 @smallexample
15581 GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
15582
15583 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
15584 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
15585 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
15586 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
15587 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
15588 demo1.adb
15589 gen_list.ads
15590 gen_list.adb
15591 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
15592 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
15593 instr.ads
15594 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
15595 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
15596 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
15597 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
15598 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
15599 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
15600 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
15601 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
15602 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
15603 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
15604 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
15605 @end smallexample
15606 @end ifset
15607
15608 @node Cleaning Up Using gnatclean
15609 @chapter Cleaning Up Using @code{gnatclean}
15610 @findex gnatclean
15611 @cindex Cleaning tool
15612
15613 @noindent
15614 @code{gnatclean} is a tool that allows the deletion of files produced by the
15615 compiler, binder and linker, including ALI files, object files, tree files,
15616 expanded source files, library files, interface copy source files, binder
15617 generated files and executable files.
15618
15619 @menu
15620 * Running gnatclean::
15621 * Switches for gnatclean::
15622 @c * Examples of gnatclean Usage::
15623 @end menu
15624
15625 @node Running gnatclean
15626 @section Running @code{gnatclean}
15627
15628 @noindent
15629 The @code{gnatclean} command has the form:
15630
15631 @smallexample
15632 $ gnatclean switches @var{names}
15633 @end smallexample
15634
15635 @noindent
15636 @var{names} is a list of source file names. Suffixes @code{.^ads^ADS^} and
15637 @code{^adb^ADB^} may be omitted. If a project file is specified using switch
15638 @code{^-P^/PROJECT_FILE=^}, then @var{names} may be completely omitted.
15639
15640 @noindent
15641 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
15642 if switch @code{^-c^/COMPILER_FILES_ONLY^} is not specified, by the binder and
15643 the linker. In informative-only mode, specified by switch
15644 @code{^-n^/NODELETE^}, the list of files that would have been deleted in
15645 normal mode is listed, but no file is actually deleted.
15646
15647 @node Switches for gnatclean
15648 @section Switches for @code{gnatclean}
15649
15650 @noindent
15651 @code{gnatclean} recognizes the following switches:
15652
15653 @table @option
15654 @c !sort!
15655 @cindex @option{--version} @command{gnatclean}
15656 Display Copyright and version, then exit disregarding all other options.
15657
15658 @item --help
15659 @cindex @option{--help} @command{gnatclean}
15660 If @option{--version} was not used, display usage, then exit disregarding
15661 all other options.
15662
15663 @item ^--subdirs^/SUBDIRS^=subdir
15664 Actual object directory of each project file is the subdirectory subdir of the
15665 object directory specified or defaulted in the project file.
15666
15667 @item ^--unchecked-shared-lib-imports^/UNCHECKED_SHARED_LIB_IMPORTS^
15668 By default, shared library projects are not allowed to import static library
15669 projects. When this switch is used on the command line, this restriction is
15670 relaxed.
15671
15672 @item ^-c^/COMPILER_FILES_ONLY^
15673 @cindex @option{^-c^/COMPILER_FILES_ONLY^} (@code{gnatclean})
15674 Only attempt to delete the files produced by the compiler, not those produced
15675 by the binder or the linker. The files that are not to be deleted are library
15676 files, interface copy files, binder generated files and executable files.
15677
15678 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
15679 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatclean})
15680 Indicate that ALI and object files should normally be found in directory
15681 @var{dir}.
15682
15683 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
15684 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatclean})
15685 When using project files, if some errors or warnings are detected during
15686 parsing and verbose mode is not in effect (no use of switch
15687 ^-v^/VERBOSE^), then error lines start with the full path name of the project
15688 file, rather than its simple file name.
15689
15690 @item ^-h^/HELP^
15691 @cindex @option{^-h^/HELP^} (@code{gnatclean})
15692 Output a message explaining the usage of @code{^gnatclean^gnatclean^}.
15693
15694 @item ^-n^/NODELETE^
15695 @cindex @option{^-n^/NODELETE^} (@code{gnatclean})
15696 Informative-only mode. Do not delete any files. Output the list of the files
15697 that would have been deleted if this switch was not specified.
15698
15699 @item ^-P^/PROJECT_FILE=^@var{project}
15700 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatclean})
15701 Use project file @var{project}. Only one such switch can be used.
15702 When cleaning a project file, the files produced by the compilation of the
15703 immediate sources or inherited sources of the project files are to be
15704 deleted. This is not depending on the presence or not of executable names
15705 on the command line.
15706
15707 @item ^-q^/QUIET^
15708 @cindex @option{^-q^/QUIET^} (@code{gnatclean})
15709 Quiet output. If there are no errors, do not output anything, except in
15710 verbose mode (switch ^-v^/VERBOSE^) or in informative-only mode
15711 (switch ^-n^/NODELETE^).
15712
15713 @item ^-r^/RECURSIVE^
15714 @cindex @option{^-r^/RECURSIVE^} (@code{gnatclean})
15715 When a project file is specified (using switch ^-P^/PROJECT_FILE=^),
15716 clean all imported and extended project files, recursively. If this switch
15717 is not specified, only the files related to the main project file are to be
15718 deleted. This switch has no effect if no project file is specified.
15719
15720 @item ^-v^/VERBOSE^
15721 @cindex @option{^-v^/VERBOSE^} (@code{gnatclean})
15722 Verbose mode.
15723
15724 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
15725 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (@code{gnatclean})
15726 Indicates the verbosity of the parsing of GNAT project files.
15727 @xref{Switches Related to Project Files}.
15728
15729 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
15730 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (@code{gnatclean})
15731 Indicates that external variable @var{name} has the value @var{value}.
15732 The Project Manager will use this value for occurrences of
15733 @code{external(name)} when parsing the project file.
15734 @xref{Switches Related to Project Files}.
15735
15736 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
15737 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatclean})
15738 When searching for ALI and object files, look in directory
15739 @var{dir}.
15740
15741 @item ^-I^/SEARCH=^@var{dir}
15742 @cindex @option{^-I^/SEARCH^} (@code{gnatclean})
15743 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}}.
15744
15745 @item ^-I-^/NOCURRENT_DIRECTORY^
15746 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatclean})
15747 @cindex Source files, suppressing search
15748 Do not look for ALI or object files in the directory
15749 where @code{gnatclean} was invoked.
15750
15751 @end table
15752
15753 @c @node Examples of gnatclean Usage
15754 @c @section Examples of @code{gnatclean} Usage
15755
15756 @ifclear vms
15757 @node GNAT and Libraries
15758 @chapter GNAT and Libraries
15759 @cindex Library, building, installing, using
15760
15761 @noindent
15762 This chapter describes how to build and use libraries with GNAT, and also shows
15763 how to recompile the GNAT run-time library. You should be familiar with the
15764 Project Manager facility (@pxref{GNAT Project Manager}) before reading this
15765 chapter.
15766
15767 @menu
15768 * Introduction to Libraries in GNAT::
15769 * General Ada Libraries::
15770 * Stand-alone Ada Libraries::
15771 * Rebuilding the GNAT Run-Time Library::
15772 @end menu
15773
15774 @node Introduction to Libraries in GNAT
15775 @section Introduction to Libraries in GNAT
15776
15777 @noindent
15778 A library is, conceptually, a collection of objects which does not have its
15779 own main thread of execution, but rather provides certain services to the
15780 applications that use it. A library can be either statically linked with the
15781 application, in which case its code is directly included in the application,
15782 or, on platforms that support it, be dynamically linked, in which case
15783 its code is shared by all applications making use of this library.
15784
15785 GNAT supports both types of libraries.
15786 In the static case, the compiled code can be provided in different ways. The
15787 simplest approach is to provide directly the set of objects resulting from
15788 compilation of the library source files. Alternatively, you can group the
15789 objects into an archive using whatever commands are provided by the operating
15790 system. For the latter case, the objects are grouped into a shared library.
15791
15792 In the GNAT environment, a library has three types of components:
15793 @itemize @bullet
15794 @item
15795 Source files.
15796 @item
15797 @file{ALI} files.
15798 @xref{The Ada Library Information Files}.
15799 @item
15800 Object files, an archive or a shared library.
15801 @end itemize
15802
15803 @noindent
15804 A GNAT library may expose all its source files, which is useful for
15805 documentation purposes. Alternatively, it may expose only the units needed by
15806 an external user to make use of the library. That is to say, the specs
15807 reflecting the library services along with all the units needed to compile
15808 those specs, which can include generic bodies or any body implementing an
15809 inlined routine. In the case of @emph{stand-alone libraries} those exposed
15810 units are called @emph{interface units} (@pxref{Stand-alone Ada Libraries}).
15811
15812 All compilation units comprising an application, including those in a library,
15813 need to be elaborated in an order partially defined by Ada's semantics. GNAT
15814 computes the elaboration order from the @file{ALI} files and this is why they
15815 constitute a mandatory part of GNAT libraries.
15816 @emph{Stand-alone libraries} are the exception to this rule because a specific
15817 library elaboration routine is produced independently of the application(s)
15818 using the library.
15819
15820 @node General Ada Libraries
15821 @section General Ada Libraries
15822
15823 @menu
15824 * Building a library::
15825 * Installing a library::
15826 * Using a library::
15827 @end menu
15828
15829 @node Building a library
15830 @subsection Building a library
15831
15832 @noindent
15833 The easiest way to build a library is to use the Project Manager,
15834 which supports a special type of project called a @emph{Library Project}
15835 (@pxref{Library Projects}).
15836
15837 A project is considered a library project, when two project-level attributes
15838 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
15839 control different aspects of library configuration, additional optional
15840 project-level attributes can be specified:
15841 @table @code
15842 @item Library_Kind
15843 This attribute controls whether the library is to be static or dynamic
15844
15845 @item Library_Version
15846 This attribute specifies the library version; this value is used
15847 during dynamic linking of shared libraries to determine if the currently
15848 installed versions of the binaries are compatible.
15849
15850 @item Library_Options
15851 @item Library_GCC
15852 These attributes specify additional low-level options to be used during
15853 library generation, and redefine the actual application used to generate
15854 library.
15855 @end table
15856
15857 @noindent
15858 The GNAT Project Manager takes full care of the library maintenance task,
15859 including recompilation of the source files for which objects do not exist
15860 or are not up to date, assembly of the library archive, and installation of
15861 the library (i.e., copying associated source, object and @file{ALI} files
15862 to the specified location).
15863
15864 Here is a simple library project file:
15865 @smallexample @c ada
15866 project My_Lib is
15867    for Source_Dirs use ("src1", "src2");
15868    for Object_Dir use "obj";
15869    for Library_Name use "mylib";
15870    for Library_Dir use "lib";
15871    for Library_Kind use "dynamic";
15872 end My_lib;
15873 @end smallexample
15874
15875 @noindent
15876 and the compilation command to build and install the library:
15877
15878 @smallexample @c ada
15879   $ gnatmake -Pmy_lib
15880 @end smallexample
15881
15882 @noindent
15883 It is not entirely trivial to perform manually all the steps required to
15884 produce a library. We recommend that you use the GNAT Project Manager
15885 for this task. In special cases where this is not desired, the necessary
15886 steps are discussed below.
15887
15888 There are various possibilities for compiling the units that make up the
15889 library: for example with a Makefile (@pxref{Using the GNU make Utility}) or
15890 with a conventional script. For simple libraries, it is also possible to create
15891 a dummy main program which depends upon all the packages that comprise the
15892 interface of the library. This dummy main program can then be given to
15893 @command{gnatmake}, which will ensure that all necessary objects are built.
15894
15895 After this task is accomplished, you should follow the standard procedure
15896 of the underlying operating system to produce the static or shared library.
15897
15898 Here is an example of such a dummy program:
15899 @smallexample @c ada
15900 @group
15901 with My_Lib.Service1;
15902 with My_Lib.Service2;
15903 with My_Lib.Service3;
15904 procedure My_Lib_Dummy is
15905 begin
15906    null;
15907 end;
15908 @end group
15909 @end smallexample
15910
15911 @noindent
15912 Here are the generic commands that will build an archive or a shared library.
15913
15914 @smallexample
15915 # compiling the library
15916 $ gnatmake -c my_lib_dummy.adb
15917
15918 # we don't need the dummy object itself
15919 $ rm my_lib_dummy.o my_lib_dummy.ali
15920
15921 # create an archive with the remaining objects
15922 $ ar rc libmy_lib.a *.o
15923 # some systems may require "ranlib" to be run as well
15924
15925 # or create a shared library
15926 $ gcc -shared -o libmy_lib.so *.o
15927 # some systems may require the code to have been compiled with -fPIC
15928
15929 # remove the object files that are now in the library
15930 $ rm *.o
15931
15932 # Make the ALI files read-only so that gnatmake will not try to
15933 # regenerate the objects that are in the library
15934 $ chmod -w *.ali
15935 @end smallexample
15936
15937 @noindent
15938 Please note that the library must have a name of the form @file{lib@var{xxx}.a}
15939 or @file{lib@var{xxx}.so} (or @file{lib@var{xxx}.dll} on Windows) in order to
15940 be accessed by the directive @option{-l@var{xxx}} at link time.
15941
15942 @node Installing a library
15943 @subsection Installing a library
15944 @cindex @code{ADA_PROJECT_PATH}
15945 @cindex @code{GPR_PROJECT_PATH}
15946
15947 @noindent
15948 If you use project files, library installation is part of the library build
15949 process (@pxref{Installing a library with project files}).
15950
15951 When project files are not an option, it is also possible, but not recommended,
15952 to install the library so that the sources needed to use the library are on the
15953 Ada source path and the ALI files & libraries be on the Ada Object path (see
15954 @ref{Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
15955 administrator can place general-purpose libraries in the default compiler
15956 paths, by specifying the libraries' location in the configuration files
15957 @file{ada_source_path} and @file{ada_object_path}. These configuration files
15958 must be located in the GNAT installation tree at the same place as the gcc spec
15959 file. The location of the gcc spec file can be determined as follows:
15960 @smallexample
15961 $ gcc -v
15962 @end smallexample
15963
15964 @noindent
15965 The configuration files mentioned above have a simple format: each line
15966 must contain one unique directory name.
15967 Those names are added to the corresponding path
15968 in their order of appearance in the file. The names can be either absolute
15969 or relative; in the latter case, they are relative to where theses files
15970 are located.
15971
15972 The files @file{ada_source_path} and @file{ada_object_path} might not be
15973 present in a
15974 GNAT installation, in which case, GNAT will look for its run-time library in
15975 the directories @file{adainclude} (for the sources) and @file{adalib} (for the
15976 objects and @file{ALI} files). When the files exist, the compiler does not
15977 look in @file{adainclude} and @file{adalib}, and thus the
15978 @file{ada_source_path} file
15979 must contain the location for the GNAT run-time sources (which can simply
15980 be @file{adainclude}). In the same way, the @file{ada_object_path} file must
15981 contain the location for the GNAT run-time objects (which can simply
15982 be @file{adalib}).
15983
15984 You can also specify a new default path to the run-time library at compilation
15985 time with the switch @option{--RTS=rts-path}. You can thus choose / change
15986 the run-time library you want your program to be compiled with. This switch is
15987 recognized by @command{gcc}, @command{gnatmake}, @command{gnatbind},
15988 @command{gnatls}, @command{gnatfind} and @command{gnatxref}.
15989
15990 It is possible to install a library before or after the standard GNAT
15991 library, by reordering the lines in the configuration files. In general, a
15992 library must be installed before the GNAT library if it redefines
15993 any part of it.
15994
15995 @node Using a library
15996 @subsection Using a library
15997
15998 @noindent Once again, the project facility greatly simplifies the use of
15999 libraries. In this context, using a library is just a matter of adding a
16000 @code{with} clause in the user project. For instance, to make use of the
16001 library @code{My_Lib} shown in examples in earlier sections, you can
16002 write:
16003
16004 @smallexample @c projectfile
16005 with "my_lib";
16006 project My_Proj is
16007   @dots{}
16008 end My_Proj;
16009 @end smallexample
16010
16011 Even if you have a third-party, non-Ada library, you can still use GNAT's
16012 Project Manager facility to provide a wrapper for it. For example, the
16013 following project, when @code{with}ed by your main project, will link with the
16014 third-party library @file{liba.a}:
16015
16016 @smallexample @c projectfile
16017 @group
16018 project Liba is
16019    for Externally_Built use "true";
16020    for Source_Files use ();
16021    for Library_Dir use "lib";
16022    for Library_Name use "a";
16023    for Library_Kind use "static";
16024 end Liba;
16025 @end group
16026 @end smallexample
16027 This is an alternative to the use of @code{pragma Linker_Options}. It is
16028 especially interesting in the context of systems with several interdependent
16029 static libraries where finding a proper linker order is not easy and best be
16030 left to the tools having visibility over project dependence information.
16031
16032 @noindent
16033 In order to use an Ada library manually, you need to make sure that this
16034 library is on both your source and object path
16035 (see @ref{Search Paths and the Run-Time Library (RTL)}
16036 and @ref{Search Paths for gnatbind}). Furthermore, when the objects are grouped
16037 in an archive or a shared library, you need to specify the desired
16038 library at link time.
16039
16040 For example, you can use the library @file{mylib} installed in
16041 @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
16042
16043 @smallexample
16044 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
16045   -largs -lmy_lib
16046 @end smallexample
16047
16048 @noindent
16049 This can be expressed more simply:
16050 @smallexample
16051 $ gnatmake my_appl
16052 @end smallexample
16053 @noindent
16054 when the following conditions are met:
16055 @itemize @bullet
16056 @item
16057 @file{/dir/my_lib_src} has been added by the user to the environment
16058 variable @env{ADA_INCLUDE_PATH}, or by the administrator to the file
16059 @file{ada_source_path}
16060 @item
16061 @file{/dir/my_lib_obj} has been added by the user to the environment
16062 variable @env{ADA_OBJECTS_PATH}, or by the administrator to the file
16063 @file{ada_object_path}
16064 @item
16065 a pragma @code{Linker_Options} has been added to one of the sources.
16066 For example:
16067
16068 @smallexample @c ada
16069 pragma Linker_Options ("-lmy_lib");
16070 @end smallexample
16071 @end itemize
16072
16073 @node Stand-alone Ada Libraries
16074 @section Stand-alone Ada Libraries
16075 @cindex Stand-alone library, building, using
16076
16077 @menu
16078 * Introduction to Stand-alone Libraries::
16079 * Building a Stand-alone Library::
16080 * Creating a Stand-alone Library to be used in a non-Ada context::
16081 * Restrictions in Stand-alone Libraries::
16082 @end menu
16083
16084 @node Introduction to Stand-alone Libraries
16085 @subsection Introduction to Stand-alone Libraries
16086
16087 @noindent
16088 A Stand-alone Library (abbreviated ``SAL'') is a library that contains the
16089 necessary code to
16090 elaborate the Ada units that are included in the library. In contrast with
16091 an ordinary library, which consists of all sources, objects and @file{ALI}
16092 files of the
16093 library, a SAL may specify a restricted subset of compilation units
16094 to serve as a library interface. In this case, the fully
16095 self-sufficient set of files will normally consist of an objects
16096 archive, the sources of interface units' specs, and the @file{ALI}
16097 files of interface units.
16098 If an interface spec contains a generic unit or an inlined subprogram,
16099 the body's
16100 source must also be provided; if the units that must be provided in the source
16101 form depend on other units, the source and @file{ALI} files of those must
16102 also be provided.
16103
16104 The main purpose of a SAL is to minimize the recompilation overhead of client
16105 applications when a new version of the library is installed. Specifically,
16106 if the interface sources have not changed, client applications do not need to
16107 be recompiled. If, furthermore, a SAL is provided in the shared form and its
16108 version, controlled by @code{Library_Version} attribute, is not changed,
16109 then the clients do not need to be relinked.
16110
16111 SALs also allow the library providers to minimize the amount of library source
16112 text exposed to the clients.  Such ``information hiding'' might be useful or
16113 necessary for various reasons.
16114
16115 Stand-alone libraries are also well suited to be used in an executable whose
16116 main routine is not written in Ada.
16117
16118 @node Building a Stand-alone Library
16119 @subsection Building a Stand-alone Library
16120
16121 @noindent
16122 GNAT's Project facility provides a simple way of building and installing
16123 stand-alone libraries; see @ref{Stand-alone Library Projects}.
16124 To be a Stand-alone Library Project, in addition to the two attributes
16125 that make a project a Library Project (@code{Library_Name} and
16126 @code{Library_Dir}; see @ref{Library Projects}), the attribute
16127 @code{Library_Interface} must be defined.  For example:
16128
16129 @smallexample @c projectfile
16130 @group
16131    for Library_Dir use "lib_dir";
16132    for Library_Name use "dummy";
16133    for Library_Interface use ("int1", "int1.child");
16134 @end group
16135 @end smallexample
16136
16137 @noindent
16138 Attribute @code{Library_Interface} has a non-empty string list value,
16139 each string in the list designating a unit contained in an immediate source
16140 of the project file.
16141
16142 When a Stand-alone Library is built, first the binder is invoked to build
16143 a package whose name depends on the library name
16144 (@file{^b~dummy.ads/b^B$DUMMY.ADS/B^} in the example above).
16145 This binder-generated package includes initialization and
16146 finalization procedures whose
16147 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
16148 in the example
16149 above). The object corresponding to this package is included in the library.
16150
16151 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
16152 calling of these procedures if a static SAL is built, or if a shared SAL
16153 is built
16154 with the project-level attribute @code{Library_Auto_Init} set to
16155 @code{"false"}.
16156
16157 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
16158 (those that are listed in attribute @code{Library_Interface}) are copied to
16159 the Library Directory. As a consequence, only the Interface Units may be
16160 imported from Ada units outside of the library. If other units are imported,
16161 the binding phase will fail.
16162
16163 The attribute @code{Library_Src_Dir} may be specified for a
16164 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
16165 single string value. Its value must be the path (absolute or relative to the
16166 project directory) of an existing directory. This directory cannot be the
16167 object directory or one of the source directories, but it can be the same as
16168 the library directory. The sources of the Interface
16169 Units of the library that are needed by an Ada client of the library will be
16170 copied to the designated directory, called the Interface Copy directory.
16171 These sources include the specs of the Interface Units, but they may also
16172 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
16173 are used, or when there is a generic unit in the spec. Before the sources
16174 are copied to the Interface Copy directory, an attempt is made to delete all
16175 files in the Interface Copy directory.
16176
16177 Building stand-alone libraries by hand is somewhat tedious, but for those
16178 occasions when it is necessary here are the steps that you need to perform:
16179 @itemize @bullet
16180 @item
16181 Compile all library sources.
16182
16183 @item
16184 Invoke the binder with the switch @option{-n} (No Ada main program),
16185 with all the @file{ALI} files of the interfaces, and
16186 with the switch @option{-L} to give specific names to the @code{init}
16187 and @code{final} procedures.  For example:
16188 @smallexample
16189   gnatbind -n int1.ali int2.ali -Lsal1
16190 @end smallexample
16191
16192 @item
16193 Compile the binder generated file:
16194 @smallexample
16195   gcc -c b~int2.adb
16196 @end smallexample
16197
16198 @item
16199 Link the dynamic library with all the necessary object files,
16200 indicating to the linker the names of the @code{init} (and possibly
16201 @code{final}) procedures for automatic initialization (and finalization).
16202 The built library should be placed in a directory different from
16203 the object directory.
16204
16205 @item
16206 Copy the @code{ALI} files of the interface to the library directory,
16207 add in this copy an indication that it is an interface to a SAL
16208 (i.e., add a word @option{SL} on the line in the @file{ALI} file that starts
16209 with letter ``P'') and make the modified copy of the @file{ALI} file
16210 read-only.
16211 @end itemize
16212
16213 @noindent
16214 Using SALs is not different from using other libraries
16215 (see @ref{Using a library}).
16216
16217 @node Creating a Stand-alone Library to be used in a non-Ada context
16218 @subsection Creating a Stand-alone Library to be used in a non-Ada context
16219
16220 @noindent
16221 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
16222 a non-Ada context.
16223
16224 The only extra step required is to ensure that library interface subprograms
16225 are compatible with the main program, by means of @code{pragma Export}
16226 or @code{pragma Convention}.
16227
16228 Here is an example of simple library interface for use with C main program:
16229
16230 @smallexample @c ada
16231 package My_Package is
16232
16233    procedure Do_Something;
16234    pragma Export (C, Do_Something, "do_something");
16235
16236    procedure Do_Something_Else;
16237    pragma Export (C, Do_Something_Else, "do_something_else");
16238
16239 end My_Package;
16240 @end smallexample
16241
16242 @noindent
16243 On the foreign language side, you must provide a ``foreign'' view of the
16244 library interface; remember that it should contain elaboration routines in
16245 addition to interface subprograms.
16246
16247 The example below shows the content of @code{mylib_interface.h} (note
16248 that there is no rule for the naming of this file, any name can be used)
16249 @smallexample
16250 /* the library elaboration procedure */
16251 extern void mylibinit (void);
16252
16253 /* the library finalization procedure */
16254 extern void mylibfinal (void);
16255
16256 /* the interface exported by the library */
16257 extern void do_something (void);
16258 extern void do_something_else (void);
16259 @end smallexample
16260
16261 @noindent
16262 Libraries built as explained above can be used from any program, provided
16263 that the elaboration procedures (named @code{mylibinit} in the previous
16264 example) are called before the library services are used. Any number of
16265 libraries can be used simultaneously, as long as the elaboration
16266 procedure of each library is called.
16267
16268 Below is an example of a C program that uses the @code{mylib} library.
16269
16270 @smallexample
16271 #include "mylib_interface.h"
16272
16273 int
16274 main (void)
16275 @{
16276    /* First, elaborate the library before using it */
16277    mylibinit ();
16278
16279    /* Main program, using the library exported entities */
16280    do_something ();
16281    do_something_else ();
16282
16283    /* Library finalization at the end of the program */
16284    mylibfinal ();
16285    return 0;
16286 @}
16287 @end smallexample
16288
16289 @noindent
16290 Note that invoking any library finalization procedure generated by
16291 @code{gnatbind} shuts down the Ada run-time environment.
16292 Consequently, the
16293 finalization of all Ada libraries must be performed at the end of the program.
16294 No call to these libraries or to the Ada run-time library should be made
16295 after the finalization phase.
16296
16297 @node Restrictions in Stand-alone Libraries
16298 @subsection Restrictions in Stand-alone Libraries
16299
16300 @noindent
16301 The pragmas listed below should be used with caution inside libraries,
16302 as they can create incompatibilities with other Ada libraries:
16303 @itemize @bullet
16304 @item pragma @code{Locking_Policy}
16305 @item pragma @code{Queuing_Policy}
16306 @item pragma @code{Task_Dispatching_Policy}
16307 @item pragma @code{Unreserve_All_Interrupts}
16308 @end itemize
16309
16310 @noindent
16311 When using a library that contains such pragmas, the user must make sure
16312 that all libraries use the same pragmas with the same values. Otherwise,
16313 @code{Program_Error} will
16314 be raised during the elaboration of the conflicting
16315 libraries. The usage of these pragmas and its consequences for the user
16316 should therefore be well documented.
16317
16318 Similarly, the traceback in the exception occurrence mechanism should be
16319 enabled or disabled in a consistent manner across all libraries.
16320 Otherwise, Program_Error will be raised during the elaboration of the
16321 conflicting libraries.
16322
16323 If the @code{Version} or @code{Body_Version}
16324 attributes are used inside a library, then you need to
16325 perform a @code{gnatbind} step that specifies all @file{ALI} files in all
16326 libraries, so that version identifiers can be properly computed.
16327 In practice these attributes are rarely used, so this is unlikely
16328 to be a consideration.
16329
16330 @node  Rebuilding the GNAT Run-Time Library
16331 @section Rebuilding the GNAT Run-Time Library
16332 @cindex GNAT Run-Time Library, rebuilding
16333 @cindex Building the GNAT Run-Time Library
16334 @cindex Rebuilding the GNAT Run-Time Library
16335 @cindex Run-Time Library, rebuilding
16336
16337 @noindent
16338 It may be useful to recompile the GNAT library in various contexts, the
16339 most important one being the use of partition-wide configuration pragmas
16340 such as @code{Normalize_Scalars}. A special Makefile called
16341 @code{Makefile.adalib} is provided to that effect and can be found in
16342 the directory containing the GNAT library. The location of this
16343 directory depends on the way the GNAT environment has been installed and can
16344 be determined by means of the command:
16345
16346 @smallexample
16347 $ gnatls -v
16348 @end smallexample
16349
16350 @noindent
16351 The last entry in the object search path usually contains the
16352 gnat library. This Makefile contains its own documentation and in
16353 particular the set of instructions needed to rebuild a new library and
16354 to use it.
16355
16356 @node Using the GNU make Utility
16357 @chapter Using the GNU @code{make} Utility
16358 @findex make
16359
16360 @noindent
16361 This chapter offers some examples of makefiles that solve specific
16362 problems. It does not explain how to write a makefile (@pxref{Top,, GNU
16363 make, make, GNU @code{make}}), nor does it try to replace the
16364 @command{gnatmake} utility (@pxref{The GNAT Make Program gnatmake}).
16365
16366 All the examples in this section are specific to the GNU version of
16367 make. Although @command{make} is a standard utility, and the basic language
16368 is the same, these examples use some advanced features found only in
16369 @code{GNU make}.
16370
16371 @menu
16372 * Using gnatmake in a Makefile::
16373 * Automatically Creating a List of Directories::
16374 * Generating the Command Line Switches::
16375 * Overcoming Command Line Length Limits::
16376 @end menu
16377
16378 @node Using gnatmake in a Makefile
16379 @section Using gnatmake in a Makefile
16380 @findex makefile
16381 @cindex GNU make
16382
16383 @noindent
16384 Complex project organizations can be handled in a very powerful way by
16385 using GNU make combined with gnatmake. For instance, here is a Makefile
16386 which allows you to build each subsystem of a big project into a separate
16387 shared library. Such a makefile allows you to significantly reduce the link
16388 time of very big applications while maintaining full coherence at
16389 each step of the build process.
16390
16391 The list of dependencies are handled automatically by
16392 @command{gnatmake}. The Makefile is simply used to call gnatmake in each of
16393 the appropriate directories.
16394
16395 Note that you should also read the example on how to automatically
16396 create the list of directories
16397 (@pxref{Automatically Creating a List of Directories})
16398 which might help you in case your project has a lot of subdirectories.
16399
16400 @smallexample
16401 @iftex
16402 @leftskip=0cm
16403 @font@heightrm=cmr8
16404 @heightrm
16405 @end iftex
16406 ## This Makefile is intended to be used with the following directory
16407 ## configuration:
16408 ##  - The sources are split into a series of csc (computer software components)
16409 ##    Each of these csc is put in its own directory.
16410 ##    Their name are referenced by the directory names.
16411 ##    They will be compiled into shared library (although this would also work
16412 ##    with static libraries
16413 ##  - The main program (and possibly other packages that do not belong to any
16414 ##    csc is put in the top level directory (where the Makefile is).
16415 ##       toplevel_dir __ first_csc  (sources) __ lib (will contain the library)
16416 ##                    \_ second_csc (sources) __ lib (will contain the library)
16417 ##                    \_ @dots{}
16418 ## Although this Makefile is build for shared library, it is easy to modify
16419 ## to build partial link objects instead (modify the lines with -shared and
16420 ## gnatlink below)
16421 ##
16422 ## With this makefile, you can change any file in the system or add any new
16423 ## file, and everything will be recompiled correctly (only the relevant shared
16424 ## objects will be recompiled, and the main program will be re-linked).
16425
16426 # The list of computer software component for your project. This might be
16427 # generated automatically.
16428 CSC_LIST=aa bb cc
16429
16430 # Name of the main program (no extension)
16431 MAIN=main
16432
16433 # If we need to build objects with -fPIC, uncomment the following line
16434 #NEED_FPIC=-fPIC
16435
16436 # The following variable should give the directory containing libgnat.so
16437 # You can get this directory through 'gnatls -v'. This is usually the last
16438 # directory in the Object_Path.
16439 GLIB=@dots{}
16440
16441 # The directories for the libraries
16442 # (This macro expands the list of CSC to the list of shared libraries, you
16443 # could simply use the expanded form:
16444 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
16445 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
16446
16447 $@{MAIN@}: objects $@{LIB_DIR@}
16448     gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
16449     gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
16450
16451 objects::
16452     # recompile the sources
16453     gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
16454
16455 # Note: In a future version of GNAT, the following commands will be simplified
16456 # by a new tool, gnatmlib
16457 $@{LIB_DIR@}:
16458     mkdir -p $@{dir $@@ @}
16459     cd $@{dir $@@ @} && gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
16460     cd $@{dir $@@ @} && cp -f ../*.ali .
16461
16462 # The dependencies for the modules
16463 # Note that we have to force the expansion of *.o, since in some cases
16464 # make won't be able to do it itself.
16465 aa/lib/libaa.so: $@{wildcard aa/*.o@}
16466 bb/lib/libbb.so: $@{wildcard bb/*.o@}
16467 cc/lib/libcc.so: $@{wildcard cc/*.o@}
16468
16469 # Make sure all of the shared libraries are in the path before starting the
16470 # program
16471 run::
16472     LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
16473
16474 clean::
16475     $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
16476     $@{RM@} $@{CSC_LIST:%=%/*.ali@}
16477     $@{RM@} $@{CSC_LIST:%=%/*.o@}
16478     $@{RM@} *.o *.ali $@{MAIN@}
16479 @end smallexample
16480
16481 @node Automatically Creating a List of Directories
16482 @section Automatically Creating a List of Directories
16483
16484 @noindent
16485 In most makefiles, you will have to specify a list of directories, and
16486 store it in a variable. For small projects, it is often easier to
16487 specify each of them by hand, since you then have full control over what
16488 is the proper order for these directories, which ones should be
16489 included.
16490
16491 However, in larger projects, which might involve hundreds of
16492 subdirectories, it might be more convenient to generate this list
16493 automatically.
16494
16495 The example below presents two methods. The first one, although less
16496 general, gives you more control over the list. It involves wildcard
16497 characters, that are automatically expanded by @command{make}. Its
16498 shortcoming is that you need to explicitly specify some of the
16499 organization of your project, such as for instance the directory tree
16500 depth, whether some directories are found in a separate tree, @enddots{}
16501
16502 The second method is the most general one. It requires an external
16503 program, called @command{find}, which is standard on all Unix systems. All
16504 the directories found under a given root directory will be added to the
16505 list.
16506
16507 @smallexample
16508 @iftex
16509 @leftskip=0cm
16510 @font@heightrm=cmr8
16511 @heightrm
16512 @end iftex
16513 # The examples below are based on the following directory hierarchy:
16514 # All the directories can contain any number of files
16515 # ROOT_DIRECTORY ->  a  ->  aa  ->  aaa
16516 #                       ->  ab
16517 #                       ->  ac
16518 #                ->  b  ->  ba  ->  baa
16519 #                       ->  bb
16520 #                       ->  bc
16521 # This Makefile creates a variable called DIRS, that can be reused any time
16522 # you need this list (see the other examples in this section)
16523
16524 # The root of your project's directory hierarchy
16525 ROOT_DIRECTORY=.
16526
16527 ####
16528 # First method: specify explicitly the list of directories
16529 # This allows you to specify any subset of all the directories you need.
16530 ####
16531
16532 DIRS := a/aa/ a/ab/ b/ba/
16533
16534 ####
16535 # Second method: use wildcards
16536 # Note that the argument(s) to wildcard below should end with a '/'.
16537 # Since wildcards also return file names, we have to filter them out
16538 # to avoid duplicate directory names.
16539 # We thus use make's @code{dir} and @code{sort} functions.
16540 # It sets DIRs to the following value (note that the directories aaa and baa
16541 # are not given, unless you change the arguments to wildcard).
16542 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
16543 ####
16544
16545 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
16546                     $@{ROOT_DIRECTORY@}/*/*/@}@}@}
16547
16548 ####
16549 # Third method: use an external program
16550 # This command is much faster if run on local disks, avoiding NFS slowdowns.
16551 # This is the most complete command: it sets DIRs to the following value:
16552 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
16553 ####
16554
16555 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
16556
16557 @end smallexample
16558
16559 @node Generating the Command Line Switches
16560 @section Generating the Command Line Switches
16561
16562 @noindent
16563 Once you have created the list of directories as explained in the
16564 previous section (@pxref{Automatically Creating a List of Directories}),
16565 you can easily generate the command line arguments to pass to gnatmake.
16566
16567 For the sake of completeness, this example assumes that the source path
16568 is not the same as the object path, and that you have two separate lists
16569 of directories.
16570
16571 @smallexample
16572 # see "Automatically creating a list of directories" to create
16573 # these variables
16574 SOURCE_DIRS=
16575 OBJECT_DIRS=
16576
16577 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
16578 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
16579
16580 all:
16581         gnatmake $@{GNATMAKE_SWITCHES@} main_unit
16582 @end smallexample
16583
16584 @node Overcoming Command Line Length Limits
16585 @section Overcoming Command Line Length Limits
16586
16587 @noindent
16588 One problem that might be encountered on big projects is that many
16589 operating systems limit the length of the command line. It is thus hard to give
16590 gnatmake the list of source and object directories.
16591
16592 This example shows how you can set up environment variables, which will
16593 make @command{gnatmake} behave exactly as if the directories had been
16594 specified on the command line, but have a much higher length limit (or
16595 even none on most systems).
16596
16597 It assumes that you have created a list of directories in your Makefile,
16598 using one of the methods presented in
16599 @ref{Automatically Creating a List of Directories}.
16600 For the sake of completeness, we assume that the object
16601 path (where the ALI files are found) is different from the sources patch.
16602
16603 Note a small trick in the Makefile below: for efficiency reasons, we
16604 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
16605 expanded immediately by @code{make}. This way we overcome the standard
16606 make behavior which is to expand the variables only when they are
16607 actually used.
16608
16609 On Windows, if you are using the standard Windows command shell, you must
16610 replace colons with semicolons in the assignments to these variables.
16611
16612 @smallexample
16613 @iftex
16614 @leftskip=0cm
16615 @font@heightrm=cmr8
16616 @heightrm
16617 @end iftex
16618 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECTS_PATH.
16619 # This is the same thing as putting the -I arguments on the command line.
16620 # (the equivalent of using -aI on the command line would be to define
16621 #  only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECTS_PATH).
16622 # You can of course have different values for these variables.
16623 #
16624 # Note also that we need to keep the previous values of these variables, since
16625 # they might have been set before running 'make' to specify where the GNAT
16626 # library is installed.
16627
16628 # see "Automatically creating a list of directories" to create these
16629 # variables
16630 SOURCE_DIRS=
16631 OBJECT_DIRS=
16632
16633 empty:=
16634 space:=$@{empty@} $@{empty@}
16635 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
16636 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
16637 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
16638 ADA_OBJECTS_PATH += $@{OBJECT_LIST@}
16639 export ADA_INCLUDE_PATH
16640 export ADA_OBJECTS_PATH
16641
16642 all:
16643         gnatmake main_unit
16644 @end smallexample
16645 @end ifclear
16646
16647 @node Memory Management Issues
16648 @chapter Memory Management Issues
16649
16650 @noindent
16651 This chapter describes some useful memory pools provided in the GNAT library
16652 and in particular the GNAT Debug Pool facility, which can be used to detect
16653 incorrect uses of access values (including ``dangling references'').
16654 @ifclear vms
16655 It also describes the @command{gnatmem} tool, which can be used to track down
16656 ``memory leaks''.
16657 @end ifclear
16658
16659 @menu
16660 * Some Useful Memory Pools::
16661 * The GNAT Debug Pool Facility::
16662 @ifclear vms
16663 * The gnatmem Tool::
16664 @end ifclear
16665 @end menu
16666
16667 @node Some Useful Memory Pools
16668 @section Some Useful Memory Pools
16669 @findex Memory Pool
16670 @cindex storage, pool
16671
16672 @noindent
16673 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
16674 storage pool. Allocations use the standard system call @code{malloc} while
16675 deallocations use the standard system call @code{free}. No reclamation is
16676 performed when the pool goes out of scope. For performance reasons, the
16677 standard default Ada allocators/deallocators do not use any explicit storage
16678 pools but if they did, they could use this storage pool without any change in
16679 behavior. That is why this storage pool is used  when the user
16680 manages to make the default implicit allocator explicit as in this example:
16681 @smallexample @c ada
16682    type T1 is access Something;
16683     -- no Storage pool is defined for T2
16684    type T2 is access Something_Else;
16685    for T2'Storage_Pool use T1'Storage_Pool;
16686    -- the above is equivalent to
16687    for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
16688 @end smallexample
16689
16690 @noindent
16691 The @code{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
16692 pool. The allocation strategy is similar to @code{Pool_Local}'s
16693 except that the all
16694 storage allocated with this pool is reclaimed when the pool object goes out of
16695 scope. This pool provides a explicit mechanism similar to the implicit one
16696 provided by several Ada 83 compilers for allocations performed through a local
16697 access type and whose purpose was to reclaim memory when exiting the
16698 scope of a given local access. As an example, the following program does not
16699 leak memory even though it does not perform explicit deallocation:
16700
16701 @smallexample @c ada
16702 with System.Pool_Local;
16703 procedure Pooloc1 is
16704    procedure Internal is
16705       type A is access Integer;
16706       X : System.Pool_Local.Unbounded_Reclaim_Pool;
16707       for A'Storage_Pool use X;
16708       v : A;
16709    begin
16710       for I in  1 .. 50 loop
16711          v := new Integer;
16712       end loop;
16713    end Internal;
16714 begin
16715    for I in  1 .. 100 loop
16716       Internal;
16717    end loop;
16718 end Pooloc1;
16719 @end smallexample
16720
16721 @noindent
16722 The @code{System.Pool_Size} package implements the Stack_Bounded_Pool used when
16723 @code{Storage_Size} is specified for an access type.
16724 The whole storage for the pool is
16725 allocated at once, usually on the stack at the point where the access type is
16726 elaborated. It is automatically reclaimed when exiting the scope where the
16727 access type is defined. This package is not intended to be used directly by the
16728 user and it is implicitly used for each such declaration:
16729
16730 @smallexample @c ada
16731    type T1 is access Something;
16732    for T1'Storage_Size use 10_000;
16733 @end smallexample
16734
16735 @node The GNAT Debug Pool Facility
16736 @section The GNAT Debug Pool Facility
16737 @findex Debug Pool
16738 @cindex storage, pool, memory corruption
16739
16740 @noindent
16741 The use of unchecked deallocation and unchecked conversion can easily
16742 lead to incorrect memory references. The problems generated by such
16743 references are usually difficult to tackle because the symptoms can be
16744 very remote from the origin of the problem. In such cases, it is
16745 very helpful to detect the problem as early as possible. This is the
16746 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
16747
16748 In order to use the GNAT specific debugging pool, the user must
16749 associate a debug pool object with each of the access types that may be
16750 related to suspected memory problems. See Ada Reference Manual 13.11.
16751 @smallexample @c ada
16752 type Ptr is access Some_Type;
16753 Pool : GNAT.Debug_Pools.Debug_Pool;
16754 for Ptr'Storage_Pool use Pool;
16755 @end smallexample
16756
16757 @noindent
16758 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
16759 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
16760 allow the user to redefine allocation and deallocation strategies. They
16761 also provide a checkpoint for each dereference, through the use of
16762 the primitive operation @code{Dereference} which is implicitly called at
16763 each dereference of an access value.
16764
16765 Once an access type has been associated with a debug pool, operations on
16766 values of the type may raise four distinct exceptions,
16767 which correspond to four potential kinds of memory corruption:
16768 @itemize @bullet
16769 @item
16770 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
16771 @item
16772 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
16773 @item
16774 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
16775 @item
16776 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
16777 @end itemize
16778
16779 @noindent
16780 For types associated with a Debug_Pool, dynamic allocation is performed using
16781 the standard GNAT allocation routine. References to all allocated chunks of
16782 memory are kept in an internal dictionary. Several deallocation strategies are
16783 provided, whereupon the user can choose to release the memory to the system,
16784 keep it allocated for further invalid access checks, or fill it with an easily
16785 recognizable pattern for debug sessions. The memory pattern is the old IBM
16786 hexadecimal convention: @code{16#DEADBEEF#}.
16787
16788 See the documentation in the file g-debpoo.ads for more information on the
16789 various strategies.
16790
16791 Upon each dereference, a check is made that the access value denotes a
16792 properly allocated memory location. Here is a complete example of use of
16793 @code{Debug_Pools}, that includes typical instances of  memory corruption:
16794 @smallexample @c ada
16795 @iftex
16796 @leftskip=0cm
16797 @end iftex
16798 with Gnat.Io; use Gnat.Io;
16799 with Unchecked_Deallocation;
16800 with Unchecked_Conversion;
16801 with GNAT.Debug_Pools;
16802 with System.Storage_Elements;
16803 with Ada.Exceptions; use Ada.Exceptions;
16804 procedure Debug_Pool_Test is
16805
16806    type T is access Integer;
16807    type U is access all T;
16808
16809    P : GNAT.Debug_Pools.Debug_Pool;
16810    for T'Storage_Pool use P;
16811
16812    procedure Free is new Unchecked_Deallocation (Integer, T);
16813    function UC is new Unchecked_Conversion (U, T);
16814    A, B : aliased T;
16815
16816    procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
16817
16818 begin
16819    Info (P);
16820    A := new Integer;
16821    B := new Integer;
16822    B := A;
16823    Info (P);
16824    Free (A);
16825    begin
16826       Put_Line (Integer'Image(B.all));
16827    exception
16828       when E : others => Put_Line ("raised: " & Exception_Name (E));
16829    end;
16830    begin
16831       Free (B);
16832    exception
16833       when E : others => Put_Line ("raised: " & Exception_Name (E));
16834    end;
16835    B := UC(A'Access);
16836    begin
16837       Put_Line (Integer'Image(B.all));
16838    exception
16839       when E : others => Put_Line ("raised: " & Exception_Name (E));
16840    end;
16841    begin
16842       Free (B);
16843    exception
16844       when E : others => Put_Line ("raised: " & Exception_Name (E));
16845    end;
16846    Info (P);
16847 end Debug_Pool_Test;
16848 @end smallexample
16849
16850 @noindent
16851 The debug pool mechanism provides the following precise diagnostics on the
16852 execution of this erroneous program:
16853 @smallexample
16854 Debug Pool info:
16855   Total allocated bytes :  0
16856   Total deallocated bytes :  0
16857   Current Water Mark:  0
16858   High Water Mark:  0
16859
16860 Debug Pool info:
16861   Total allocated bytes :  8
16862   Total deallocated bytes :  0
16863   Current Water Mark:  8
16864   High Water Mark:  8
16865
16866 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
16867 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
16868 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
16869 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
16870 Debug Pool info:
16871   Total allocated bytes :  8
16872   Total deallocated bytes :  4
16873   Current Water Mark:  4
16874   High Water Mark:  8
16875 @end smallexample
16876
16877 @ifclear vms
16878 @node The gnatmem Tool
16879 @section The @command{gnatmem} Tool
16880 @findex gnatmem
16881
16882 @noindent
16883 The @code{gnatmem} utility monitors dynamic allocation and
16884 deallocation activity in a program, and displays information about
16885 incorrect deallocations and possible sources of memory leaks.
16886 It is designed to work in association with a static runtime library
16887 only and in this context provides three types of information:
16888 @itemize @bullet
16889 @item
16890 General information concerning memory management, such as the total
16891 number of allocations and deallocations, the amount of allocated
16892 memory and the high water mark, i.e.@: the largest amount of allocated
16893 memory in the course of program execution.
16894
16895 @item
16896 Backtraces for all incorrect deallocations, that is to say deallocations
16897 which do not correspond to a valid allocation.
16898
16899 @item
16900 Information on each allocation that is potentially the origin of a memory
16901 leak.
16902 @end itemize
16903
16904 @menu
16905 * Running gnatmem::
16906 * Switches for gnatmem::
16907 * Example of gnatmem Usage::
16908 @end menu
16909
16910 @node Running gnatmem
16911 @subsection Running @code{gnatmem}
16912
16913 @noindent
16914 @code{gnatmem} makes use of the output created by the special version of
16915 allocation and deallocation routines that record call information. This
16916 allows to obtain accurate dynamic memory usage history at a minimal cost to
16917 the execution speed. Note however, that @code{gnatmem} is not supported on
16918 all platforms (currently, it is supported on AIX, HP-UX, GNU/Linux,
16919 Solaris and Windows NT/2000/XP (x86).
16920
16921 @noindent
16922 The @code{gnatmem} command has the form
16923
16924 @smallexample
16925 @c    $ gnatmem @ovar{switches} user_program
16926 @c Expanding @ovar macro inline (explanation in macro def comments)
16927       $ gnatmem @r{[}@var{switches}@r{]} @var{user_program}
16928 @end smallexample
16929
16930 @noindent
16931 The program must have been linked with the instrumented version of the
16932 allocation and deallocation routines. This is done by linking with the
16933 @file{libgmem.a} library. For correct symbolic backtrace information,
16934 the user program should be compiled with debugging options
16935 (see @ref{Switches for gcc}). For example to build @file{my_program}:
16936
16937 @smallexample
16938 $ gnatmake -g my_program -largs -lgmem
16939 @end smallexample
16940
16941 @noindent
16942 As library @file{libgmem.a} contains an alternate body for package
16943 @code{System.Memory}, @file{s-memory.adb} should not be compiled and linked
16944 when an executable is linked with library @file{libgmem.a}. It is then not
16945 recommended to use @command{gnatmake} with switch @option{^-a^/ALL_FILES^}.
16946
16947 @noindent
16948 When @file{my_program} is executed, the file @file{gmem.out} is produced.
16949 This file contains information about all allocations and deallocations
16950 performed by the program. It is produced by the instrumented allocations and
16951 deallocations routines and will be used by @code{gnatmem}.
16952
16953 In order to produce symbolic backtrace information for allocations and
16954 deallocations performed by the GNAT run-time library, you need to use a
16955 version of that library that has been compiled with the @option{-g} switch
16956 (see @ref{Rebuilding the GNAT Run-Time Library}).
16957
16958 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
16959 examine. If the location of @file{gmem.out} file was not explicitly supplied by
16960 @option{-i} switch, gnatmem will assume that this file can be found in the
16961 current directory. For example, after you have executed @file{my_program},
16962 @file{gmem.out} can be analyzed by @code{gnatmem} using the command:
16963
16964 @smallexample
16965 $ gnatmem my_program
16966 @end smallexample
16967
16968 @noindent
16969 This will produce the output with the following format:
16970
16971 *************** debut cc
16972 @smallexample
16973 $ gnatmem my_program
16974
16975 Global information
16976 ------------------
16977    Total number of allocations        :  45
16978    Total number of deallocations      :   6
16979    Final Water Mark (non freed mem)   :  11.29 Kilobytes
16980    High Water Mark                    :  11.40 Kilobytes
16981
16982 .
16983 .
16984 .
16985 Allocation Root # 2
16986 -------------------
16987  Number of non freed allocations    :  11
16988  Final Water Mark (non freed mem)   :   1.16 Kilobytes
16989  High Water Mark                    :   1.27 Kilobytes
16990  Backtrace                          :
16991    my_program.adb:23 my_program.alloc
16992 .
16993 .
16994 .
16995 @end smallexample
16996
16997 The first block of output gives general information. In this case, the
16998 Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
16999 Unchecked_Deallocation routine occurred.
17000
17001 @noindent
17002 Subsequent paragraphs display  information on all allocation roots.
17003 An allocation root is a specific point in the execution of the program
17004 that generates some dynamic allocation, such as a ``@code{@b{new}}''
17005 construct. This root is represented by an execution backtrace (or subprogram
17006 call stack). By default the backtrace depth for allocations roots is 1, so
17007 that a root corresponds exactly to a source location. The backtrace can
17008 be made deeper, to make the root more specific.
17009
17010 @node Switches for gnatmem
17011 @subsection Switches for @code{gnatmem}
17012
17013 @noindent
17014 @code{gnatmem} recognizes the following switches:
17015
17016 @table @option
17017
17018 @item -q
17019 @cindex @option{-q} (@code{gnatmem})
17020 Quiet. Gives the minimum output needed to identify the origin of the
17021 memory leaks. Omits statistical information.
17022
17023 @item @var{N}
17024 @cindex @var{N} (@code{gnatmem})
17025 N is an integer literal (usually between 1 and 10) which controls the
17026 depth of the backtraces defining allocation root. The default value for
17027 N is 1. The deeper the backtrace, the more precise the localization of
17028 the root. Note that the total number of roots can depend on this
17029 parameter. This parameter must be specified @emph{before} the name of the
17030 executable to be analyzed, to avoid ambiguity.
17031
17032 @item -b n
17033 @cindex @option{-b} (@code{gnatmem})
17034 This switch has the same effect as just depth parameter.
17035
17036 @item -i @var{file}
17037 @cindex @option{-i} (@code{gnatmem})
17038 Do the @code{gnatmem} processing starting from @file{file}, rather than
17039 @file{gmem.out} in the current directory.
17040
17041 @item -m n
17042 @cindex @option{-m} (@code{gnatmem})
17043 This switch causes @code{gnatmem} to mask the allocation roots that have less
17044 than n leaks. The default value is 1. Specifying the value of 0 will allow to
17045 examine even the roots that didn't result in leaks.
17046
17047 @item -s order
17048 @cindex @option{-s} (@code{gnatmem})
17049 This switch causes @code{gnatmem} to sort the allocation roots according to the
17050 specified order of sort criteria, each identified by a single letter. The
17051 currently supported criteria are @code{n, h, w} standing respectively for
17052 number of unfreed allocations, high watermark, and final watermark
17053 corresponding to a specific root. The default order is @code{nwh}.
17054
17055 @end table
17056
17057 @node Example of gnatmem Usage
17058 @subsection Example of @code{gnatmem} Usage
17059
17060 @noindent
17061 The following example shows the use of @code{gnatmem}
17062 on a simple memory-leaking program.
17063 Suppose that we have the following Ada program:
17064
17065 @smallexample @c ada
17066 @group
17067 @cartouche
17068 with Unchecked_Deallocation;
17069 procedure Test_Gm is
17070
17071    type T is array (1..1000) of Integer;
17072    type Ptr is access T;
17073    procedure Free is new Unchecked_Deallocation (T, Ptr);
17074    A : Ptr;
17075
17076    procedure My_Alloc is
17077    begin
17078       A := new T;
17079    end My_Alloc;
17080
17081    procedure My_DeAlloc is
17082       B : Ptr := A;
17083    begin
17084       Free (B);
17085    end My_DeAlloc;
17086
17087 begin
17088    My_Alloc;
17089    for I in 1 .. 5 loop
17090       for J in I .. 5 loop
17091          My_Alloc;
17092       end loop;
17093       My_Dealloc;
17094    end loop;
17095 end;
17096 @end cartouche
17097 @end group
17098 @end smallexample
17099
17100 @noindent
17101 The program needs to be compiled with debugging option and linked with
17102 @code{gmem} library:
17103
17104 @smallexample
17105 $ gnatmake -g test_gm -largs -lgmem
17106 @end smallexample
17107
17108 @noindent
17109 Then we execute the program as usual:
17110
17111 @smallexample
17112 $ test_gm
17113 @end smallexample
17114
17115 @noindent
17116 Then @code{gnatmem} is invoked simply with
17117 @smallexample
17118 $ gnatmem test_gm
17119 @end smallexample
17120
17121 @noindent
17122 which produces the following output (result may vary on different platforms):
17123
17124 @smallexample
17125 Global information
17126 ------------------
17127    Total number of allocations        :  18
17128    Total number of deallocations      :   5
17129    Final Water Mark (non freed mem)   :  53.00 Kilobytes
17130    High Water Mark                    :  56.90 Kilobytes
17131
17132 Allocation Root # 1
17133 -------------------
17134  Number of non freed allocations    :  11
17135  Final Water Mark (non freed mem)   :  42.97 Kilobytes
17136  High Water Mark                    :  46.88 Kilobytes
17137  Backtrace                          :
17138    test_gm.adb:11 test_gm.my_alloc
17139
17140 Allocation Root # 2
17141 -------------------
17142  Number of non freed allocations    :   1
17143  Final Water Mark (non freed mem)   :  10.02 Kilobytes
17144  High Water Mark                    :  10.02 Kilobytes
17145  Backtrace                          :
17146    s-secsta.adb:81 system.secondary_stack.ss_init
17147
17148 Allocation Root # 3
17149 -------------------
17150  Number of non freed allocations    :   1
17151  Final Water Mark (non freed mem)   :  12 Bytes
17152  High Water Mark                    :  12 Bytes
17153  Backtrace                          :
17154    s-secsta.adb:181 system.secondary_stack.ss_init
17155 @end smallexample
17156
17157 @noindent
17158 Note that the GNAT run time contains itself a certain number of
17159 allocations that have no  corresponding deallocation,
17160 as shown here for root #2 and root
17161 #3. This is a normal behavior when the number of non-freed allocations
17162 is one, it allocates dynamic data structures that the run time needs for
17163 the complete lifetime of the program. Note also that there is only one
17164 allocation root in the user program with a single line back trace:
17165 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
17166 program shows that 'My_Alloc' is called at 2 different points in the
17167 source (line 21 and line 24). If those two allocation roots need to be
17168 distinguished, the backtrace depth parameter can be used:
17169
17170 @smallexample
17171 $ gnatmem 3 test_gm
17172 @end smallexample
17173
17174 @noindent
17175 which will give the following output:
17176
17177 @smallexample
17178 Global information
17179 ------------------
17180    Total number of allocations        :  18
17181    Total number of deallocations      :   5
17182    Final Water Mark (non freed mem)   :  53.00 Kilobytes
17183    High Water Mark                    :  56.90 Kilobytes
17184
17185 Allocation Root # 1
17186 -------------------
17187  Number of non freed allocations    :  10
17188  Final Water Mark (non freed mem)   :  39.06 Kilobytes
17189  High Water Mark                    :  42.97 Kilobytes
17190  Backtrace                          :
17191    test_gm.adb:11 test_gm.my_alloc
17192    test_gm.adb:24 test_gm
17193    b_test_gm.c:52 main
17194
17195 Allocation Root # 2
17196 -------------------
17197  Number of non freed allocations    :   1
17198  Final Water Mark (non freed mem)   :  10.02 Kilobytes
17199  High Water Mark                    :  10.02 Kilobytes
17200  Backtrace                          :
17201    s-secsta.adb:81  system.secondary_stack.ss_init
17202    s-secsta.adb:283 <system__secondary_stack___elabb>
17203    b_test_gm.c:33   adainit
17204
17205 Allocation Root # 3
17206 -------------------
17207  Number of non freed allocations    :   1
17208  Final Water Mark (non freed mem)   :   3.91 Kilobytes
17209  High Water Mark                    :   3.91 Kilobytes
17210  Backtrace                          :
17211    test_gm.adb:11 test_gm.my_alloc
17212    test_gm.adb:21 test_gm
17213    b_test_gm.c:52 main
17214
17215 Allocation Root # 4
17216 -------------------
17217  Number of non freed allocations    :   1
17218  Final Water Mark (non freed mem)   :  12 Bytes
17219  High Water Mark                    :  12 Bytes
17220  Backtrace                          :
17221    s-secsta.adb:181 system.secondary_stack.ss_init
17222    s-secsta.adb:283 <system__secondary_stack___elabb>
17223    b_test_gm.c:33   adainit
17224 @end smallexample
17225
17226 @noindent
17227 The allocation root #1 of the first example has been split in 2 roots #1
17228 and #3 thanks to the more precise associated backtrace.
17229
17230 @end ifclear
17231
17232 @node Stack Related Facilities
17233 @chapter Stack Related Facilities
17234
17235 @noindent
17236 This chapter describes some useful tools associated with stack
17237 checking and analysis. In
17238 particular, it deals with dynamic and static stack usage measurements.
17239
17240 @menu
17241 * Stack Overflow Checking::
17242 * Static Stack Usage Analysis::
17243 * Dynamic Stack Usage Analysis::
17244 @end menu
17245
17246 @node Stack Overflow Checking
17247 @section Stack Overflow Checking
17248 @cindex Stack Overflow Checking
17249 @cindex -fstack-check
17250
17251 @noindent
17252 For most operating systems, @command{gcc} does not perform stack overflow
17253 checking by default. This means that if the main environment task or
17254 some other task exceeds the available stack space, then unpredictable
17255 behavior will occur. Most native systems offer some level of protection by
17256 adding a guard page at the end of each task stack. This mechanism is usually
17257 not enough for dealing properly with stack overflow situations because
17258 a large local variable could ``jump'' above the guard page.
17259 Furthermore, when the
17260 guard page is hit, there may not be any space left on the stack for executing
17261 the exception propagation code. Enabling stack checking avoids
17262 such situations.
17263
17264 To activate stack checking, compile all units with the gcc option
17265 @option{-fstack-check}. For example:
17266
17267 @smallexample
17268 gcc -c -fstack-check package1.adb
17269 @end smallexample
17270
17271 @noindent
17272 Units compiled with this option will generate extra instructions to check
17273 that any use of the stack (for procedure calls or for declaring local
17274 variables in declare blocks) does not exceed the available stack space.
17275 If the space is exceeded, then a @code{Storage_Error} exception is raised.
17276
17277 For declared tasks, the stack size is controlled by the size
17278 given in an applicable @code{Storage_Size} pragma or by the value specified
17279 at bind time with @option{-d} (@pxref{Switches for gnatbind}) or is set to
17280 the default size as defined in the GNAT runtime otherwise.
17281
17282 For the environment task, the stack size depends on
17283 system defaults and is unknown to the compiler. Stack checking
17284 may still work correctly if a fixed
17285 size stack is allocated, but this cannot be guaranteed.
17286 @ifclear vms
17287 To ensure that a clean exception is signalled for stack
17288 overflow, set the environment variable
17289 @env{GNAT_STACK_LIMIT} to indicate the maximum
17290 stack area that can be used, as in:
17291 @cindex GNAT_STACK_LIMIT
17292
17293 @smallexample
17294 SET GNAT_STACK_LIMIT 1600
17295 @end smallexample
17296
17297 @noindent
17298 The limit is given in kilobytes, so the above declaration would
17299 set the stack limit of the environment task to 1.6 megabytes.
17300 Note that the only purpose of this usage is to limit the amount
17301 of stack used by the environment task. If it is necessary to
17302 increase the amount of stack for the environment task, then this
17303 is an operating systems issue, and must be addressed with the
17304 appropriate operating systems commands.
17305 @end ifclear
17306 @ifset vms
17307 To have a fixed size stack in the environment task, the stack must be put
17308 in the P0 address space and its size specified.  Use these switches to
17309 create a p0 image:
17310
17311 @smallexample
17312 gnatmake my_progs -largs "-Wl,--opt=STACK=4000,/p0image"
17313 @end smallexample
17314
17315 @noindent
17316 The quotes are required to keep case.  The number after @samp{STACK=} is the
17317 size of the environmental task stack in pagelets (512 bytes).  In this example
17318 the stack size is about 2 megabytes.
17319
17320 @noindent
17321 A consequence of the @option{/p0image} qualifier is also to makes RMS buffers
17322 be placed in P0 space.  Refer to @cite{HP OpenVMS Linker Utility Manual} for
17323 more details about the @option{/p0image} qualifier and the @option{stack}
17324 option.
17325
17326 @noindent
17327 On Itanium platforms, you can instead assign the @samp{GNAT_STACK_SIZE} and
17328 @samp{GNAT_RBS_SIZE} logicals to the size of the primary and register
17329 stack in kilobytes.  For example:
17330
17331 @smallexample
17332 $ define GNAT_RBS_SIZE 1024 ! Limit the RBS size to 1MB.
17333 @end smallexample
17334 @end ifset
17335
17336 @node Static Stack Usage Analysis
17337 @section Static Stack Usage Analysis
17338 @cindex Static Stack Usage Analysis
17339 @cindex -fstack-usage
17340
17341 @noindent
17342 A unit compiled with @option{-fstack-usage} will generate an extra file
17343 that specifies
17344 the maximum amount of stack used, on a per-function basis.
17345 The file has the same
17346 basename as the target object file with a @file{.su} extension.
17347 Each line of this file is made up of three fields:
17348
17349 @itemize
17350 @item
17351 The name of the function.
17352 @item
17353 A number of bytes.
17354 @item
17355 One or more qualifiers: @code{static}, @code{dynamic}, @code{bounded}.
17356 @end itemize
17357
17358 The second field corresponds to the size of the known part of the function
17359 frame.
17360
17361 The qualifier @code{static} means that the function frame size
17362 is purely static.
17363 It usually means that all local variables have a static size.
17364 In this case, the second field is a reliable measure of the function stack
17365 utilization.
17366
17367 The qualifier @code{dynamic} means that the function frame size is not static.
17368 It happens mainly when some local variables have a dynamic size. When this
17369 qualifier appears alone, the second field is not a reliable measure
17370 of the function stack analysis. When it is qualified with  @code{bounded}, it
17371 means that the second field is a reliable maximum of the function stack
17372 utilization.
17373
17374 A unit compiled with @option{-Wstack-usage} will issue a warning for each
17375 subprogram whose stack usage might be larger than the specified amount of
17376 bytes.  The wording is in keeping with the qualifier documented above.
17377
17378 @node Dynamic Stack Usage Analysis
17379 @section Dynamic Stack Usage Analysis
17380
17381 @noindent
17382 It is possible to measure the maximum amount of stack used by a task, by
17383 adding a switch to @command{gnatbind}, as:
17384
17385 @smallexample
17386 $ gnatbind -u0 file
17387 @end smallexample
17388
17389 @noindent
17390 With this option, at each task termination, its stack usage is  output on
17391 @file{stderr}.
17392 It is not always convenient to output the stack usage when the program
17393 is still running. Hence, it is possible to delay this output until program
17394 termination. for a given number of tasks specified as the argument of the
17395 @option{-u} option. For instance:
17396
17397 @smallexample
17398 $ gnatbind -u100 file
17399 @end smallexample
17400
17401 @noindent
17402 will buffer the stack usage information of the first 100 tasks to terminate and
17403 output this info at program termination. Results are displayed in four
17404 columns:
17405
17406 @noindent
17407 Index | Task Name | Stack Size | Stack Usage
17408
17409 @noindent
17410 where:
17411
17412 @table @emph
17413 @item Index
17414 is a number associated with each task.
17415
17416 @item Task Name
17417 is the name of the task analyzed.
17418
17419 @item Stack Size
17420 is the maximum size for the stack.
17421
17422 @item Stack Usage
17423 is the measure done by the stack analyzer. In order to prevent overflow, the stack
17424 is not entirely analyzed, and it's not possible to know exactly how
17425 much has actually been used.
17426
17427 @end table
17428
17429 @noindent
17430 The environment task stack, e.g., the stack that contains the main unit, is
17431 only processed when the environment variable GNAT_STACK_LIMIT is set.
17432
17433 @noindent
17434 The package @code{GNAT.Task_Stack_Usage} provides facilities to get
17435 stack usage reports at run-time. See its body for the details.
17436
17437 @c *********************************
17438 @c *            GNATCHECK          *
17439 @c *********************************
17440 @node Verifying Properties Using gnatcheck
17441 @chapter Verifying Properties Using @command{gnatcheck}
17442 @findex gnatcheck
17443 @cindex @command{gnatcheck}
17444
17445 @noindent
17446 The @command{gnatcheck} tool is an ASIS-based utility that checks properties
17447 of Ada source files according to a given set of semantic rules.
17448 @cindex ASIS
17449
17450 In order to check compliance with a given rule, @command{gnatcheck} has to
17451 semantically analyze the Ada sources.
17452 Therefore, checks can only be performed on
17453 legal Ada units. Moreover, when a unit depends semantically upon units located
17454 outside the current directory, the source search path has to be provided when
17455 calling @command{gnatcheck}, either through a specified project file or
17456 through @command{gnatcheck} switches.
17457
17458 For full details, refer to @cite{GNATcheck Reference Manual} document.
17459
17460
17461 @c *********************************
17462 @node Creating Sample Bodies Using gnatstub
17463 @chapter Creating Sample Bodies Using @command{gnatstub}
17464 @findex gnatstub
17465
17466 @noindent
17467 @command{gnatstub} creates body stubs, that is, empty but compilable bodies
17468 for library unit declarations.
17469
17470 Note: to invoke @code{gnatstub} with a project file, use the @code{gnat}
17471 driver (see @ref{The GNAT Driver and Project Files}).
17472
17473 To create a body stub, @command{gnatstub} has to compile the library
17474 unit declaration. Therefore, bodies can be created only for legal
17475 library units. Moreover, if a library unit depends semantically upon
17476 units located outside the current directory, you have to provide
17477 the source search path when calling @command{gnatstub}, see the description
17478 of @command{gnatstub} switches below.
17479
17480 By default, all the program unit body stubs generated by @code{gnatstub}
17481 raise the predefined @code{Program_Error} exception, which will catch
17482 accidental calls of generated stubs. This behavior can be changed with
17483 option @option{^--no-exception^/NO_EXCEPTION^} (see below).
17484
17485 @menu
17486 * Running gnatstub::
17487 * Switches for gnatstub::
17488 @end menu
17489
17490 @node Running gnatstub
17491 @section Running @command{gnatstub}
17492
17493 @noindent
17494 @command{gnatstub} has the command-line interface of the form
17495
17496 @smallexample
17497 @c $ gnatstub @ovar{switches} @var{filename} @ovar{directory}
17498 @c Expanding @ovar macro inline (explanation in macro def comments)
17499 $ gnatstub @r{[}@var{switches}@r{]} @var{filename} @r{[}@var{directory}@r{]} @r{[}-cargs @var{gcc_switches}@r{]}
17500 @end smallexample
17501
17502 @noindent
17503 where
17504 @table @var
17505 @item filename
17506 is the name of the source file that contains a library unit declaration
17507 for which a body must be created. The file name may contain the path
17508 information.
17509 The file name does not have to follow the GNAT file name conventions. If the
17510 name
17511 does not follow GNAT file naming conventions, the name of the body file must
17512 be provided
17513 explicitly as the value of the @option{^-o^/BODY=^@var{body-name}} option.
17514 If the file name follows the GNAT file naming
17515 conventions and the name of the body file is not provided,
17516 @command{gnatstub}
17517 creates the name
17518 of the body file from the argument file name by replacing the @file{.ads}
17519 suffix
17520 with the @file{.adb} suffix.
17521
17522 @item directory
17523 indicates the directory in which the body stub is to be placed (the default
17524 is the
17525 current directory)
17526
17527 @item @samp{@var{gcc_switches}} is a list of switches for
17528 @command{gcc}. They will be passed on to all compiler invocations made by
17529 @command{gnatstub} to generate the ASIS trees. Here you can provide
17530 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
17531 use the @option{-gnatec} switch to set the configuration file,
17532 use the @option{-gnat05} switch if sources should be compiled in
17533 Ada 2005 mode etc.
17534
17535 @item switches
17536 is an optional sequence of switches as described in the next section
17537 @end table
17538
17539 @node Switches for gnatstub
17540 @section Switches for @command{gnatstub}
17541
17542 @table @option
17543 @c !sort!
17544
17545 @item ^-f^/FULL^
17546 @cindex @option{^-f^/FULL^} (@command{gnatstub})
17547 If the destination directory already contains a file with the name of the
17548 body file
17549 for the argument spec file, replace it with the generated body stub.
17550
17551 @item ^-hs^/HEADER=SPEC^
17552 @cindex @option{^-hs^/HEADER=SPEC^} (@command{gnatstub})
17553 Put the comment header (i.e., all the comments preceding the
17554 compilation unit) from the source of the library unit declaration
17555 into the body stub.
17556
17557 @item ^-hg^/HEADER=GENERAL^
17558 @cindex @option{^-hg^/HEADER=GENERAL^} (@command{gnatstub})
17559 Put a sample comment header into the body stub.
17560
17561 @item ^--header-file=@var{filename}^/FROM_HEADER_FILE=@var{filename}^
17562 @cindex @option{^--header-file^/FROM_HEADER_FILE=^} (@command{gnatstub})
17563 Use the content of the file as the comment header for a generated body stub.
17564
17565 @ifclear vms
17566 @item -IDIR
17567 @cindex @option{-IDIR} (@command{gnatstub})
17568 @itemx -I-
17569 @cindex @option{-I-} (@command{gnatstub})
17570 @end ifclear
17571 @ifset vms
17572 @item /NOCURRENT_DIRECTORY
17573 @cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub})
17574 @end ifset
17575 ^These switches have ^This switch has^ the same meaning as in calls to
17576 @command{gcc}.
17577 ^They define ^It defines ^ the source search path in the call to
17578 @command{gcc} issued
17579 by @command{gnatstub} to compile an argument source file.
17580
17581 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE=^@var{PATH}
17582 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatstub})
17583 This switch has the same meaning as in calls to @command{gcc}.
17584 It defines the additional configuration file to be passed to the call to
17585 @command{gcc} issued
17586 by @command{gnatstub} to compile an argument source file.
17587
17588 @item ^-gnatyM^/MAX_LINE_LENGTH=^@var{n}
17589 @cindex @option{^-gnatyM^/MAX_LINE_LENGTH^} (@command{gnatstub})
17590 (@var{n} is a non-negative integer). Set the maximum line length in the
17591 body stub to @var{n}; the default is 79. The maximum value that can be
17592 specified is 32767. Note that in the special case of configuration
17593 pragma files, the maximum is always 32767 regardless of whether or
17594 not this switch appears.
17595
17596 @item ^-gnaty^/STYLE_CHECKS=^@var{n}
17597 @cindex @option{^-gnaty^/STYLE_CHECKS=^} (@command{gnatstub})
17598 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
17599 the generated body sample to @var{n}.
17600 The default indentation is 3.
17601
17602 @item ^-gnatyo^/ORDERED_SUBPROGRAMS^
17603 @cindex @option{^-gnato^/ORDERED_SUBPROGRAMS^} (@command{gnatstub})
17604 Order local bodies alphabetically. (By default local bodies are ordered
17605 in the same way as the corresponding local specs in the argument spec file.)
17606
17607 @item ^-i^/INDENTATION=^@var{n}
17608 @cindex @option{^-i^/INDENTATION^} (@command{gnatstub})
17609 Same as @option{^-gnaty^/STYLE_CHECKS=^@var{n}}
17610
17611 @item ^-k^/TREE_FILE=SAVE^
17612 @cindex @option{^-k^/TREE_FILE=SAVE^} (@command{gnatstub})
17613 Do not remove the tree file (i.e., the snapshot of the compiler internal
17614 structures used by @command{gnatstub}) after creating the body stub.
17615
17616 @item ^-l^/LINE_LENGTH=^@var{n}
17617 @cindex @option{^-l^/LINE_LENGTH^} (@command{gnatstub})
17618 Same as @option{^-gnatyM^/MAX_LINE_LENGTH=^@var{n}}
17619
17620 @item ^--no-exception^/NO_EXCEPTION^
17621 @cindex @option{^--no-exception^/NO_EXCEPTION^} (@command{gnatstub})
17622 Avoid raising PROGRAM_ERROR in the generated bodies of program unit stubs.
17623 This is not always possible for function stubs.
17624
17625 @item ^--no-local-header^/NO_LOCAL_HEADER^
17626 @cindex @option{^--no-local-header^/NO_LOCAL_HEADER^} (@command{gnatstub})
17627 Do not place local comment header with unit name before body stub for a
17628 unit.
17629
17630 @item ^-o ^/BODY=^@var{body-name}
17631 @cindex @option{^-o^/BODY^} (@command{gnatstub})
17632 Body file name.  This should be set if the argument file name does not
17633 follow
17634 the GNAT file naming
17635 conventions. If this switch is omitted the default name for the body will be
17636 obtained
17637 from the argument file name according to the GNAT file naming conventions.
17638
17639 @item ^-q^/QUIET^
17640 @cindex @option{^-q^/QUIET^} (@command{gnatstub})
17641 Quiet mode: do not generate a confirmation when a body is
17642 successfully created, and do not generate a message when a body is not
17643 required for an
17644 argument unit.
17645
17646 @item ^-r^/TREE_FILE=REUSE^
17647 @cindex @option{^-r^/TREE_FILE=REUSE^} (@command{gnatstub})
17648 Reuse the tree file (if it exists) instead of creating it.  Instead of
17649 creating the tree file for the library unit declaration, @command{gnatstub}
17650 tries to find it in the current directory and use it for creating
17651 a body. If the tree file is not found, no body is created. This option
17652 also implies @option{^-k^/SAVE^}, whether or not
17653 the latter is set explicitly.
17654
17655 @item ^-t^/TREE_FILE=OVERWRITE^
17656 @cindex @option{^-t^/TREE_FILE=OVERWRITE^} (@command{gnatstub})
17657 Overwrite the existing tree file.  If the current directory already
17658 contains the file which, according to the GNAT file naming rules should
17659 be considered as a tree file for the argument source file,
17660 @command{gnatstub}
17661 will refuse to create the tree file needed to create a sample body
17662 unless this option is set.
17663
17664 @item ^-v^/VERBOSE^
17665 @cindex @option{^-v^/VERBOSE^} (@command{gnatstub})
17666 Verbose mode: generate version information.
17667
17668 @end table
17669
17670 @c *********************************
17671 @node Creating Unit Tests Using gnattest
17672 @chapter Creating Unit Tests Using @command{gnattest}
17673 @findex gnattest
17674
17675 @noindent
17676 @command{gnattest} is an ASIS-based utility that creates unit tests stubs
17677 as well as a test driver infrastructure (harness). @command{gnattest} creates
17678 a stub for each visible subprogram in the packages under consideration when
17679 they do not exist already.
17680
17681 In order to process source files from the project, @command{gnattest} has to
17682 semantically analyze these Ada sources. Therefore, test stubs can only be
17683 generated for legal Ada units. If a unit is dependent on some other units,
17684 those units should be among source files of the project or of other projects
17685 imported by this one.
17686
17687 Generated stubs and harness are based on the AUnit testing framework. AUnit is
17688 an Ada adaptation of the xxxUnit testing frameworks similar to JUnit for Java or
17689 CppUnit for C++. While it is advised that gnattest users read AUnit manual, deep
17690 knowledge of AUnit is not necessary for using gnattest. For correct operation of
17691 @command{gnattest} AUnit should be installed and aunit.gpr must be on the
17692 project path. This happens automatically when Aunit is installed at its default
17693 location.
17694 @menu
17695 * Running gnattest::
17696 * Switches for gnattest::
17697 * Project Attributes for gnattest::
17698 * Simple Example::
17699 * Setting Up and Tearing Down Testing Environment::
17700 * Regenerating Tests::
17701 * Default Test Behavior::
17702 * Testing Primitive Operations of Tagged Types::
17703 * Test Inheritance::
17704 * Tagged Types Substitutability Testing::
17705 * Testing with Contracts::
17706 * Additional Tests::
17707 * Current Limitations::
17708 @end menu
17709
17710 @node Running gnattest
17711 @section Running @command{gnattest}
17712
17713 @noindent
17714 @command{gnattest} has the command-line interface of the form
17715
17716 @smallexample
17717 @c $ gnattest @var{-Pprojname} @ovar{switches} @ovar{filename} @ovar{directory}
17718 @c Expanding @ovar macro inline (explanation in macro def comments)
17719 $ gnattest @var{-Pprojname} @r{[}@var{--harness-dir=dirname}@r{]} @r{[}@var{switches}@r{]} @r{[}@var{filename}@r{]} @r{[}-cargs @var{gcc_switches}@r{]}
17720 @end smallexample
17721
17722 @noindent
17723 where
17724 @table @var
17725
17726 @item -Pprojname
17727 specifies the project that allow locating the source files. When no [filenames]
17728 are provided on the command line, all project sources are used as input. This
17729 switch is mandatory.
17730
17731 @item --harness-dir=dirname
17732 specifies directory to put harness packages and project file for the test
17733 driver. The harness dir should be either specified by that switch or by
17734 corresponding attribute in the argument project file.
17735
17736 @item filename
17737 is the name of the source file that contains a library unit package declaration
17738 for which a test package must be created. The file name may contain the path
17739 information.
17740
17741 @item @samp{@var{gcc_switches}} is a list of switches for
17742 @command{gcc}. They will be passed on to all compiler invocations made by
17743 @command{gnatstub} to generate the ASIS trees. Here you can provide
17744 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
17745 use the @option{-gnatec} switch to set the configuration file,
17746 use the @option{-gnat05} switch if sources should be compiled in
17747 Ada 2005 mode etc.
17748
17749 @item switches
17750 is an optional sequence of switches as described in the next section
17751
17752 @end table
17753
17754 @command{gnattest} results can be found in two different places.
17755
17756 @itemize @bullet
17757 @item automatic harness
17758 the harnessing code which is located in the harness-dir as specified on the
17759 comand line or in the project file. All this code is generated completely
17760 automatically and can be destroyed and regenerated at will. It is not
17761 recommended to modify manually this code since it might be overridden
17762 easily. The entry point in this harnessing code is the project file called
17763 @command{test_driver.gpr}. Tests can be compiled and run using a command
17764 such as:
17765
17766 @smallexample
17767 gnatmake -P<harness-dir>/test_driver
17768 test_runner
17769 @end smallexample
17770
17771 @item actual unit test stubs
17772 a test stub for each visible subprogram is created in a separate file, if it
17773 doesn't exist already. By default, those separate test files are located in a
17774 "tests" directory that is created in the directory containing the source file
17775 itself. if it is not appropriate to create the tests in subdirs of the source,
17776 option @option{--separate-root} can be used. So let say for instance that
17777 a source file my_unit.ads in directory src contains a visible subprogram Proc.
17778 Then, the corresponding unit test will be found in file
17779 src/tests/my_unit-tests-proc_<code>.adb. <code> is an signature encoding used to
17780 differentiate test names in case of overloading.
17781 @end itemize
17782
17783 @node Switches for gnattest
17784 @section Switches for @command{gnattest}
17785
17786 @table @option
17787 @c !sort!
17788
17789 @item --harness-only
17790 @cindex @option{--harness-only} (@command{gnattest})
17791 When this option is given, @command{gnattest} creates a harness for all
17792 sources treating them as test packages.
17793
17794 @item --additional-tests=@var{projname}
17795 @cindex @option{--additional-tests} (@command{gnattest})
17796 Sources described in @var{projname} are considered potential additional
17797 manual tests to be added to the test suite.
17798
17799 @item -r
17800 @cindex @option{-r} (@command{gnattest})
17801 Consider recursively all sources from all projects.
17802
17803 @item -q
17804 @cindex @option{-q} (@command{gnattest})
17805 Supresses non-critical output messages.
17806
17807 @item -v
17808 @cindex @option{-v} (@command{gnattest})
17809 Verbose mode: generate version information.
17810
17811 @item --liskov
17812 @cindex @option{--liskov} (@command{gnattest})
17813 Enables Liskov verification: run all tests from all parents in order
17814 to check substitutability.
17815
17816 @item --stub-default=@var{val}
17817 @cindex @option{--stub-default} (@command{gnattest})
17818 Specifies the default behavior of generated stubs. @var{val} can be either
17819 "fail" or "pass", "fail" being the default.
17820
17821 @item --separate-root=@var{dirname}
17822 @cindex @option{--separate-root} (@command{gnattest})
17823 Directory hierarchy of tested sources is recreated in the @var{dirname} directory,
17824 test packages are placed in corresponding dirs.
17825
17826 @item --subdir=@var{dirname}
17827 @cindex @option{--subdir} (@command{gnattest})
17828 Test packages are placed in subdirectories. That's the default output mode since
17829 it does not require any additional input from the user. Subdirs called "tests"
17830 will be created by default.
17831
17832 @end table
17833
17834 @option{--separate_root} and @option{--subdir} switches are mutually exclusive.
17835
17836 @node Project Attributes for gnattest
17837 @section Project Attributes for @command{gnattest}
17838
17839 @noindent
17840
17841 Most of the command line options can be also given to the tool by adding
17842 special attributes to the project file. Those attributes should be put in
17843 package gnattest. Here is the list of the attributes.
17844
17845 @itemize @bullet
17846
17847 @item Separate_Stub_Root
17848 is used to select the same output mode as with the --separate-root option.
17849 This attribute cannot be used togather with Stub_Subdir.
17850
17851 @item Stub_Subdir
17852 is used to select the same output mode as with the --sudbir option.
17853 This attribute cannot be used togather with Separate_Stub_Root.
17854
17855 @item Harness_Dir
17856 is used to specify the directory to place harness packages and project
17857 file for the test driver, otherwise specified by --harness-dir.
17858
17859 @item Additional_Tests
17860 is used to specify the project file otherwise given by
17861 --additional-tests switch.
17862
17863 @item Stubs_Default
17864 is used to specify the default behaviour of test stubs, otherwise
17865 specified by --stub-default option. The value for this attribute
17866 shoul be either "pass" or "fail"
17867
17868 @end itemize
17869
17870 All those attributes can be overridden from command line if needed.
17871 Other @command{gnattest} switches can also be passed via the project
17872 file as an attribute list called GNATtest_Switches.
17873
17874 @node Simple Example
17875 @section Simple Example
17876
17877 @noindent
17878
17879 Let's take a very simple example using the first @command{gnattest} example
17880 located at
17881
17882 @smallexample
17883 <install_prefix>/share/examples/gnattest/simple
17884 @end smallexample
17885
17886 This project contains a simple package containing one subprogram. By running gnattest
17887
17888 @smallexample
17889 $ gnattest --harness-dir=driver -Psimple.gpr
17890 @end smallexample
17891
17892 a test driver is created in dir "driver". It can be compiled and run:
17893
17894 @smallexample
17895 $ cd driver
17896 $ gprbuild -Ptest_driver
17897 $ test_runner
17898 @end smallexample
17899
17900 One failed test with diagnosis "test not implemented" is reported.
17901 Since no special output option was specified the test package Simple.Tests
17902 is located in
17903
17904 @smallexample
17905 <install_prefix>/share/examples/gnattest/simple/src/tests
17906 @end smallexample
17907
17908 For each package containing visible subprograms, a child test package is
17909 generated. It contains one test routine per tested subprogram. Each
17910 declaration of test subprogram has a comment specifying to which tested
17911 subprogram it corresponds. All the test routines have separated bodies.
17912 The test routine locates at simple-tests-test_inc_5eaee3.adb has a single
17913 statement - procedure Assert. It has two arguments: the boolean expression
17914 which we want to check and the diagnosis message to display if the condition
17915 is false.
17916
17917 That is where actual testing code should be written after a proper setup.
17918 An actual check can be performed by replacing the assert statement with
17919
17920 @smallexample @c ada
17921 Assert (Inc (1) = 2, "wrong incrementation");
17922 @end smallexample
17923
17924 After recompiling and running the test driver one successfully passed test
17925 is reported.
17926
17927 @node Setting Up and Tearing Down Testing Environment
17928 @section Setting Up and Tearing Down Testing Environment
17929
17930 @noindent
17931
17932 Besides test routines themselves, each test package has an inner package
17933 Env_Mgmt that has two procedures: User_Set_Up and User_Tear_Down.
17934 User_Set_Up is called before each test routine of the package and
17935 User_Tear_Down is called after each test routine. Those two procedures can
17936 be used to perform necessary initialization and finalization,
17937 memory allocation etc.
17938
17939 @node Regenerating Tests
17940 @section Regenerating Tests
17941
17942 @noindent
17943
17944 Bodies of test routines and env_mgmt packages are never overridden after they
17945 have been created once. As long as the name of the subprogram, full expanded Ada
17946 names and order of its parameters are the same, the old test routine will
17947 fit in it's place and no test stub will be generated for this subprogram.
17948
17949 This can be demonstrated with the previous example. By uncommenting declaration
17950 and body of function Dec in simple.ads and simple.adb, running
17951 @command{gnattest} on the project and then running the test driver:
17952
17953 @smallexample
17954 gnattest --harness-dir=driver -Psimple.gpr
17955 cd driver
17956 gprbuild -Ptest_driver
17957 test_runner
17958 @end smallexample
17959
17960 the old test is not replaced with a stub neither lost but a new test stub is
17961 created for function Dec.
17962
17963 The only way for regenerating tests stubs is t oremove the previously created
17964 tests.
17965
17966 @node Default Test Behavior
17967 @section Default Test Behavior
17968
17969 @noindent
17970
17971 Generated test driver can treat all unimplemented tests in two ways:
17972 either count them all as failed (this is usefull to see which tests are still
17973 left to implement) or as  passed (to sort out unimplemented ones from those
17974 actually failing for a reason).
17975
17976 Test driver accepts a switch to specify this behavior: --stub-default=val,
17977 where val is either "pass" or "fail" (exactly as for @command{gnattest}).
17978
17979 The default behavior of the test driver is set with the same switch
17980 passed to gnattest when generating the test driver.
17981
17982 Passing it to the driver generated on the first example
17983
17984 @smallexample
17985 test_runner --stub-default=pass
17986 @end smallexample
17987
17988 makes both tests pass, even the unimplemented one.
17989
17990 @node Testing Primitive Operations of Tagged Types
17991 @section Testing Primitive Operations of Tagged Types
17992
17993 @noindent
17994
17995 Creating test stubs for primitive operations of tagged types have a number
17996 of features. Test routines for all primitives of a given tagged type are
17997 placed in a separate child package named after the tagged type (so if you
17998 have tagged type T in package P all tests for primitives of T will be in
17999 P.T_Tests).
18000
18001 By running gnattest on the second example (actual tests for this example
18002 are already written so no need to worry if the tool reports that 0 new stubs
18003 were generated).
18004
18005 @smallexample
18006 cd <install_prefix>/share/examples/gnattest/tagged_rec
18007 gnattest --harness-dir=driver -Ptagged_rec.gpr
18008 @end smallexample
18009
18010 Taking a closer look at the test type declared in the test package
18011 Speed1.Controller_Tests is necessary. It is declared in
18012
18013 @smallexample
18014 <install_prefix>/share/examples/gnattest/tagged_rec/src/tests
18015 @end smallexample
18016
18017 Test types are direct or indirect descendants of
18018 AUnit.Test_Fixtures.Test_Fixture type. For non-primitive tested subprograms
18019 there is no need for the user to care about them. However when generating
18020 test packages for primitive operations, there are some things the user
18021 should know.
18022
18023 Type Test_Controller has component that allows to assign it all kinds of
18024 derivations of type Controller. And if you look at the specification of
18025 package Speed2.Auto_Controller, you can see, that Test_Auto_Controller
18026 actually derives from Test_Controller rather that AUnit type Test_Fixture.
18027 Thus test types repeat the hierarchy of tested types.
18028
18029 The User_Set_Up procedure of Env_Mgmt package corresponding to a test package
18030 of primitive operations of type T assigns Fixture with a reference to an
18031 object of that exact type T. Notice however, that if the tagged type has
18032 discriminants, the User_Set_Up only has a commented template of setting
18033 up the fixture since filling the discriminant with actual value is up
18034 to the user.
18035
18036 The knowledge of the structure if test types allows to have additional testing
18037 without additional effort. Those possibilities are described below.
18038
18039 @node Test Inheritance
18040 @section Test Inheritance
18041
18042 @noindent
18043
18044 Since test type hierarchy mimics the hierarchy of tested types, the
18045 inheritance of tests take place. An example of such inheritance can be
18046 shown by running the test driver generated for second example. As previously
18047 mentioned, actual tests are already written for this example.
18048
18049 @smallexample
18050 cd driver
18051 gprbuild -Ptest_driver
18052 test_runner
18053 @end smallexample
18054
18055 There are 6 passed tests while there are only 5 testable subprograms. Test
18056 routine for function Speed has been inherited and ran against objects of the
18057 derived type.
18058
18059 @node Tagged Types Substitutability Testing
18060 @section Tagged Types Substitutability Testing
18061
18062 @noindent
18063
18064 Tagged Types Substitutability Testing is a way of verifying by testing
18065 the Liskov substitution principle (LSP). LSP is a principle stating that if
18066 S is a subtype of T (in Ada, S is a derived type of tagged type T),
18067 then objects of type T may be replaced with objects of type S (i.e., objects
18068 of type S may be substituted for objects of type T), without altering any of
18069 the desirable properties of the program. When the properties of the program are
18070 expressed in the form of subprogram pre & postconditions, LSP is formulated
18071 as relations between the pre & post of primitive operations and the pre & post
18072 of theirs derived operations. The pre of a derived operation should not be
18073 stronger that the original pre, and the post of the derived operation should not
18074 be weaker than the original post. Those relations insure that verifying if a
18075 dyspatching call is safe can be done just with the pre & post of the root
18076 operation.
18077
18078 Verifying LSP by testing consists in running all the unit tests associated with
18079 the primitives of a given tagged type with objects of its derived types.
18080
18081 In the example used by the previous section there clearly have a violation of LSP.
18082 The overriding primitive Adjust_Speed in package Speed2 removes the
18083 functionality of the overridden primitive and thus doesn't respect LSP.
18084 Gnattest has a special option to run
18085 overridden parent tests against objects of the type which have overriding
18086 primitives.
18087
18088 @smallexample
18089 gnattest --harness-dir=driver --liskov -Ptagged_rec.gpr
18090 cd driver
18091 gprbuild -Ptest_driver
18092 test_runner
18093 @end smallexample
18094
18095 While all the tests pass by themselves, the parent test for Adjust_Speed fails
18096 against object of derived type.
18097
18098 @node Testing with Contracts
18099 @section Testing with Contracts
18100
18101 @noindent
18102
18103 @command{gnattest} supports pragmas Precondition, Postcondition and Test_Case.
18104 Test routines are generated one per each Test_Case associated with a tested
18105 subprogram. Those test routines have special wrappers for tested functions
18106 that have composition of pre- and postcondition of the subprogram an
18107 "requires" and "ensures" of the Test_Case (depending on the mode pre- and post
18108 either count for Nominal mode or do not for Robustness mode).
18109
18110 The third example demonstrates how it works:
18111
18112 @smallexample
18113 cd <install_prefix>/share/examples/gnattest/contracts
18114 gnattest --harness-dir=driver -Pcontracts.gpr
18115 @end smallexample
18116
18117 Putting actual checks within the range of the contract does not cause any
18118 error reports. For example, for the test routine which corresponds to
18119 test case 1
18120
18121 @smallexample @c ada
18122 Assert (Sqrt (9.0) = 3.0, "wrong sqrt");
18123 @end smallexample
18124
18125 and for the test routine corresponding to test case 2
18126
18127 @smallexample @c ada
18128 Assert (Sqrt (-5.0) = -1.0, "wrong error indication");
18129 @end smallexample
18130
18131 are acceptable:
18132
18133 @smallexample
18134 cd driver
18135 gprbuild -Ptest_driver
18136 test_runner
18137 @end smallexample
18138
18139 However, by by changing 9.0 to 25.0 and 3.0 to 5.0 for example you can get
18140 a precondition violation for test case one. Also by putting any otherwise
18141 correct but positive pair of numbers to the second test routine you can also
18142 get a precondition violation. Postconditions are checked and reported
18143 the same way.
18144
18145 @node Additional Tests
18146 @section Additional Tests
18147
18148 @noindent
18149 @command{gnattest} can add user written tests to the main suite of the test
18150 driver. @command{gnattest} traverses given packages and searches for test
18151 routines. All procedures with a single in out parameter of a type which is
18152 a derivation of AUnit.Test_Fixtures.Test_Fixture declared in package
18153 specifications are added to the suites and then are executed by test driver.
18154 (Set_Up and Tear_Down are filtered out).
18155
18156 An example illustrates two ways of crating test harness for user written tests.
18157 Directory additional contains a AUnit based test driver written by hand.
18158
18159 @smallexample
18160 <install_prefix>/share/examples/gnattest/additional_tests/
18161 @end smallexample
18162
18163 To create a test driver for already written tests use --harness-only option:
18164
18165 @smallexample
18166 gnattest -Padditional/harness/harness.gpr --harness-dir=harness_only \
18167   --harness-only
18168 gnatmake -Pharness_only/test_driver.gpr
18169 harness_only/test_runner
18170 @end smallexample
18171
18172 Additional tests can also be executed together withgenerated tests:
18173
18174 @smallexample
18175 gnattest -Psimple.gpr --additional-tests=additional/harness/harness.gpr \
18176   --harness-dir=mixing
18177 gnatmake -Pmixing/test_driver.gpr
18178 mixing/test_runner
18179 @end smallexample
18180
18181 @node Current Limitations
18182 @section Current Limitations
18183
18184 @noindent
18185
18186 The tool currently does not support following features:
18187
18188 @itemize @bullet
18189 @item generic tests for generic packages and package instantiations
18190 @item tests for protected operations and entries
18191 @item acpects Pre-, Postcondition and Test_Case
18192 @end itemize
18193
18194 @c *********************************
18195 @node Generating Ada Bindings for C and C++ headers
18196 @chapter Generating Ada Bindings for C and C++ headers
18197 @findex binding
18198
18199 @noindent
18200 GNAT now comes with a binding generator for C and C++ headers which is
18201 intended to do 95% of the tedious work of generating Ada specs from C
18202 or C++ header files.
18203
18204 Note that this capability is not intended to generate 100% correct Ada specs,
18205 and will is some cases require manual adjustments, although it can often
18206 be used out of the box in practice.
18207
18208 Some of the known limitations include:
18209
18210 @itemize @bullet
18211 @item only very simple character constant macros are translated into Ada
18212 constants. Function macros (macros with arguments) are partially translated
18213 as comments, to be completed manually if needed.
18214 @item some extensions (e.g. vector types) are not supported
18215 @item pointers to pointers or complex structures are mapped to System.Address
18216 @item identifiers with identical name (except casing) will generate compilation
18217       errors (e.g. @code{shm_get} vs @code{SHM_GET}).
18218 @end itemize
18219
18220 The code generated is using the Ada 2005 syntax, which makes it
18221 easier to interface with other languages than previous versions of Ada.
18222
18223 @menu
18224 * Running the binding generator::
18225 * Generating bindings for C++ headers::
18226 * Switches::
18227 @end menu
18228
18229 @node Running the binding generator
18230 @section Running the binding generator
18231
18232 @noindent
18233 The binding generator is part of the @command{gcc} compiler and can be
18234 invoked via the @option{-fdump-ada-spec} switch, which will generate Ada
18235 spec files for the header files specified on the command line, and all
18236 header files needed by these files transitively. For example:
18237
18238 @smallexample
18239 $ g++ -c -fdump-ada-spec -C /usr/include/time.h
18240 $ gcc -c -gnat05 *.ads
18241 @end smallexample
18242
18243 will generate, under GNU/Linux, the following files: @file{time_h.ads},
18244 @file{bits_time_h.ads}, @file{stddef_h.ads}, @file{bits_types_h.ads} which
18245 correspond to the files @file{/usr/include/time.h},
18246 @file{/usr/include/bits/time.h}, etc@dots{}, and will then compile in Ada 2005
18247 mode these Ada specs.
18248
18249 The @code{-C} switch tells @command{gcc} to extract comments from headers,
18250 and will attempt to generate corresponding Ada comments.
18251
18252 If you want to generate a single Ada file and not the transitive closure, you
18253 can use instead the @option{-fdump-ada-spec-slim} switch.
18254
18255 Note that we recommend when possible to use the @command{g++} driver to
18256 generate bindings, even for most C headers, since this will in general
18257 generate better Ada specs. For generating bindings for C++ headers, it is
18258 mandatory to use the @command{g++} command, or @command{gcc -x c++} which
18259 is equivalent in this case. If @command{g++} cannot work on your C headers
18260 because of incompatibilities between C and C++, then you can fallback to
18261 @command{gcc} instead.
18262
18263 For an example of better bindings generated from the C++ front-end,
18264 the name of the parameters (when available) are actually ignored by the C
18265 front-end. Consider the following C header:
18266
18267 @smallexample
18268 extern void foo (int variable);
18269 @end smallexample
18270
18271 with the C front-end, @code{variable} is ignored, and the above is handled as:
18272
18273 @smallexample
18274 extern void foo (int);
18275 @end smallexample
18276
18277 generating a generic:
18278
18279 @smallexample
18280 procedure foo (param1 : int);
18281 @end smallexample
18282
18283 with the C++ front-end, the name is available, and we generate:
18284
18285 @smallexample
18286 procedure foo (variable : int);
18287 @end smallexample
18288
18289 In some cases, the generated bindings will be more complete or more meaningful
18290 when defining some macros, which you can do via the @option{-D} switch. This
18291 is for example the case with @file{Xlib.h} under GNU/Linux:
18292
18293 @smallexample
18294 g++ -c -fdump-ada-spec -DXLIB_ILLEGAL_ACCESS -C /usr/include/X11/Xlib.h
18295 @end smallexample
18296
18297 The above will generate more complete bindings than a straight call without
18298 the @option{-DXLIB_ILLEGAL_ACCESS} switch.
18299
18300 In other cases, it is not possible to parse a header file in a stand alone
18301 manner, because other include files need to be included first. In this
18302 case, the solution is to create a small header file including the needed
18303 @code{#include} and possible @code{#define} directives. For example, to
18304 generate Ada bindings for @file{readline/readline.h}, you need to first
18305 include @file{stdio.h}, so you can create a file with the following two
18306 lines in e.g. @file{readline1.h}:
18307
18308 @smallexample
18309 #include <stdio.h>
18310 #include <readline/readline.h>
18311 @end smallexample
18312
18313 and then generate Ada bindings from this file:
18314
18315 @smallexample
18316 $ g++ -c -fdump-ada-spec readline1.h
18317 @end smallexample
18318
18319 @node Generating bindings for C++ headers
18320 @section Generating bindings for C++ headers
18321
18322 @noindent
18323 Generating bindings for C++ headers is done using the same options, always
18324 with the @command{g++} compiler.
18325
18326 In this mode, C++ classes will be mapped to Ada tagged types, constructors
18327 will be mapped using the @code{CPP_Constructor} pragma, and when possible,
18328 multiple inheritance of abstract classes will be mapped to Ada interfaces
18329 (@xref{Interfacing to C++,,,gnat_rm, GNAT Reference Manual}, for additional
18330 information on interfacing to C++).
18331
18332 For example, given the following C++ header file:
18333
18334 @smallexample
18335 @group
18336 @cartouche
18337 class Carnivore @{
18338 public:
18339    virtual int Number_Of_Teeth () = 0;
18340 @};
18341
18342 class Domestic @{
18343 public:
18344    virtual void Set_Owner (char* Name) = 0;
18345 @};
18346
18347 class Animal @{
18348 public:
18349   int Age_Count;
18350   virtual void Set_Age (int New_Age);
18351 @};
18352
18353 class Dog : Animal, Carnivore, Domestic @{
18354  public:
18355   int  Tooth_Count;
18356   char *Owner;
18357
18358   virtual int  Number_Of_Teeth ();
18359   virtual void Set_Owner (char* Name);
18360
18361   Dog();
18362 @};
18363 @end cartouche
18364 @end group
18365 @end smallexample
18366
18367 The corresponding Ada code is generated:
18368
18369 @smallexample @c ada
18370 @group
18371 @cartouche
18372   package Class_Carnivore is
18373     type Carnivore is limited interface;
18374     pragma Import (CPP, Carnivore);
18375
18376     function Number_Of_Teeth (this : access Carnivore) return int is abstract;
18377   end;
18378   use Class_Carnivore;
18379
18380   package Class_Domestic is
18381     type Domestic is limited interface;
18382     pragma Import (CPP, Domestic);
18383
18384     procedure Set_Owner
18385       (this : access Domestic;
18386        Name : Interfaces.C.Strings.chars_ptr) is abstract;
18387   end;
18388   use Class_Domestic;
18389
18390   package Class_Animal is
18391     type Animal is tagged limited record
18392       Age_Count : aliased int;
18393     end record;
18394     pragma Import (CPP, Animal);
18395
18396     procedure Set_Age (this : access Animal; New_Age : int);
18397     pragma Import (CPP, Set_Age, "_ZN6Animal7Set_AgeEi");
18398   end;
18399   use Class_Animal;
18400
18401   package Class_Dog is
18402     type Dog is new Animal and Carnivore and Domestic with record
18403       Tooth_Count : aliased int;
18404       Owner : Interfaces.C.Strings.chars_ptr;
18405     end record;
18406     pragma Import (CPP, Dog);
18407
18408     function Number_Of_Teeth (this : access Dog) return int;
18409     pragma Import (CPP, Number_Of_Teeth, "_ZN3Dog15Number_Of_TeethEv");
18410
18411     procedure Set_Owner
18412       (this : access Dog; Name : Interfaces.C.Strings.chars_ptr);
18413     pragma Import (CPP, Set_Owner, "_ZN3Dog9Set_OwnerEPc");
18414
18415     function New_Dog return Dog;
18416     pragma CPP_Constructor (New_Dog);
18417     pragma Import (CPP, New_Dog, "_ZN3DogC1Ev");
18418   end;
18419   use Class_Dog;
18420 @end cartouche
18421 @end group
18422 @end smallexample
18423
18424 @node Switches
18425 @section Switches
18426
18427 @table @option
18428 @item -fdump-ada-spec
18429 @cindex @option{-fdump-ada-spec} (@command{gcc})
18430 Generate Ada spec files for the given header files transitively (including
18431 all header files that these headers depend upon).
18432
18433 @item -fdump-ada-spec-slim
18434 @cindex @option{-fdump-ada-spec-slim} (@command{gcc})
18435 Generate Ada spec files for the header files specified on the command line
18436 only.
18437
18438 @item -C
18439 @cindex @option{-C} (@command{gcc})
18440 Extract comments from headers and generate Ada comments in the Ada spec files.
18441 @end table
18442
18443 @node Other Utility Programs
18444 @chapter Other Utility Programs
18445
18446 @noindent
18447 This chapter discusses some other utility programs available in the Ada
18448 environment.
18449
18450 @menu
18451 * Using Other Utility Programs with GNAT::
18452 * The External Symbol Naming Scheme of GNAT::
18453 * Converting Ada Files to html with gnathtml::
18454 * Installing gnathtml::
18455 @ifset vms
18456 * LSE::
18457 * Profiling::
18458 @end ifset
18459 @end menu
18460
18461 @node Using Other Utility Programs with GNAT
18462 @section Using Other Utility Programs with GNAT
18463
18464 @noindent
18465 The object files generated by GNAT are in standard system format and in
18466 particular the debugging information uses this format. This means
18467 programs generated by GNAT can be used with existing utilities that
18468 depend on these formats.
18469
18470 @ifclear vms
18471 In general, any utility program that works with C will also often work with
18472 Ada programs generated by GNAT. This includes software utilities such as
18473 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
18474 as Purify.
18475 @end ifclear
18476
18477 @node The External Symbol Naming Scheme of GNAT
18478 @section The External Symbol Naming Scheme of GNAT
18479
18480 @noindent
18481 In order to interpret the output from GNAT, when using tools that are
18482 originally intended for use with other languages, it is useful to
18483 understand the conventions used to generate link names from the Ada
18484 entity names.
18485
18486 All link names are in all lowercase letters. With the exception of library
18487 procedure names, the mechanism used is simply to use the full expanded
18488 Ada name with dots replaced by double underscores. For example, suppose
18489 we have the following package spec:
18490
18491 @smallexample @c ada
18492 @group
18493 @cartouche
18494 package QRS is
18495    MN : Integer;
18496 end QRS;
18497 @end cartouche
18498 @end group
18499 @end smallexample
18500
18501 @noindent
18502 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
18503 the corresponding link name is @code{qrs__mn}.
18504 @findex Export
18505 Of course if a @code{pragma Export} is used this may be overridden:
18506
18507 @smallexample @c ada
18508 @group
18509 @cartouche
18510 package Exports is
18511    Var1 : Integer;
18512    pragma Export (Var1, C, External_Name => "var1_name");
18513    Var2 : Integer;
18514    pragma Export (Var2, C, Link_Name => "var2_link_name");
18515 end Exports;
18516 @end cartouche
18517 @end group
18518 @end smallexample
18519
18520 @noindent
18521 In this case, the link name for @var{Var1} is whatever link name the
18522 C compiler would assign for the C function @var{var1_name}. This typically
18523 would be either @var{var1_name} or @var{_var1_name}, depending on operating
18524 system conventions, but other possibilities exist. The link name for
18525 @var{Var2} is @var{var2_link_name}, and this is not operating system
18526 dependent.
18527
18528 @findex _main
18529 One exception occurs for library level procedures. A potential ambiguity
18530 arises between the required name @code{_main} for the C main program,
18531 and the name we would otherwise assign to an Ada library level procedure
18532 called @code{Main} (which might well not be the main program).
18533
18534 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
18535 names. So if we have a library level procedure such as
18536
18537 @smallexample @c ada
18538 @group
18539 @cartouche
18540 procedure Hello (S : String);
18541 @end cartouche
18542 @end group
18543 @end smallexample
18544
18545 @noindent
18546 the external name of this procedure will be @var{_ada_hello}.
18547
18548
18549 @node Converting Ada Files to html with gnathtml
18550 @section Converting Ada Files to HTML with @code{gnathtml}
18551
18552 @noindent
18553 This @code{Perl} script allows Ada source files to be browsed using
18554 standard Web browsers. For installation procedure, see the section
18555 @xref{Installing gnathtml}.
18556
18557 Ada reserved keywords are highlighted in a bold font and Ada comments in
18558 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
18559 switch to suppress the generation of cross-referencing information, user
18560 defined variables and types will appear in a different color; you will
18561 be able to click on any identifier and go to its declaration.
18562
18563 The command line is as follow:
18564 @smallexample
18565 @c $ perl gnathtml.pl @ovar{^switches^options^} @var{ada-files}
18566 @c Expanding @ovar macro inline (explanation in macro def comments)
18567 $ perl gnathtml.pl @r{[}@var{^switches^options^}@r{]} @var{ada-files}
18568 @end smallexample
18569
18570 @noindent
18571 You can pass it as many Ada files as you want. @code{gnathtml} will generate
18572 an html file for every ada file, and a global file called @file{index.htm}.
18573 This file is an index of every identifier defined in the files.
18574
18575 The available ^switches^options^ are the following ones:
18576
18577 @table @option
18578 @item -83
18579 @cindex @option{-83} (@code{gnathtml})
18580 Only the Ada 83 subset of keywords will be highlighted.
18581
18582 @item -cc @var{color}
18583 @cindex @option{-cc} (@code{gnathtml})
18584 This option allows you to change the color used for comments. The default
18585 value is green. The color argument can be any name accepted by html.
18586
18587 @item -d
18588 @cindex @option{-d} (@code{gnathtml})
18589 If the Ada files depend on some other files (for instance through
18590 @code{with} clauses, the latter files will also be converted to html.
18591 Only the files in the user project will be converted to html, not the files
18592 in the run-time library itself.
18593
18594 @item -D
18595 @cindex @option{-D} (@code{gnathtml})
18596 This command is the same as @option{-d} above, but @command{gnathtml} will
18597 also look for files in the run-time library, and generate html files for them.
18598
18599 @item -ext @var{extension}
18600 @cindex @option{-ext} (@code{gnathtml})
18601 This option allows you to change the extension of the generated HTML files.
18602 If you do not specify an extension, it will default to @file{htm}.
18603
18604 @item -f
18605 @cindex @option{-f} (@code{gnathtml})
18606 By default, gnathtml will generate html links only for global entities
18607 ('with'ed units, global variables and types,@dots{}).  If you specify
18608 @option{-f} on the command line, then links will be generated for local
18609 entities too.
18610
18611 @item -l @var{number}
18612 @cindex @option{-l} (@code{gnathtml})
18613 If this ^switch^option^ is provided and @var{number} is not 0, then
18614 @code{gnathtml} will number the html files every @var{number} line.
18615
18616 @item -I @var{dir}
18617 @cindex @option{-I} (@code{gnathtml})
18618 Specify a directory to search for library files (@file{.ALI} files) and
18619 source files. You can provide several -I switches on the command line,
18620 and the directories will be parsed in the order of the command line.
18621
18622 @item -o @var{dir}
18623 @cindex @option{-o} (@code{gnathtml})
18624 Specify the output directory for html files. By default, gnathtml will
18625 saved the generated html files in a subdirectory named @file{html/}.
18626
18627 @item -p @var{file}
18628 @cindex @option{-p} (@code{gnathtml})
18629 If you are using Emacs and the most recent Emacs Ada mode, which provides
18630 a full Integrated Development Environment for compiling, checking,
18631 running and debugging applications, you may use @file{.gpr} files
18632 to give the directories where Emacs can find sources and object files.
18633
18634 Using this ^switch^option^, you can tell gnathtml to use these files.
18635 This allows you to get an html version of your application, even if it
18636 is spread over multiple directories.
18637
18638 @item -sc @var{color}
18639 @cindex @option{-sc} (@code{gnathtml})
18640 This ^switch^option^ allows you to change the color used for symbol
18641 definitions.
18642 The default value is red. The color argument can be any name accepted by html.
18643
18644 @item -t @var{file}
18645 @cindex @option{-t} (@code{gnathtml})
18646 This ^switch^option^ provides the name of a file. This file contains a list of
18647 file names to be converted, and the effect is exactly as though they had
18648 appeared explicitly on the command line. This
18649 is the recommended way to work around the command line length limit on some
18650 systems.
18651
18652 @end table
18653
18654 @node Installing gnathtml
18655 @section Installing @code{gnathtml}
18656
18657 @noindent
18658 @code{Perl} needs to be installed on your machine to run this script.
18659 @code{Perl} is freely available for almost every architecture and
18660 Operating System via the Internet.
18661
18662 On Unix systems, you  may want to modify  the  first line of  the script
18663 @code{gnathtml},  to explicitly  tell  the Operating  system  where Perl
18664 is. The syntax of this line is:
18665 @smallexample
18666 #!full_path_name_to_perl
18667 @end smallexample
18668
18669 @noindent
18670 Alternatively, you may run the script using the following command line:
18671
18672 @smallexample
18673 @c $ perl gnathtml.pl @ovar{switches} @var{files}
18674 @c Expanding @ovar macro inline (explanation in macro def comments)
18675 $ perl gnathtml.pl @r{[}@var{switches}@r{]} @var{files}
18676 @end smallexample
18677
18678 @ifset vms
18679 @node LSE
18680 @section LSE
18681 @findex LSE
18682
18683 @noindent
18684 The GNAT distribution provides an Ada 95 template for the HP Language
18685 Sensitive Editor (LSE), a component of DECset. In order to
18686 access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
18687
18688 @node Profiling
18689 @section Profiling
18690 @findex PCA
18691
18692 @noindent
18693 GNAT supports The HP Performance Coverage Analyzer (PCA), a component
18694 of DECset. To use it proceed as outlined under ``HELP PCA'', except for running
18695 the collection phase with the /DEBUG qualifier.
18696
18697 @smallexample
18698 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
18699 $ DEFINE LIB$DEBUG PCA$COLLECTOR
18700 $ RUN/DEBUG <PROGRAM_NAME>
18701 @end smallexample
18702 @noindent
18703 @end ifset
18704
18705 @ifclear vms
18706 @c ******************************
18707 @node Code Coverage and Profiling
18708 @chapter Code Coverage and Profiling
18709 @cindex Code Coverage
18710 @cindex Profiling
18711
18712 @noindent
18713 This chapter describes how to use @code{gcov} - coverage testing tool - and
18714 @code{gprof} - profiler tool - on your Ada programs.
18715
18716 @menu
18717 * Code Coverage of Ada Programs using gcov::
18718 * Profiling an Ada Program using gprof::
18719 @end menu
18720
18721 @node Code Coverage of Ada Programs using gcov
18722 @section Code Coverage of Ada Programs using gcov
18723 @cindex gcov
18724 @cindex -fprofile-arcs
18725 @cindex -ftest-coverage
18726 @cindex -coverage
18727 @cindex Code Coverage
18728
18729 @noindent
18730 @code{gcov} is a test coverage program: it analyzes the execution of a given
18731 program on selected tests, to help you determine the portions of the program
18732 that are still untested.
18733
18734 @code{gcov} is part of the GCC suite, and is described in detail in the GCC
18735 User's Guide. You can refer to this documentation for a more complete
18736 description.
18737
18738 This chapter provides a quick startup guide, and
18739 details some Gnat-specific features.
18740
18741 @menu
18742 * Quick startup guide::
18743 * Gnat specifics::
18744 @end menu
18745
18746 @node Quick startup guide
18747 @subsection Quick startup guide
18748
18749 In order to perform coverage analysis of a program using @code{gcov}, 3
18750 steps are needed:
18751
18752 @itemize @bullet
18753 @item
18754 Code instrumentation during the compilation process
18755 @item
18756 Execution of the instrumented program
18757 @item
18758 Execution of the @code{gcov} tool to generate the result.
18759 @end itemize
18760
18761 The code instrumentation needed by gcov is created at the object level:
18762 The source code is not modified in any way, because the instrumentation code is
18763 inserted by gcc during the compilation process. To compile your code with code
18764 coverage activated, you need to recompile your whole project using the
18765 switches
18766 @code{-fprofile-arcs} and @code{-ftest-coverage}, and link it using
18767 @code{-fprofile-arcs}.
18768
18769 @smallexample
18770 $ gnatmake -P my_project.gpr -f -cargs -fprofile-arcs -ftest-coverage \
18771    -largs -fprofile-arcs
18772 @end smallexample
18773
18774 This compilation process will create @file{.gcno} files together with
18775 the usual object files.
18776
18777 Once the program is compiled with coverage instrumentation, you can
18778 run it as many times as needed - on portions of a test suite for
18779 example. The first execution will produce @file{.gcda} files at the
18780 same location as the @file{.gcno} files.  The following executions
18781 will update those files, so that a cumulative result of the covered
18782 portions of the program is generated.
18783
18784 Finally, you need to call the @code{gcov} tool. The different options of
18785 @code{gcov} are available in the GCC User's Guide, section 'Invoking gcov'.
18786
18787 This will create annotated source files with a @file{.gcov} extension:
18788 @file{my_main.adb} file will be analysed in @file{my_main.adb.gcov}.
18789
18790 @node Gnat specifics
18791 @subsection Gnat specifics
18792
18793 Because Ada semantics, portions of the source code may be shared among
18794 several object files. This is the case for example when generics are
18795 involved, when inlining is active  or when declarations generate  initialisation
18796 calls. In order to take
18797 into account this shared code, you need to call @code{gcov} on all
18798 source files of the tested program at once.
18799
18800 The list of source files might exceed the system's maximum command line
18801 length. In order to bypass this limitation, a new mechanism has been
18802 implemented in @code{gcov}: you can now list all your project's files into a
18803 text file, and provide this file to gcov as a parameter,  preceded by a @@
18804 (e.g. @samp{gcov @@mysrclist.txt}).
18805
18806 Note that on AIX compiling a static library with @code{-fprofile-arcs} is
18807 not supported as there can be unresolved symbols during the final link.
18808
18809 @node Profiling an Ada Program using gprof
18810 @section Profiling an Ada Program using gprof
18811 @cindex gprof
18812 @cindex -pg
18813 @cindex Profiling
18814
18815 @noindent
18816 This section is not meant to be an exhaustive documentation of @code{gprof}.
18817 Full documentation for it can be found in the GNU Profiler User's Guide
18818 documentation that is part of this GNAT distribution.
18819
18820 Profiling a program helps determine the parts of a program that are executed
18821 most often, and are therefore the most time-consuming.
18822
18823 @code{gprof} is the standard GNU profiling tool; it has been enhanced to
18824 better handle Ada programs and multitasking.
18825 It is currently supported on the following platforms
18826 @itemize @bullet
18827 @item
18828 linux x86/x86_64
18829 @item
18830 solaris sparc/sparc64/x86
18831 @item
18832 windows x86
18833 @end itemize
18834
18835 @noindent
18836 In order to profile a program using @code{gprof}, 3 steps are needed:
18837
18838 @itemize @bullet
18839 @item
18840 Code instrumentation, requiring a full recompilation of the project with the
18841 proper switches.
18842 @item
18843 Execution of the program under the analysis conditions, i.e. with the desired
18844 input.
18845 @item
18846 Analysis of the results using the @code{gprof} tool.
18847 @end itemize
18848
18849 @noindent
18850 The following sections detail the different steps, and indicate how
18851 to interpret the results:
18852 @menu
18853 * Compilation for profiling::
18854 * Program execution::
18855 * Running gprof::
18856 * Interpretation of profiling results::
18857 @end menu
18858
18859 @node Compilation for profiling
18860 @subsection Compilation for profiling
18861 @cindex -pg
18862 @cindex Profiling
18863
18864 In order to profile a program the first step is to tell the compiler
18865 to generate the necessary profiling information. The compiler switch to be used
18866 is @code{-pg}, which must be added to other compilation switches. This
18867 switch needs to be specified both during compilation and link stages, and can
18868 be specified once when using gnatmake:
18869
18870 @smallexample
18871 gnatmake -f -pg -P my_project
18872 @end smallexample
18873
18874 @noindent
18875 Note that only the objects that were compiled with the @samp{-pg} switch will
18876 be profiled; if you need to profile your whole project, use the @samp{-f}
18877 gnatmake switch to force full recompilation.
18878
18879 @node Program execution
18880 @subsection Program execution
18881
18882 @noindent
18883 Once the program has been compiled for profiling, you can run it as usual.
18884
18885 The only constraint imposed by profiling is that the program must terminate
18886 normally. An interrupted program (via a Ctrl-C, kill, etc.) will not be
18887 properly analyzed.
18888
18889 Once the program completes execution, a data file called @file{gmon.out} is
18890 generated in the directory where the program was launched from. If this file
18891 already exists, it will be overwritten.
18892
18893 @node Running gprof
18894 @subsection Running gprof
18895
18896 @noindent
18897 The @code{gprof} tool is called as follow:
18898
18899 @smallexample
18900 gprof my_prog gmon.out
18901 @end smallexample
18902
18903 @noindent
18904 or simpler:
18905
18906 @smallexample
18907 gprof my_prog
18908 @end smallexample
18909
18910 @noindent
18911 The complete form of the gprof command line is the following:
18912
18913 @smallexample
18914 gprof [^switches^options^] [executable [data-file]]
18915 @end smallexample
18916
18917 @noindent
18918 @code{gprof} supports numerous ^switch^options^. The order of these
18919 ^switch^options^ does not matter. The full list of options can be found in
18920 the GNU Profiler User's Guide documentation that comes with this documentation.
18921
18922 The following is the subset of those switches that is most relevant:
18923
18924 @table @option
18925
18926 @item --demangle[=@var{style}]
18927 @itemx --no-demangle
18928 @cindex @option{--demangle} (@code{gprof})
18929 These options control whether symbol names should be demangled when
18930 printing output.  The default is to demangle C++ symbols.  The
18931 @code{--no-demangle} option may be used to turn off demangling. Different
18932 compilers have different mangling styles.  The optional demangling style
18933 argument can be used to choose an appropriate demangling style for your
18934 compiler, in particular Ada symbols generated by GNAT can be demangled using
18935 @code{--demangle=gnat}.
18936
18937 @item -e @var{function_name}
18938 @cindex @option{-e} (@code{gprof})
18939 The @samp{-e @var{function}} option tells @code{gprof} not to print
18940 information about the function @var{function_name} (and its
18941 children@dots{}) in the call graph.  The function will still be listed
18942 as a child of any functions that call it, but its index number will be
18943 shown as @samp{[not printed]}.  More than one @samp{-e} option may be
18944 given; only one @var{function_name} may be indicated with each @samp{-e}
18945 option.
18946
18947 @item -E @var{function_name}
18948 @cindex @option{-E} (@code{gprof})
18949 The @code{-E @var{function}} option works like the @code{-e} option, but
18950 execution time spent in the function (and children who were not called from
18951 anywhere else), will not be used to compute the percentages-of-time for
18952 the call graph.  More than one @samp{-E} option may be given; only one
18953 @var{function_name} may be indicated with each @samp{-E} option.
18954
18955 @item -f @var{function_name}
18956 @cindex @option{-f} (@code{gprof})
18957 The @samp{-f @var{function}} option causes @code{gprof} to limit the
18958 call graph to the function @var{function_name} and its children (and
18959 their children@dots{}).  More than one @samp{-f} option may be given;
18960 only one @var{function_name} may be indicated with each @samp{-f}
18961 option.
18962
18963 @item -F @var{function_name}
18964 @cindex @option{-F} (@code{gprof})
18965 The @samp{-F @var{function}} option works like the @code{-f} option, but
18966 only time spent in the function and its children (and their
18967 children@dots{}) will be used to determine total-time and
18968 percentages-of-time for the call graph.  More than one @samp{-F} option
18969 may be given; only one @var{function_name} may be indicated with each
18970 @samp{-F} option.  The @samp{-F} option overrides the @samp{-E} option.
18971
18972 @end table
18973
18974 @node Interpretation of profiling results
18975 @subsection Interpretation of profiling results
18976
18977 @noindent
18978
18979 The results of the profiling analysis are represented by two arrays: the
18980 'flat profile' and the 'call graph'. Full documentation of those outputs
18981 can be found in the GNU Profiler User's Guide.
18982
18983 The flat profile shows the time spent in each function of the program, and how
18984 many time it has been called. This allows you to locate easily the most
18985 time-consuming functions.
18986
18987 The call graph shows, for each subprogram, the subprograms that call it,
18988 and the subprograms that it calls. It also provides an estimate of the time
18989 spent in each of those callers/called subprograms.
18990 @end ifclear
18991
18992 @c ******************************
18993 @node Running and Debugging Ada Programs
18994 @chapter Running and Debugging Ada Programs
18995 @cindex Debugging
18996
18997 @noindent
18998 This chapter discusses how to debug Ada programs.
18999 @ifset vms
19000 It applies to GNAT on the Alpha OpenVMS platform;
19001 for I64 OpenVMS please refer to the @cite{OpenVMS Debugger Manual},
19002 since HP has implemented Ada support in the OpenVMS debugger on I64.
19003 @end ifset
19004
19005 An incorrect Ada program may be handled in three ways by the GNAT compiler:
19006
19007 @enumerate
19008 @item
19009 The illegality may be a violation of the static semantics of Ada. In
19010 that case GNAT diagnoses the constructs in the program that are illegal.
19011 It is then a straightforward matter for the user to modify those parts of
19012 the program.
19013
19014 @item
19015 The illegality may be a violation of the dynamic semantics of Ada. In
19016 that case the program compiles and executes, but may generate incorrect
19017 results, or may terminate abnormally with some exception.
19018
19019 @item
19020 When presented with a program that contains convoluted errors, GNAT
19021 itself may terminate abnormally without providing full diagnostics on
19022 the incorrect user program.
19023 @end enumerate
19024
19025 @menu
19026 * The GNAT Debugger GDB::
19027 * Running GDB::
19028 * Introduction to GDB Commands::
19029 * Using Ada Expressions::
19030 * Calling User-Defined Subprograms::
19031 * Using the Next Command in a Function::
19032 * Ada Exceptions::
19033 * Ada Tasks::
19034 * Debugging Generic Units::
19035 * Remote Debugging using gdbserver::
19036 * GNAT Abnormal Termination or Failure to Terminate::
19037 * Naming Conventions for GNAT Source Files::
19038 * Getting Internal Debugging Information::
19039 * Stack Traceback::
19040 @end menu
19041
19042 @cindex Debugger
19043 @findex gdb
19044
19045 @node The GNAT Debugger GDB
19046 @section The GNAT Debugger GDB
19047
19048 @noindent
19049 @code{GDB} is a general purpose, platform-independent debugger that
19050 can be used to debug mixed-language programs compiled with @command{gcc},
19051 and in particular is capable of debugging Ada programs compiled with
19052 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
19053 complex Ada data structures.
19054
19055 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
19056 @ifset vms
19057 located in the GNU:[DOCS] directory,
19058 @end ifset
19059 for full details on the usage of @code{GDB}, including a section on
19060 its usage on programs. This manual should be consulted for full
19061 details. The section that follows is a brief introduction to the
19062 philosophy and use of @code{GDB}.
19063
19064 When GNAT programs are compiled, the compiler optionally writes debugging
19065 information into the generated object file, including information on
19066 line numbers, and on declared types and variables. This information is
19067 separate from the generated code. It makes the object files considerably
19068 larger, but it does not add to the size of the actual executable that
19069 will be loaded into memory, and has no impact on run-time performance. The
19070 generation of debug information is triggered by the use of the
19071 ^-g^/DEBUG^ switch in the @command{gcc} or @command{gnatmake} command
19072 used to carry out the compilations. It is important to emphasize that
19073 the use of these options does not change the generated code.
19074
19075 The debugging information is written in standard system formats that
19076 are used by many tools, including debuggers and profilers. The format
19077 of the information is typically designed to describe C types and
19078 semantics, but GNAT implements a translation scheme which allows full
19079 details about Ada types and variables to be encoded into these
19080 standard C formats. Details of this encoding scheme may be found in
19081 the file exp_dbug.ads in the GNAT source distribution. However, the
19082 details of this encoding are, in general, of no interest to a user,
19083 since @code{GDB} automatically performs the necessary decoding.
19084
19085 When a program is bound and linked, the debugging information is
19086 collected from the object files, and stored in the executable image of
19087 the program. Again, this process significantly increases the size of
19088 the generated executable file, but it does not increase the size of
19089 the executable program itself. Furthermore, if this program is run in
19090 the normal manner, it runs exactly as if the debug information were
19091 not present, and takes no more actual memory.
19092
19093 However, if the program is run under control of @code{GDB}, the
19094 debugger is activated.  The image of the program is loaded, at which
19095 point it is ready to run.  If a run command is given, then the program
19096 will run exactly as it would have if @code{GDB} were not present. This
19097 is a crucial part of the @code{GDB} design philosophy.  @code{GDB} is
19098 entirely non-intrusive until a breakpoint is encountered.  If no
19099 breakpoint is ever hit, the program will run exactly as it would if no
19100 debugger were present. When a breakpoint is hit, @code{GDB} accesses
19101 the debugging information and can respond to user commands to inspect
19102 variables, and more generally to report on the state of execution.
19103
19104 @c **************
19105 @node Running GDB
19106 @section Running GDB
19107
19108 @noindent
19109 This section describes how to initiate the debugger.
19110 @c The above sentence is really just filler, but it was otherwise
19111 @c clumsy to get the first paragraph nonindented given the conditional
19112 @c nature of the description
19113
19114 @ifclear vms
19115 The debugger can be launched from a @code{GPS} menu or
19116 directly from the command line. The description below covers the latter use.
19117 All the commands shown can be used in the @code{GPS} debug console window,
19118 but there are usually more GUI-based ways to achieve the same effect.
19119 @end ifclear
19120
19121 The command to run @code{GDB} is
19122
19123 @smallexample
19124 $ ^gdb program^GDB PROGRAM^
19125 @end smallexample
19126
19127 @noindent
19128 where @code{^program^PROGRAM^} is the name of the executable file. This
19129 activates the debugger and results in a prompt for debugger commands.
19130 The simplest command is simply @code{run}, which causes the program to run
19131 exactly as if the debugger were not present. The following section
19132 describes some of the additional commands that can be given to @code{GDB}.
19133
19134 @c *******************************
19135 @node Introduction to GDB Commands
19136 @section Introduction to GDB Commands
19137
19138 @noindent
19139 @code{GDB} contains a large repertoire of commands.  @xref{Top,,
19140 Debugging with GDB, gdb, Debugging with GDB},
19141 @ifset vms
19142 located in the GNU:[DOCS] directory,
19143 @end ifset
19144 for extensive documentation on the use
19145 of these commands, together with examples of their use. Furthermore,
19146 the command @command{help} invoked from within GDB activates a simple help
19147 facility which summarizes the available commands and their options.
19148 In this section we summarize a few of the most commonly
19149 used commands to give an idea of what @code{GDB} is about. You should create
19150 a simple program with debugging information and experiment with the use of
19151 these @code{GDB} commands on the program as you read through the
19152 following section.
19153
19154 @table @code
19155 @item set args @var{arguments}
19156 The @var{arguments} list above is a list of arguments to be passed to
19157 the program on a subsequent run command, just as though the arguments
19158 had been entered on a normal invocation of the program. The @code{set args}
19159 command is not needed if the program does not require arguments.
19160
19161 @item run
19162 The @code{run} command causes execution of the program to start from
19163 the beginning. If the program is already running, that is to say if
19164 you are currently positioned at a breakpoint, then a prompt will ask
19165 for confirmation that you want to abandon the current execution and
19166 restart.
19167
19168 @item breakpoint @var{location}
19169 The breakpoint command sets a breakpoint, that is to say a point at which
19170 execution will halt and @code{GDB} will await further
19171 commands. @var{location} is
19172 either a line number within a file, given in the format @code{file:linenumber},
19173 or it is the name of a subprogram. If you request that a breakpoint be set on
19174 a subprogram that is overloaded, a prompt will ask you to specify on which of
19175 those subprograms you want to breakpoint. You can also
19176 specify that all of them should be breakpointed. If the program is run
19177 and execution encounters the breakpoint, then the program
19178 stops and @code{GDB} signals that the breakpoint was encountered by
19179 printing the line of code before which the program is halted.
19180
19181 @item catch exception @var{name}
19182 This command causes the program execution to stop whenever exception
19183 @var{name} is raised.  If @var{name} is omitted, then the execution is
19184 suspended when any exception is raised.
19185
19186 @item print @var{expression}
19187 This will print the value of the given expression. Most simple
19188 Ada expression formats are properly handled by @code{GDB}, so the expression
19189 can contain function calls, variables, operators, and attribute references.
19190
19191 @item continue
19192 Continues execution following a breakpoint, until the next breakpoint or the
19193 termination of the program.
19194
19195 @item step
19196 Executes a single line after a breakpoint. If the next statement
19197 is a subprogram call, execution continues into (the first statement of)
19198 the called subprogram.
19199
19200 @item next
19201 Executes a single line. If this line is a subprogram call, executes and
19202 returns from the call.
19203
19204 @item list
19205 Lists a few lines around the current source location. In practice, it
19206 is usually more convenient to have a separate edit window open with the
19207 relevant source file displayed. Successive applications of this command
19208 print subsequent lines. The command can be given an argument which is a
19209 line number, in which case it displays a few lines around the specified one.
19210
19211 @item backtrace
19212 Displays a backtrace of the call chain. This command is typically
19213 used after a breakpoint has occurred, to examine the sequence of calls that
19214 leads to the current breakpoint. The display includes one line for each
19215 activation record (frame) corresponding to an active subprogram.
19216
19217 @item up
19218 At a breakpoint, @code{GDB} can display the values of variables local
19219 to the current frame. The command @code{up} can be used to
19220 examine the contents of other active frames, by moving the focus up
19221 the stack, that is to say from callee to caller, one frame at a time.
19222
19223 @item down
19224 Moves the focus of @code{GDB} down from the frame currently being
19225 examined to the frame of its callee (the reverse of the previous command),
19226
19227 @item frame @var{n}
19228 Inspect the frame with the given number. The value 0 denotes the frame
19229 of the current breakpoint, that is to say the top of the call stack.
19230
19231 @end table
19232
19233 @noindent
19234 The above list is a very short introduction to the commands that
19235 @code{GDB} provides. Important additional capabilities, including conditional
19236 breakpoints, the ability to execute command sequences on a breakpoint,
19237 the ability to debug at the machine instruction level and many other
19238 features are described in detail in @ref{Top,, Debugging with GDB, gdb,
19239 Debugging with GDB}.  Note that most commands can be abbreviated
19240 (for example, c for continue, bt for backtrace).
19241
19242 @node Using Ada Expressions
19243 @section Using Ada Expressions
19244 @cindex Ada expressions
19245
19246 @noindent
19247 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
19248 extensions. The philosophy behind the design of this subset is
19249
19250 @itemize @bullet
19251 @item
19252 That @code{GDB} should provide basic literals and access to operations for
19253 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
19254 leaving more sophisticated computations to subprograms written into the
19255 program (which therefore may be called from @code{GDB}).
19256
19257 @item
19258 That type safety and strict adherence to Ada language restrictions
19259 are not particularly important to the @code{GDB} user.
19260
19261 @item
19262 That brevity is important to the @code{GDB} user.
19263 @end itemize
19264
19265 @noindent
19266 Thus, for brevity, the debugger acts as if there were
19267 implicit @code{with} and @code{use} clauses in effect for all user-written
19268 packages, thus making it unnecessary to fully qualify most names with
19269 their packages, regardless of context. Where this causes ambiguity,
19270 @code{GDB} asks the user's intent.
19271
19272 For details on the supported Ada syntax, see @ref{Top,, Debugging with
19273 GDB, gdb, Debugging with GDB}.
19274
19275 @node Calling User-Defined Subprograms
19276 @section Calling User-Defined Subprograms
19277
19278 @noindent
19279 An important capability of @code{GDB} is the ability to call user-defined
19280 subprograms while debugging. This is achieved simply by entering
19281 a subprogram call statement in the form:
19282
19283 @smallexample
19284 call subprogram-name (parameters)
19285 @end smallexample
19286
19287 @noindent
19288 The keyword @code{call} can be omitted in the normal case where the
19289 @code{subprogram-name} does not coincide with any of the predefined
19290 @code{GDB} commands.
19291
19292 The effect is to invoke the given subprogram, passing it the
19293 list of parameters that is supplied. The parameters can be expressions and
19294 can include variables from the program being debugged. The
19295 subprogram must be defined
19296 at the library level within your program, and @code{GDB} will call the
19297 subprogram within the environment of your program execution (which
19298 means that the subprogram is free to access or even modify variables
19299 within your program).
19300
19301 The most important use of this facility is in allowing the inclusion of
19302 debugging routines that are tailored to particular data structures
19303 in your program. Such debugging routines can be written to provide a suitably
19304 high-level description of an abstract type, rather than a low-level dump
19305 of its physical layout. After all, the standard
19306 @code{GDB print} command only knows the physical layout of your
19307 types, not their abstract meaning. Debugging routines can provide information
19308 at the desired semantic level and are thus enormously useful.
19309
19310 For example, when debugging GNAT itself, it is crucial to have access to
19311 the contents of the tree nodes used to represent the program internally.
19312 But tree nodes are represented simply by an integer value (which in turn
19313 is an index into a table of nodes).
19314 Using the @code{print} command on a tree node would simply print this integer
19315 value, which is not very useful. But the PN routine (defined in file
19316 treepr.adb in the GNAT sources) takes a tree node as input, and displays
19317 a useful high level representation of the tree node, which includes the
19318 syntactic category of the node, its position in the source, the integers
19319 that denote descendant nodes and parent node, as well as varied
19320 semantic information. To study this example in more detail, you might want to
19321 look at the body of the PN procedure in the stated file.
19322
19323 @node Using the Next Command in a Function
19324 @section Using the Next Command in a Function
19325
19326 @noindent
19327 When you use the @code{next} command in a function, the current source
19328 location will advance to the next statement as usual. A special case
19329 arises in the case of a @code{return} statement.
19330
19331 Part of the code for a return statement is the ``epilog'' of the function.
19332 This is the code that returns to the caller. There is only one copy of
19333 this epilog code, and it is typically associated with the last return
19334 statement in the function if there is more than one return. In some
19335 implementations, this epilog is associated with the first statement
19336 of the function.
19337
19338 The result is that if you use the @code{next} command from a return
19339 statement that is not the last return statement of the function you
19340 may see a strange apparent jump to the last return statement or to
19341 the start of the function. You should simply ignore this odd jump.
19342 The value returned is always that from the first return statement
19343 that was stepped through.
19344
19345 @node Ada Exceptions
19346 @section Stopping when Ada Exceptions are Raised
19347 @cindex Exceptions
19348
19349 @noindent
19350 You can set catchpoints that stop the program execution when your program
19351 raises selected exceptions.
19352
19353 @table @code
19354 @item catch exception
19355 Set a catchpoint that stops execution whenever (any task in the) program
19356 raises any exception.
19357
19358 @item catch exception @var{name}
19359 Set a catchpoint that stops execution whenever (any task in the) program
19360 raises the exception @var{name}.
19361
19362 @item catch exception unhandled
19363 Set a catchpoint that stops executing whenever (any task in the) program
19364 raises an exception for which there is no handler.
19365
19366 @item info exceptions
19367 @itemx info exceptions @var{regexp}
19368 The @code{info exceptions} command permits the user to examine all defined
19369 exceptions within Ada programs. With a regular expression, @var{regexp}, as
19370 argument, prints out only those exceptions whose name matches @var{regexp}.
19371 @end table
19372
19373 @node Ada Tasks
19374 @section Ada Tasks
19375 @cindex Tasks
19376
19377 @noindent
19378 @code{GDB} allows the following task-related commands:
19379
19380 @table @code
19381 @item info tasks
19382 This command shows a list of current Ada tasks, as in the following example:
19383
19384 @smallexample
19385 @iftex
19386 @leftskip=0cm
19387 @end iftex
19388 (gdb) info tasks
19389   ID       TID P-ID   Thread Pri State                 Name
19390    1   8088000   0   807e000  15 Child Activation Wait main_task
19391    2   80a4000   1   80ae000  15 Accept/Select Wait    b
19392    3   809a800   1   80a4800  15 Child Activation Wait a
19393 *  4   80ae800   3   80b8000  15 Running               c
19394 @end smallexample
19395
19396 @noindent
19397 In this listing, the asterisk before the first task indicates it to be the
19398 currently running task. The first column lists the task ID that is used
19399 to refer to tasks in the following commands.
19400
19401 @item break @var{linespec} task @var{taskid}
19402 @itemx break @var{linespec} task @var{taskid} if @dots{}
19403 @cindex Breakpoints and tasks
19404 These commands are like the @code{break @dots{} thread @dots{}}.
19405 @var{linespec} specifies source lines.
19406
19407 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
19408 to specify that you only want @code{GDB} to stop the program when a
19409 particular Ada task reaches this breakpoint. @var{taskid} is one of the
19410 numeric task identifiers assigned by @code{GDB}, shown in the first
19411 column of the @samp{info tasks} display.
19412
19413 If you do not specify @samp{task @var{taskid}} when you set a
19414 breakpoint, the breakpoint applies to @emph{all} tasks of your
19415 program.
19416
19417 You can use the @code{task} qualifier on conditional breakpoints as
19418 well; in this case, place @samp{task @var{taskid}} before the
19419 breakpoint condition (before the @code{if}).
19420
19421 @item task @var{taskno}
19422 @cindex Task switching
19423
19424 This command allows to switch to the task referred by @var{taskno}. In
19425 particular, This allows to browse the backtrace of the specified
19426 task. It is advised to switch back to the original task before
19427 continuing execution otherwise the scheduling of the program may be
19428 perturbed.
19429 @end table
19430
19431 @noindent
19432 For more detailed information on the tasking support,
19433 see @ref{Top,, Debugging with GDB, gdb, Debugging with GDB}.
19434
19435 @node Debugging Generic Units
19436 @section Debugging Generic Units
19437 @cindex Debugging Generic Units
19438 @cindex Generics
19439
19440 @noindent
19441 GNAT always uses code expansion for generic instantiation. This means that
19442 each time an instantiation occurs, a complete copy of the original code is
19443 made, with appropriate substitutions of formals by actuals.
19444
19445 It is not possible to refer to the original generic entities in
19446 @code{GDB}, but it is always possible to debug a particular instance of
19447 a generic, by using the appropriate expanded names. For example, if we have
19448
19449 @smallexample @c ada
19450 @group
19451 @cartouche
19452 procedure g is
19453
19454    generic package k is
19455       procedure kp (v1 : in out integer);
19456    end k;
19457
19458    package body k is
19459       procedure kp (v1 : in out integer) is
19460       begin
19461          v1 := v1 + 1;
19462       end kp;
19463    end k;
19464
19465    package k1 is new k;
19466    package k2 is new k;
19467
19468    var : integer := 1;
19469
19470 begin
19471    k1.kp (var);
19472    k2.kp (var);
19473    k1.kp (var);
19474    k2.kp (var);
19475 end;
19476 @end cartouche
19477 @end group
19478 @end smallexample
19479
19480 @noindent
19481 Then to break on a call to procedure kp in the k2 instance, simply
19482 use the command:
19483
19484 @smallexample
19485 (gdb) break g.k2.kp
19486 @end smallexample
19487
19488 @noindent
19489 When the breakpoint occurs, you can step through the code of the
19490 instance in the normal manner and examine the values of local variables, as for
19491 other units.
19492
19493 @node Remote Debugging using gdbserver
19494 @section Remote Debugging using gdbserver
19495 @cindex Remote Debugging using gdbserver
19496
19497 @noindent
19498 On platforms where gdbserver is supported, it is possible to use this tool
19499 to debug your application remotely.  This can be useful in situations
19500 where the program needs to be run on a target host that is different
19501 from the host used for development, particularly when the target has
19502 a limited amount of resources (either CPU and/or memory).
19503
19504 To do so, start your program using gdbserver on the target machine.
19505 gdbserver then automatically suspends the execution of your program
19506 at its entry point, waiting for a debugger to connect to it.  The
19507 following commands starts an application and tells gdbserver to
19508 wait for a connection with the debugger on localhost port 4444.
19509
19510 @smallexample
19511 $ gdbserver localhost:4444 program
19512 Process program created; pid = 5685
19513 Listening on port 4444
19514 @end smallexample
19515
19516 Once gdbserver has started listening, we can tell the debugger to establish
19517 a connection with this gdbserver, and then start the same debugging session
19518 as if the program was being debugged on the same host, directly under
19519 the control of GDB.
19520
19521 @smallexample
19522 $ gdb program
19523 (gdb) target remote targethost:4444
19524 Remote debugging using targethost:4444
19525 0x00007f29936d0af0 in ?? () from /lib64/ld-linux-x86-64.so.
19526 (gdb) b foo.adb:3
19527 Breakpoint 1 at 0x401f0c: file foo.adb, line 3.
19528 (gdb) continue
19529 Continuing.
19530
19531 Breakpoint 1, foo () at foo.adb:4
19532 4       end foo;
19533 @end smallexample
19534
19535 It is also possible to use gdbserver to attach to an already running
19536 program, in which case the execution of that program is simply suspended
19537 until the connection between the debugger and gdbserver is established.
19538
19539 For more information on how to use gdbserver, @ref{Top, Server, Using
19540 the gdbserver Program, gdb, Debugging with GDB}.  @value{EDITION} provides support
19541 for gdbserver on x86-linux, x86-windows and x86_64-linux.
19542
19543 @node GNAT Abnormal Termination or Failure to Terminate
19544 @section GNAT Abnormal Termination or Failure to Terminate
19545 @cindex GNAT Abnormal Termination or Failure to Terminate
19546
19547 @noindent
19548 When presented with programs that contain serious errors in syntax
19549 or semantics,
19550 GNAT may on rare occasions  experience problems in operation, such
19551 as aborting with a
19552 segmentation fault or illegal memory access, raising an internal
19553 exception, terminating abnormally, or failing to terminate at all.
19554 In such cases, you can activate
19555 various features of GNAT that can help you pinpoint the construct in your
19556 program that is the likely source of the problem.
19557
19558 The following strategies are presented in increasing order of
19559 difficulty, corresponding to your experience in using GNAT and your
19560 familiarity with compiler internals.
19561
19562 @enumerate
19563 @item
19564 Run @command{gcc} with the @option{-gnatf}. This first
19565 switch causes all errors on a given line to be reported. In its absence,
19566 only the first error on a line is displayed.
19567
19568 The @option{-gnatdO} switch causes errors to be displayed as soon as they
19569 are encountered, rather than after compilation is terminated. If GNAT
19570 terminates prematurely or goes into an infinite loop, the last error
19571 message displayed may help to pinpoint the culprit.
19572
19573 @item
19574 Run @command{gcc} with the @option{^-v (verbose)^/VERBOSE^} switch. In this
19575 mode, @command{gcc} produces ongoing information about the progress of the
19576 compilation and provides the name of each procedure as code is
19577 generated. This switch allows you to find which Ada procedure was being
19578 compiled when it encountered a code generation problem.
19579
19580 @item
19581 @cindex @option{-gnatdc} switch
19582 Run @command{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
19583 switch that does for the front-end what @option{^-v^VERBOSE^} does
19584 for the back end. The system prints the name of each unit,
19585 either a compilation unit or nested unit, as it is being analyzed.
19586 @item
19587 Finally, you can start
19588 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
19589 front-end of GNAT, and can be run independently (normally it is just
19590 called from @command{gcc}). You can use @code{gdb} on @code{gnat1} as you
19591 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
19592 @code{where} command is the first line of attack; the variable
19593 @code{lineno} (seen by @code{print lineno}), used by the second phase of
19594 @code{gnat1} and by the @command{gcc} backend, indicates the source line at
19595 which the execution stopped, and @code{input_file name} indicates the name of
19596 the source file.
19597 @end enumerate
19598
19599 @node Naming Conventions for GNAT Source Files
19600 @section Naming Conventions for GNAT Source Files
19601
19602 @noindent
19603 In order to examine the workings of the GNAT system, the following
19604 brief description of its organization may be helpful:
19605
19606 @itemize @bullet
19607 @item
19608 Files with prefix @file{^sc^SC^} contain the lexical scanner.
19609
19610 @item
19611 All files prefixed with @file{^par^PAR^} are components of the parser. The
19612 numbers correspond to chapters of the Ada Reference Manual. For example,
19613 parsing of select statements can be found in @file{par-ch9.adb}.
19614
19615 @item
19616 All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
19617 numbers correspond to chapters of the Ada standard. For example, all
19618 issues involving context clauses can be found in @file{sem_ch10.adb}. In
19619 addition, some features of the language require sufficient special processing
19620 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
19621 dynamic dispatching, etc.
19622
19623 @item
19624 All files prefixed with @file{^exp^EXP^} perform normalization and
19625 expansion of the intermediate representation (abstract syntax tree, or AST).
19626 these files use the same numbering scheme as the parser and semantics files.
19627 For example, the construction of record initialization procedures is done in
19628 @file{exp_ch3.adb}.
19629
19630 @item
19631 The files prefixed with @file{^bind^BIND^} implement the binder, which
19632 verifies the consistency of the compilation, determines an order of
19633 elaboration, and generates the bind file.
19634
19635 @item
19636 The files @file{atree.ads} and @file{atree.adb} detail the low-level
19637 data structures used by the front-end.
19638
19639 @item
19640 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
19641 the abstract syntax tree as produced by the parser.
19642
19643 @item
19644 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
19645 all entities, computed during semantic analysis.
19646
19647 @item
19648 Library management issues are dealt with in files with prefix
19649 @file{^lib^LIB^}.
19650
19651 @item
19652 @findex Ada
19653 @cindex Annex A
19654 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
19655 defined in Annex A.
19656
19657 @item
19658 @findex Interfaces
19659 @cindex Annex B
19660 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
19661 defined in Annex B.
19662
19663 @item
19664 @findex System
19665 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
19666 both language-defined children and GNAT run-time routines.
19667
19668 @item
19669 @findex GNAT
19670 Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
19671 general-purpose packages, fully documented in their specs. All
19672 the other @file{.c} files are modifications of common @command{gcc} files.
19673 @end itemize
19674
19675 @node Getting Internal Debugging Information
19676 @section Getting Internal Debugging Information
19677
19678 @noindent
19679 Most compilers have internal debugging switches and modes. GNAT
19680 does also, except GNAT internal debugging switches and modes are not
19681 secret. A summary and full description of all the compiler and binder
19682 debug flags are in the file @file{debug.adb}. You must obtain the
19683 sources of the compiler to see the full detailed effects of these flags.
19684
19685 The switches that print the source of the program (reconstructed from
19686 the internal tree) are of general interest for user programs, as are the
19687 options to print
19688 the full internal tree, and the entity table (the symbol table
19689 information). The reconstructed source provides a readable version of the
19690 program after the front-end has completed analysis and  expansion,
19691 and is useful when studying the performance of specific constructs.
19692 For example, constraint checks are indicated, complex aggregates
19693 are replaced with loops and assignments, and tasking primitives
19694 are replaced with run-time calls.
19695
19696 @node Stack Traceback
19697 @section Stack Traceback
19698 @cindex traceback
19699 @cindex stack traceback
19700 @cindex stack unwinding
19701
19702 @noindent
19703 Traceback is a mechanism to display the sequence of subprogram calls that
19704 leads to a specified execution point in a program. Often (but not always)
19705 the execution point is an instruction at which an exception has been raised.
19706 This mechanism is also known as @i{stack unwinding} because it obtains
19707 its information by scanning the run-time stack and recovering the activation
19708 records of all active subprograms. Stack unwinding is one of the most
19709 important tools for program debugging.
19710
19711 The first entry stored in traceback corresponds to the deepest calling level,
19712 that is to say the subprogram currently executing the instruction
19713 from which we want to obtain the traceback.
19714
19715 Note that there is no runtime performance penalty when stack traceback
19716 is enabled, and no exception is raised during program execution.
19717
19718 @menu
19719 * Non-Symbolic Traceback::
19720 * Symbolic Traceback::
19721 @end menu
19722
19723 @node Non-Symbolic Traceback
19724 @subsection Non-Symbolic Traceback
19725 @cindex traceback, non-symbolic
19726
19727 @noindent
19728 Note: this feature is not supported on all platforms. See
19729 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
19730 platforms.
19731
19732 @menu
19733 * Tracebacks From an Unhandled Exception::
19734 * Tracebacks From Exception Occurrences (non-symbolic)::
19735 * Tracebacks From Anywhere in a Program (non-symbolic)::
19736 @end menu
19737
19738 @node Tracebacks From an Unhandled Exception
19739 @subsubsection Tracebacks From an Unhandled Exception
19740
19741 @noindent
19742 A runtime non-symbolic traceback is a list of addresses of call instructions.
19743 To enable this feature you must use the @option{-E}
19744 @code{gnatbind}'s option. With this option a stack traceback is stored as part
19745 of exception information. You can retrieve this information using the
19746 @code{addr2line} tool.
19747
19748 Here is a simple example:
19749
19750 @smallexample @c ada
19751 @cartouche
19752 procedure STB is
19753
19754    procedure P1 is
19755    begin
19756       raise Constraint_Error;
19757    end P1;
19758
19759    procedure P2 is
19760    begin
19761       P1;
19762    end P2;
19763
19764 begin
19765    P2;
19766 end STB;
19767 @end cartouche
19768 @end smallexample
19769
19770 @smallexample
19771 $ gnatmake stb -bargs -E
19772 $ stb
19773
19774 Execution terminated by unhandled exception
19775 Exception name: CONSTRAINT_ERROR
19776 Message: stb.adb:5
19777 Call stack traceback locations:
19778 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
19779 @end smallexample
19780
19781 @noindent
19782 As we see the traceback lists a sequence of addresses for the unhandled
19783 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
19784 guess that this exception come from procedure P1. To translate these
19785 addresses into the source lines where the calls appear, the
19786 @code{addr2line} tool, described below, is invaluable. The use of this tool
19787 requires the program to be compiled with debug information.
19788
19789 @smallexample
19790 $ gnatmake -g stb -bargs -E
19791 $ stb
19792
19793 Execution terminated by unhandled exception
19794 Exception name: CONSTRAINT_ERROR
19795 Message: stb.adb:5
19796 Call stack traceback locations:
19797 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
19798
19799 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
19800    0x4011f1 0x77e892a4
19801
19802 00401373 at d:/stb/stb.adb:5
19803 0040138B at d:/stb/stb.adb:10
19804 0040139C at d:/stb/stb.adb:14
19805 00401335 at d:/stb/b~stb.adb:104
19806 004011C4 at /build/@dots{}/crt1.c:200
19807 004011F1 at /build/@dots{}/crt1.c:222
19808 77E892A4 in ?? at ??:0
19809 @end smallexample
19810
19811 @noindent
19812 The @code{addr2line} tool has several other useful options:
19813
19814 @table @code
19815 @item --functions
19816 to get the function name corresponding to any location
19817
19818 @item --demangle=gnat
19819 to use the gnat decoding mode for the function names. Note that
19820 for binutils version 2.9.x the option is simply @option{--demangle}.
19821 @end table
19822
19823 @smallexample
19824 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
19825    0x40139c 0x401335 0x4011c4 0x4011f1
19826
19827 00401373 in stb.p1 at d:/stb/stb.adb:5
19828 0040138B in stb.p2 at d:/stb/stb.adb:10
19829 0040139C in stb at d:/stb/stb.adb:14
19830 00401335 in main at d:/stb/b~stb.adb:104
19831 004011C4 in <__mingw_CRTStartup> at /build/@dots{}/crt1.c:200
19832 004011F1 in <mainCRTStartup> at /build/@dots{}/crt1.c:222
19833 @end smallexample
19834
19835 @noindent
19836 From this traceback we can see that the exception was raised in
19837 @file{stb.adb} at line 5, which was reached from a procedure call in
19838 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
19839 which contains the call to the main program.
19840 @xref{Running gnatbind}. The remaining entries are assorted runtime routines,
19841 and the output will vary from platform to platform.
19842
19843 It is also possible to use @code{GDB} with these traceback addresses to debug
19844 the program. For example, we can break at a given code location, as reported
19845 in the stack traceback:
19846
19847 @smallexample
19848 $ gdb -nw stb
19849 @ifclear vms
19850 @noindent
19851 Furthermore, this feature is not implemented inside Windows DLL. Only
19852 the non-symbolic traceback is reported in this case.
19853 @end ifclear
19854
19855 (gdb) break *0x401373
19856 Breakpoint 1 at 0x401373: file stb.adb, line 5.
19857 @end smallexample
19858
19859 @noindent
19860 It is important to note that the stack traceback addresses
19861 do not change when debug information is included. This is particularly useful
19862 because it makes it possible to release software without debug information (to
19863 minimize object size), get a field report that includes a stack traceback
19864 whenever an internal bug occurs, and then be able to retrieve the sequence
19865 of calls with the same program compiled with debug information.
19866
19867 @node Tracebacks From Exception Occurrences (non-symbolic)
19868 @subsubsection Tracebacks From Exception Occurrences
19869
19870 @noindent
19871 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
19872 The stack traceback is attached to the exception information string, and can
19873 be retrieved in an exception handler within the Ada program, by means of the
19874 Ada facilities defined in @code{Ada.Exceptions}. Here is a simple example:
19875
19876 @smallexample @c ada
19877 with Ada.Text_IO;
19878 with Ada.Exceptions;
19879
19880 procedure STB is
19881
19882    use Ada;
19883    use Ada.Exceptions;
19884
19885    procedure P1 is
19886       K : Positive := 1;
19887    begin
19888       K := K - 1;
19889    exception
19890       when E : others =>
19891          Text_IO.Put_Line (Exception_Information (E));
19892    end P1;
19893
19894    procedure P2 is
19895    begin
19896       P1;
19897    end P2;
19898
19899 begin
19900    P2;
19901 end STB;
19902 @end smallexample
19903
19904 @noindent
19905 This program will output:
19906
19907 @smallexample
19908 $ stb
19909
19910 Exception name: CONSTRAINT_ERROR
19911 Message: stb.adb:12
19912 Call stack traceback locations:
19913 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
19914 @end smallexample
19915
19916 @node Tracebacks From Anywhere in a Program (non-symbolic)
19917 @subsubsection Tracebacks From Anywhere in a Program
19918
19919 @noindent
19920 It is also possible to retrieve a stack traceback from anywhere in a
19921 program. For this you need to
19922 use the @code{GNAT.Traceback} API. This package includes a procedure called
19923 @code{Call_Chain} that computes a complete stack traceback, as well as useful
19924 display procedures described below. It is not necessary to use the
19925 @option{-E gnatbind} option in this case, because the stack traceback mechanism
19926 is invoked explicitly.
19927
19928 @noindent
19929 In the following example we compute a traceback at a specific location in
19930 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
19931 convert addresses to strings:
19932
19933 @smallexample @c ada
19934 with Ada.Text_IO;
19935 with GNAT.Traceback;
19936 with GNAT.Debug_Utilities;
19937
19938 procedure STB is
19939
19940    use Ada;
19941    use GNAT;
19942    use GNAT.Traceback;
19943
19944    procedure P1 is
19945       TB  : Tracebacks_Array (1 .. 10);
19946       --  We are asking for a maximum of 10 stack frames.
19947       Len : Natural;
19948       --  Len will receive the actual number of stack frames returned.
19949    begin
19950       Call_Chain (TB, Len);
19951
19952       Text_IO.Put ("In STB.P1 : ");
19953
19954       for K in 1 .. Len loop
19955          Text_IO.Put (Debug_Utilities.Image (TB (K)));
19956          Text_IO.Put (' ');
19957       end loop;
19958
19959       Text_IO.New_Line;
19960    end P1;
19961
19962    procedure P2 is
19963    begin
19964       P1;
19965    end P2;
19966
19967 begin
19968    P2;
19969 end STB;
19970 @end smallexample
19971
19972 @smallexample
19973 $ gnatmake -g stb
19974 $ stb
19975
19976 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
19977 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
19978 @end smallexample
19979
19980 @noindent
19981 You can then get further information by invoking the @code{addr2line}
19982 tool as described earlier (note that the hexadecimal addresses
19983 need to be specified in C format, with a leading ``0x'').
19984
19985 @node Symbolic Traceback
19986 @subsection Symbolic Traceback
19987 @cindex traceback, symbolic
19988
19989 @noindent
19990 A symbolic traceback is a stack traceback in which procedure names are
19991 associated with each code location.
19992
19993 @noindent
19994 Note that this feature is not supported on all platforms. See
19995 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
19996 list of currently supported platforms.
19997
19998 @noindent
19999 Note that the symbolic traceback requires that the program be compiled
20000 with debug information. If it is not compiled with debug information
20001 only the non-symbolic information will be valid.
20002
20003 @menu
20004 * Tracebacks From Exception Occurrences (symbolic)::
20005 * Tracebacks From Anywhere in a Program (symbolic)::
20006 @end menu
20007
20008 @node Tracebacks From Exception Occurrences (symbolic)
20009 @subsubsection Tracebacks From Exception Occurrences
20010
20011 @smallexample @c ada
20012 with Ada.Text_IO;
20013 with GNAT.Traceback.Symbolic;
20014
20015 procedure STB is
20016
20017    procedure P1 is
20018    begin
20019       raise Constraint_Error;
20020    end P1;
20021
20022    procedure P2 is
20023    begin
20024       P1;
20025    end P2;
20026
20027    procedure P3 is
20028    begin
20029       P2;
20030    end P3;
20031
20032 begin
20033    P3;
20034 exception
20035    when E : others =>
20036       Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
20037 end STB;
20038 @end smallexample
20039
20040 @smallexample
20041 $ gnatmake -g .\stb -bargs -E -largs -lgnat -laddr2line -lintl
20042 $ stb
20043
20044 0040149F in stb.p1 at stb.adb:8
20045 004014B7 in stb.p2 at stb.adb:13
20046 004014CF in stb.p3 at stb.adb:18
20047 004015DD in ada.stb at stb.adb:22
20048 00401461 in main at b~stb.adb:168
20049 004011C4 in __mingw_CRTStartup at crt1.c:200
20050 004011F1 in mainCRTStartup at crt1.c:222
20051 77E892A4 in ?? at ??:0
20052 @end smallexample
20053
20054 @noindent
20055 In the above example the ``.\'' syntax in the @command{gnatmake} command
20056 is currently required by @command{addr2line} for files that are in
20057 the current working directory.
20058 Moreover, the exact sequence of linker options may vary from platform
20059 to platform.
20060 The above @option{-largs} section is for Windows platforms. By contrast,
20061 under Unix there is no need for the @option{-largs} section.
20062 Differences across platforms are due to details of linker implementation.
20063
20064 @node Tracebacks From Anywhere in a Program (symbolic)
20065 @subsubsection Tracebacks From Anywhere in a Program
20066
20067 @noindent
20068 It is possible to get a symbolic stack traceback
20069 from anywhere in a program, just as for non-symbolic tracebacks.
20070 The first step is to obtain a non-symbolic
20071 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
20072 information. Here is an example:
20073
20074 @smallexample @c ada
20075 with Ada.Text_IO;
20076 with GNAT.Traceback;
20077 with GNAT.Traceback.Symbolic;
20078
20079 procedure STB is
20080
20081    use Ada;
20082    use GNAT.Traceback;
20083    use GNAT.Traceback.Symbolic;
20084
20085    procedure P1 is
20086       TB  : Tracebacks_Array (1 .. 10);
20087       --  We are asking for a maximum of 10 stack frames.
20088       Len : Natural;
20089       --  Len will receive the actual number of stack frames returned.
20090    begin
20091       Call_Chain (TB, Len);
20092       Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
20093    end P1;
20094
20095    procedure P2 is
20096    begin
20097       P1;
20098    end P2;
20099
20100 begin
20101    P2;
20102 end STB;
20103 @end smallexample
20104
20105 @c ******************************
20106 @ifset vms
20107 @node Compatibility with HP Ada
20108 @chapter Compatibility with HP Ada
20109 @cindex Compatibility
20110
20111 @noindent
20112 @cindex DEC Ada
20113 @cindex HP Ada
20114 @cindex Compatibility between GNAT and HP Ada
20115 This chapter compares HP Ada (formerly known as ``DEC Ada'')
20116 for OpenVMS Alpha and GNAT for OpenVMS for Alpha and for I64.
20117 GNAT is highly compatible
20118 with HP Ada, and it should generally be straightforward to port code
20119 from the HP Ada environment to GNAT. However, there are a few language
20120 and implementation differences of which the user must be aware. These
20121 differences are discussed in this chapter. In
20122 addition, the operating environment and command structure for the
20123 compiler are different, and these differences are also discussed.
20124
20125 For further details on these and other compatibility issues,
20126 see Appendix E of the HP publication
20127 @cite{HP Ada, Technical Overview and Comparison on HP Platforms}.
20128
20129 Except where otherwise indicated, the description of GNAT for OpenVMS
20130 applies to both the Alpha and I64 platforms.
20131
20132 For information on porting Ada code from GNAT on Alpha OpenVMS to GNAT on
20133 I64 OpenVMS, see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
20134
20135 The discussion in this chapter addresses specifically the implementation
20136 of Ada 83 for HP OpenVMS Alpha Systems. In cases where the implementation
20137 of HP Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems,
20138 GNAT always follows the Alpha implementation.
20139
20140 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
20141 attributes are recognized, although only a subset of them can sensibly
20142 be implemented.  The description of pragmas in
20143 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
20144 indicates whether or not they are applicable to non-VMS systems.
20145
20146 @menu
20147 * Ada Language Compatibility::
20148 * Differences in the Definition of Package System::
20149 * Language-Related Features::
20150 * The Package STANDARD::
20151 * The Package SYSTEM::
20152 * Tasking and Task-Related Features::
20153 * Pragmas and Pragma-Related Features::
20154 * Library of Predefined Units::
20155 * Bindings::
20156 * Main Program Definition::
20157 * Implementation-Defined Attributes::
20158 * Compiler and Run-Time Interfacing::
20159 * Program Compilation and Library Management::
20160 * Input-Output::
20161 * Implementation Limits::
20162 * Tools and Utilities::
20163 @end menu
20164
20165 @node Ada Language Compatibility
20166 @section Ada Language Compatibility
20167
20168 @noindent
20169 GNAT handles Ada 95 and Ada 2005 as well as Ada 83, whereas HP Ada is only
20170 for Ada 83. Ada 95 and Ada 2005 are almost completely upwards compatible
20171 with Ada 83, and therefore Ada 83 programs will compile
20172 and run under GNAT with
20173 no changes or only minor changes. The @cite{Annotated Ada Reference Manual}
20174 provides details on specific incompatibilities.
20175
20176 GNAT provides the switch @option{/83} on the @command{GNAT COMPILE} command,
20177 as well as the pragma @code{ADA_83}, to force the compiler to
20178 operate in Ada 83 mode. This mode does not guarantee complete
20179 conformance to Ada 83, but in practice is sufficient to
20180 eliminate most sources of incompatibilities.
20181 In particular, it eliminates the recognition of the
20182 additional Ada 95 and Ada 2005 keywords, so that their use as identifiers
20183 in Ada 83 programs is legal, and handles the cases of packages
20184 with optional bodies, and generics that instantiate unconstrained
20185 types without the use of @code{(<>)}.
20186
20187 @node Differences in the Definition of Package System
20188 @section Differences in the Definition of Package @code{System}
20189
20190 @noindent
20191 An Ada compiler is allowed to add
20192 implementation-dependent declarations to package @code{System}.
20193 In normal mode,
20194 GNAT does not take advantage of this permission, and the version of
20195 @code{System} provided by GNAT exactly matches that defined in the Ada
20196 Reference Manual.
20197
20198 However, HP Ada adds an extensive set of declarations to package
20199 @code{System},
20200 as fully documented in the HP Ada manuals. To minimize changes required
20201 for programs that make use of these extensions, GNAT provides the pragma
20202 @code{Extend_System} for extending the definition of package System. By using:
20203 @cindex pragma @code{Extend_System}
20204 @cindex @code{Extend_System} pragma
20205
20206 @smallexample @c ada
20207 @group
20208 @cartouche
20209 pragma Extend_System (Aux_DEC);
20210 @end cartouche
20211 @end group
20212 @end smallexample
20213
20214 @noindent
20215 the set of definitions in @code{System} is extended to include those in
20216 package @code{System.Aux_DEC}.
20217 @cindex @code{System.Aux_DEC} package
20218 @cindex @code{Aux_DEC} package (child of @code{System})
20219 These definitions are incorporated directly into package @code{System},
20220 as though they had been declared there. For a
20221 list of the declarations added, see the spec of this package,
20222 which can be found in the file @file{s-auxdec.ads} in the GNAT library.
20223 @cindex @file{s-auxdec.ads} file
20224 The pragma @code{Extend_System} is a configuration pragma, which means that
20225 it can be placed in the file @file{gnat.adc}, so that it will automatically
20226 apply to all subsequent compilations. See @ref{Configuration Pragmas},
20227 for further details.
20228
20229 An alternative approach that avoids the use of the non-standard
20230 @code{Extend_System} pragma is to add a context clause to the unit that
20231 references these facilities:
20232
20233 @smallexample @c ada
20234 @cartouche
20235 with System.Aux_DEC;
20236 use  System.Aux_DEC;
20237 @end cartouche
20238 @end smallexample
20239
20240 @noindent
20241 The effect is not quite semantically identical to incorporating
20242 the declarations directly into package @code{System},
20243 but most programs will not notice a difference
20244 unless they use prefix notation (e.g.@: @code{System.Integer_8})
20245 to reference the entities directly in package @code{System}.
20246 For units containing such references,
20247 the prefixes must either be removed, or the pragma @code{Extend_System}
20248 must be used.
20249
20250 @node Language-Related Features
20251 @section Language-Related Features
20252
20253 @noindent
20254 The following sections highlight differences in types,
20255 representations of types, operations, alignment, and
20256 related topics.
20257
20258 @menu
20259 * Integer Types and Representations::
20260 * Floating-Point Types and Representations::
20261 * Pragmas Float_Representation and Long_Float::
20262 * Fixed-Point Types and Representations::
20263 * Record and Array Component Alignment::
20264 * Address Clauses::
20265 * Other Representation Clauses::
20266 @end menu
20267
20268 @node Integer Types and Representations
20269 @subsection Integer Types and Representations
20270
20271 @noindent
20272 The set of predefined integer types is identical in HP Ada and GNAT.
20273 Furthermore the representation of these integer types is also identical,
20274 including the capability of size clauses forcing biased representation.
20275
20276 In addition,
20277 HP Ada for OpenVMS Alpha systems has defined the
20278 following additional integer types in package @code{System}:
20279
20280 @itemize @bullet
20281
20282 @item
20283 @code{INTEGER_8}
20284
20285 @item
20286 @code{INTEGER_16}
20287
20288 @item
20289 @code{INTEGER_32}
20290
20291 @item
20292 @code{INTEGER_64}
20293
20294 @item
20295 @code{LARGEST_INTEGER}
20296 @end itemize
20297
20298 @noindent
20299 In GNAT, the first four of these types may be obtained from the
20300 standard Ada package @code{Interfaces}.
20301 Alternatively, by use of the pragma @code{Extend_System}, identical
20302 declarations can be referenced directly in package @code{System}.
20303 On both GNAT and HP Ada, the maximum integer size is 64 bits.
20304
20305 @node Floating-Point Types and Representations
20306 @subsection Floating-Point Types and Representations
20307 @cindex Floating-Point types
20308
20309 @noindent
20310 The set of predefined floating-point types is identical in HP Ada and GNAT.
20311 Furthermore the representation of these floating-point
20312 types is also identical. One important difference is that the default
20313 representation for HP Ada is @code{VAX_Float}, but the default representation
20314 for GNAT is IEEE.
20315
20316 Specific types may be declared to be @code{VAX_Float} or IEEE, using the
20317 pragma @code{Float_Representation} as described in the HP Ada
20318 documentation.
20319 For example, the declarations:
20320
20321 @smallexample @c ada
20322 @cartouche
20323 type F_Float is digits 6;
20324 pragma Float_Representation (VAX_Float, F_Float);
20325 @end cartouche
20326 @end smallexample
20327
20328 @noindent
20329 declares a type @code{F_Float} that will be represented in @code{VAX_Float}
20330 format.
20331 This set of declarations actually appears in @code{System.Aux_DEC},
20332 which contains
20333 the full set of additional floating-point declarations provided in
20334 the HP Ada version of package @code{System}.
20335 This and similar declarations may be accessed in a user program
20336 by using pragma @code{Extend_System}. The use of this
20337 pragma, and the related pragma @code{Long_Float} is described in further
20338 detail in the following section.
20339
20340 @node Pragmas Float_Representation and Long_Float
20341 @subsection Pragmas @code{Float_Representation} and @code{Long_Float}
20342
20343 @noindent
20344 HP Ada provides the pragma @code{Float_Representation}, which
20345 acts as a program library switch to allow control over
20346 the internal representation chosen for the predefined
20347 floating-point types declared in the package @code{Standard}.
20348 The format of this pragma is as follows:
20349
20350 @smallexample @c ada
20351 @cartouche
20352 pragma Float_Representation(VAX_Float | IEEE_Float);
20353 @end cartouche
20354 @end smallexample
20355
20356 @noindent
20357 This pragma controls the representation of floating-point
20358 types as follows:
20359
20360 @itemize @bullet
20361 @item
20362 @code{VAX_Float} specifies that floating-point
20363 types are represented by default with the VAX system hardware types
20364 @code{F-floating}, @code{D-floating}, @code{G-floating}.
20365 Note that the @code{H-floating}
20366 type was available only on VAX systems, and is not available
20367 in either HP Ada or GNAT.
20368
20369 @item
20370 @code{IEEE_Float} specifies that floating-point
20371 types are represented by default with the IEEE single and
20372 double floating-point types.
20373 @end itemize
20374
20375 @noindent
20376 GNAT provides an identical implementation of the pragma
20377 @code{Float_Representation}, except that it functions as a
20378 configuration pragma. Note that the
20379 notion of configuration pragma corresponds closely to the
20380 HP Ada notion of a program library switch.
20381
20382 When no pragma is used in GNAT, the default is @code{IEEE_Float},
20383 which is different
20384 from HP Ada 83, where the default is @code{VAX_Float}. In addition, the
20385 predefined libraries in GNAT are built using @code{IEEE_Float}, so it is not
20386 advisable to change the format of numbers passed to standard library
20387 routines, and if necessary explicit type conversions may be needed.
20388
20389 The use of @code{IEEE_Float} is recommended in GNAT since it is more
20390 efficient, and (given that it conforms to an international standard)
20391 potentially more portable.
20392 The situation in which @code{VAX_Float} may be useful is in interfacing
20393 to existing code and data that expect the use of @code{VAX_Float}.
20394 In such a situation use the predefined @code{VAX_Float}
20395 types in package @code{System}, as extended by
20396 @code{Extend_System}. For example, use @code{System.F_Float}
20397 to specify the 32-bit @code{F-Float} format.
20398
20399 @noindent
20400 On OpenVMS systems, HP Ada provides the pragma @code{Long_Float}
20401 to allow control over the internal representation chosen
20402 for the predefined type @code{Long_Float} and for floating-point
20403 type declarations with digits specified in the range 7 .. 15.
20404 The format of this pragma is as follows:
20405
20406 @smallexample @c ada
20407 @cartouche
20408 pragma Long_Float (D_FLOAT | G_FLOAT);
20409 @end cartouche
20410 @end smallexample
20411
20412 @node Fixed-Point Types and Representations
20413 @subsection Fixed-Point Types and Representations
20414
20415 @noindent
20416 On HP Ada for OpenVMS Alpha systems, rounding is
20417 away from zero for both positive and negative numbers.
20418 Therefore, @code{+0.5} rounds to @code{1},
20419 and @code{-0.5} rounds to @code{-1}.
20420
20421 On GNAT the results of operations
20422 on fixed-point types are in accordance with the Ada
20423 rules. In particular, results of operations on decimal
20424 fixed-point types are truncated.
20425
20426 @node Record and Array Component Alignment
20427 @subsection Record and Array Component Alignment
20428
20429 @noindent
20430 On HP Ada for OpenVMS Alpha, all non-composite components
20431 are aligned on natural boundaries. For example, 1-byte
20432 components are aligned on byte boundaries, 2-byte
20433 components on 2-byte boundaries, 4-byte components on 4-byte
20434 byte boundaries, and so on. The OpenVMS Alpha hardware
20435 runs more efficiently with naturally aligned data.
20436
20437 On GNAT, alignment rules are compatible
20438 with HP Ada for OpenVMS Alpha.
20439
20440 @node Address Clauses
20441 @subsection Address Clauses
20442
20443 @noindent
20444 In HP Ada and GNAT, address clauses are supported for
20445 objects and imported subprograms.
20446 The predefined type @code{System.Address} is a private type
20447 in both compilers on Alpha OpenVMS, with the same representation
20448 (it is simply a machine pointer). Addition, subtraction, and comparison
20449 operations are available in the standard Ada package
20450 @code{System.Storage_Elements}, or in package @code{System}
20451 if it is extended to include @code{System.Aux_DEC} using a
20452 pragma @code{Extend_System} as previously described.
20453
20454 Note that code that @code{with}'s both this extended package @code{System}
20455 and the package @code{System.Storage_Elements} should not @code{use}
20456 both packages, or ambiguities will result. In general it is better
20457 not to mix these two sets of facilities. The Ada package was
20458 designed specifically to provide the kind of features that HP Ada
20459 adds directly to package @code{System}.
20460
20461 The type @code{System.Address} is a 64-bit integer type in GNAT for
20462 I64 OpenVMS.  For more information,
20463 see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
20464
20465 GNAT is compatible with HP Ada in its handling of address
20466 clauses, except for some limitations in
20467 the form of address clauses for composite objects with
20468 initialization. Such address clauses are easily replaced
20469 by the use of an explicitly-defined constant as described
20470 in the Ada Reference Manual (13.1(22)). For example, the sequence
20471 of declarations:
20472
20473 @smallexample @c ada
20474 @cartouche
20475 X, Y : Integer := Init_Func;
20476 Q : String (X .. Y) := "abc";
20477 @dots{}
20478 for Q'Address use Compute_Address;
20479 @end cartouche
20480 @end smallexample
20481
20482 @noindent
20483 will be rejected by GNAT, since the address cannot be computed at the time
20484 that @code{Q} is declared. To achieve the intended effect, write instead:
20485
20486 @smallexample @c ada
20487 @group
20488 @cartouche
20489 X, Y : Integer := Init_Func;
20490 Q_Address : constant Address := Compute_Address;
20491 Q : String (X .. Y) := "abc";
20492 @dots{}
20493 for Q'Address use Q_Address;
20494 @end cartouche
20495 @end group
20496 @end smallexample
20497
20498 @noindent
20499 which will be accepted by GNAT (and other Ada compilers), and is also
20500 compatible with Ada 83. A fuller description of the restrictions
20501 on address specifications is found in @ref{Top, GNAT Reference Manual,
20502 About This Guide, gnat_rm, GNAT Reference Manual}.
20503
20504 @node Other Representation Clauses
20505 @subsection Other Representation Clauses
20506
20507 @noindent
20508 GNAT implements in a compatible manner all the representation
20509 clauses supported by HP Ada. In addition, GNAT
20510 implements the representation clause forms that were introduced in Ada 95,
20511 including @code{COMPONENT_SIZE} and @code{SIZE} clauses for objects.
20512
20513 @node The Package STANDARD
20514 @section The Package @code{STANDARD}
20515
20516 @noindent
20517 The package @code{STANDARD}, as implemented by HP Ada, is fully
20518 described in the @cite{Ada Reference Manual} and in the
20519 @cite{HP Ada Language Reference Manual}. As implemented by GNAT, the
20520 package @code{STANDARD} is described in the @cite{Ada Reference Manual}.
20521
20522 In addition, HP Ada supports the Latin-1 character set in
20523 the type @code{CHARACTER}. GNAT supports the Latin-1 character set
20524 in the type @code{CHARACTER} and also Unicode (ISO 10646 BMP) in
20525 the type @code{WIDE_CHARACTER}.
20526
20527 The floating-point types supported by GNAT are those
20528 supported by HP Ada, but the defaults are different, and are controlled by
20529 pragmas. See @ref{Floating-Point Types and Representations}, for details.
20530
20531 @node The Package SYSTEM
20532 @section The Package @code{SYSTEM}
20533
20534 @noindent
20535 HP Ada provides a specific version of the package
20536 @code{SYSTEM} for each platform on which the language is implemented.
20537 For the complete spec of the package @code{SYSTEM}, see
20538 Appendix F of the @cite{HP Ada Language Reference Manual}.
20539
20540 On HP Ada, the package @code{SYSTEM} includes the following conversion
20541 functions:
20542 @itemize @bullet
20543 @item @code{TO_ADDRESS(INTEGER)}
20544
20545 @item @code{TO_ADDRESS(UNSIGNED_LONGWORD)}
20546
20547 @item @code{TO_ADDRESS(}@i{universal_integer}@code{)}
20548
20549 @item @code{TO_INTEGER(ADDRESS)}
20550
20551 @item @code{TO_UNSIGNED_LONGWORD(ADDRESS)}
20552
20553 @item Function @code{IMPORT_VALUE return UNSIGNED_LONGWORD} and the
20554 functions @code{IMPORT_ADDRESS} and @code{IMPORT_LARGEST_VALUE}
20555 @end itemize
20556
20557 @noindent
20558 By default, GNAT supplies a version of @code{SYSTEM} that matches
20559 the definition given in the @cite{Ada Reference Manual}.
20560 This
20561 is a subset of the HP system definitions, which is as
20562 close as possible to the original definitions. The only difference
20563 is that the definition of @code{SYSTEM_NAME} is different:
20564
20565 @smallexample @c ada
20566 @cartouche
20567 type Name is (SYSTEM_NAME_GNAT);
20568 System_Name : constant Name := SYSTEM_NAME_GNAT;
20569 @end cartouche
20570 @end smallexample
20571
20572 @noindent
20573 Also, GNAT adds the Ada declarations for
20574 @code{BIT_ORDER} and @code{DEFAULT_BIT_ORDER}.
20575
20576 However, the use of the following pragma causes GNAT
20577 to extend the definition of package @code{SYSTEM} so that it
20578 encompasses the full set of HP-specific extensions,
20579 including the functions listed above:
20580
20581 @smallexample @c ada
20582 @cartouche
20583 pragma Extend_System (Aux_DEC);
20584 @end cartouche
20585 @end smallexample
20586
20587 @noindent
20588 The pragma @code{Extend_System} is a configuration pragma that
20589 is most conveniently placed in the @file{gnat.adc} file. @xref{Pragma
20590 Extend_System,,, gnat_rm, GNAT Reference Manual}, for further details.
20591
20592 HP Ada does not allow the recompilation of the package
20593 @code{SYSTEM}. Instead HP Ada provides several pragmas
20594 (@code{SYSTEM_NAME}, @code{STORAGE_UNIT}, and @code{MEMORY_SIZE})
20595 to modify values in the package @code{SYSTEM}.
20596 On OpenVMS Alpha systems, the pragma
20597 @code{SYSTEM_NAME} takes the enumeration literal @code{OPENVMS_AXP} as
20598 its single argument.
20599
20600 GNAT does permit the recompilation of package @code{SYSTEM} using
20601 the special switch @option{-gnatg}, and this switch can be used if
20602 it is necessary to modify the definitions in @code{SYSTEM}. GNAT does
20603 not permit the specification of @code{SYSTEM_NAME}, @code{STORAGE_UNIT}
20604 or @code{MEMORY_SIZE} by any other means.
20605
20606 On GNAT systems, the pragma @code{SYSTEM_NAME} takes the
20607 enumeration literal @code{SYSTEM_NAME_GNAT}.
20608
20609 The definitions provided by the use of
20610
20611 @smallexample @c ada
20612 pragma Extend_System (AUX_Dec);
20613 @end smallexample
20614
20615 @noindent
20616 are virtually identical to those provided by the HP Ada 83 package
20617 @code{SYSTEM}. One important difference is that the name of the
20618 @code{TO_ADDRESS}
20619 function for type @code{UNSIGNED_LONGWORD} is changed to
20620 @code{TO_ADDRESS_LONG}.
20621 @xref{Address Clauses,,, gnat_rm, GNAT Reference Manual}, for a
20622 discussion of why this change was necessary.
20623
20624 @noindent
20625 The version of @code{TO_ADDRESS} taking a @i{universal_integer} argument
20626 is in fact
20627 an extension to Ada 83 not strictly compatible with the reference manual.
20628 GNAT, in order to be exactly compatible with the standard,
20629 does not provide this capability. In HP Ada 83, the
20630 point of this definition is to deal with a call like:
20631
20632 @smallexample @c ada
20633 TO_ADDRESS (16#12777#);
20634 @end smallexample
20635
20636 @noindent
20637 Normally, according to Ada 83 semantics, one would expect this to be
20638 ambiguous, since it matches both the @code{INTEGER} and
20639 @code{UNSIGNED_LONGWORD} forms of @code{TO_ADDRESS}.
20640 However, in HP Ada 83, there is no ambiguity, since the
20641 definition using @i{universal_integer} takes precedence.
20642
20643 In GNAT, since the version with @i{universal_integer} cannot be supplied,
20644 it is
20645 not possible to be 100% compatible. Since there are many programs using
20646 numeric constants for the argument to @code{TO_ADDRESS}, the decision in
20647 GNAT was
20648 to change the name of the function in the @code{UNSIGNED_LONGWORD} case,
20649 so the declarations provided in the GNAT version of @code{AUX_Dec} are:
20650
20651 @smallexample @c ada
20652 function To_Address (X : Integer) return Address;
20653 pragma Pure_Function (To_Address);
20654
20655 function To_Address_Long (X : Unsigned_Longword) return Address;
20656 pragma Pure_Function (To_Address_Long);
20657 @end smallexample
20658
20659 @noindent
20660 This means that programs using @code{TO_ADDRESS} for
20661 @code{UNSIGNED_LONGWORD} must change the name to @code{TO_ADDRESS_LONG}.
20662
20663 @node Tasking and Task-Related Features
20664 @section Tasking and Task-Related Features
20665
20666 @noindent
20667 This section compares the treatment of tasking in GNAT
20668 and in HP Ada for OpenVMS Alpha.
20669 The GNAT description applies to both Alpha and I64 OpenVMS.
20670 For detailed information on tasking in
20671 HP Ada, see the @cite{HP Ada Language Reference Manual} and the
20672 relevant run-time reference manual.
20673
20674 @menu
20675 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
20676 * Assigning Task IDs::
20677 * Task IDs and Delays::
20678 * Task-Related Pragmas::
20679 * Scheduling and Task Priority::
20680 * The Task Stack::
20681 * External Interrupts::
20682 @end menu
20683
20684 @node Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
20685 @subsection Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
20686
20687 @noindent
20688 On OpenVMS Alpha systems, each Ada task (except a passive
20689 task) is implemented as a single stream of execution
20690 that is created and managed by the kernel. On these
20691 systems, HP Ada tasking support is based on DECthreads,
20692 an implementation of the POSIX standard for threads.
20693
20694 Also, on OpenVMS Alpha systems, HP Ada tasks and foreign
20695 code that calls DECthreads routines can be used together.
20696 The interaction between Ada tasks and DECthreads routines
20697 can have some benefits. For example when on OpenVMS Alpha,
20698 HP Ada can call C code that is already threaded.
20699
20700 GNAT uses the facilities of DECthreads,
20701 and Ada tasks are mapped to threads.
20702
20703 @node Assigning Task IDs
20704 @subsection Assigning Task IDs
20705
20706 @noindent
20707 The HP Ada Run-Time Library always assigns @code{%TASK 1} to
20708 the environment task that executes the main program. On
20709 OpenVMS Alpha systems, @code{%TASK 0} is often used for tasks
20710 that have been created but are not yet activated.
20711
20712 On OpenVMS Alpha systems, task IDs are assigned at
20713 activation. On GNAT systems, task IDs are also assigned at
20714 task creation but do not have the same form or values as
20715 task ID values in HP Ada. There is no null task, and the
20716 environment task does not have a specific task ID value.
20717
20718 @node Task IDs and Delays
20719 @subsection Task IDs and Delays
20720
20721 @noindent
20722 On OpenVMS Alpha systems, tasking delays are implemented
20723 using Timer System Services. The Task ID is used for the
20724 identification of the timer request (the @code{REQIDT} parameter).
20725 If Timers are used in the application take care not to use
20726 @code{0} for the identification, because cancelling such a timer
20727 will cancel all timers and may lead to unpredictable results.
20728
20729 @node Task-Related Pragmas
20730 @subsection Task-Related Pragmas
20731
20732 @noindent
20733 Ada supplies the pragma @code{TASK_STORAGE}, which allows
20734 specification of the size of the guard area for a task
20735 stack. (The guard area forms an area of memory that has no
20736 read or write access and thus helps in the detection of
20737 stack overflow.) On OpenVMS Alpha systems, if the pragma
20738 @code{TASK_STORAGE} specifies a value of zero, a minimal guard
20739 area is created. In the absence of a pragma @code{TASK_STORAGE},
20740 a default guard area is created.
20741
20742 GNAT supplies the following task-related pragmas:
20743
20744 @itemize @bullet
20745 @item  @code{TASK_INFO}
20746
20747 This pragma appears within a task definition and
20748 applies to the task in which it appears. The argument
20749 must be of type @code{SYSTEM.TASK_INFO.TASK_INFO_TYPE}.
20750
20751 @item  @code{TASK_STORAGE}
20752
20753 GNAT implements pragma @code{TASK_STORAGE} in the same way as HP Ada.
20754 Both HP Ada and GNAT supply the pragmas @code{PASSIVE},
20755 @code{SUPPRESS}, and @code{VOLATILE}.
20756 @end itemize
20757 @node Scheduling and Task Priority
20758 @subsection Scheduling and Task Priority
20759
20760 @noindent
20761 HP Ada implements the Ada language requirement that
20762 when two tasks are eligible for execution and they have
20763 different priorities, the lower priority task does not
20764 execute while the higher priority task is waiting. The HP
20765 Ada Run-Time Library keeps a task running until either the
20766 task is suspended or a higher priority task becomes ready.
20767
20768 On OpenVMS Alpha systems, the default strategy is round-
20769 robin with preemption. Tasks of equal priority take turns
20770 at the processor. A task is run for a certain period of
20771 time and then placed at the tail of the ready queue for
20772 its priority level.
20773
20774 HP Ada provides the implementation-defined pragma @code{TIME_SLICE},
20775 which can be used to enable or disable round-robin
20776 scheduling of tasks with the same priority.
20777 See the relevant HP Ada run-time reference manual for
20778 information on using the pragmas to control HP Ada task
20779 scheduling.
20780
20781 GNAT follows the scheduling rules of Annex D (Real-Time
20782 Annex) of the @cite{Ada Reference Manual}. In general, this
20783 scheduling strategy is fully compatible with HP Ada
20784 although it provides some additional constraints (as
20785 fully documented in Annex D).
20786 GNAT implements time slicing control in a manner compatible with
20787 HP Ada 83, by means of the pragma @code{Time_Slice}, whose semantics
20788 are identical to the HP Ada 83 pragma of the same name.
20789 Note that it is not possible to mix GNAT tasking and
20790 HP Ada 83 tasking in the same program, since the two run-time
20791 libraries are not compatible.
20792
20793 @node The Task Stack
20794 @subsection The Task Stack
20795
20796 @noindent
20797 In HP Ada, a task stack is allocated each time a
20798 non-passive task is activated. As soon as the task is
20799 terminated, the storage for the task stack is deallocated.
20800 If you specify a size of zero (bytes) with @code{T'STORAGE_SIZE},
20801 a default stack size is used. Also, regardless of the size
20802 specified, some additional space is allocated for task
20803 management purposes. On OpenVMS Alpha systems, at least
20804 one page is allocated.
20805
20806 GNAT handles task stacks in a similar manner. In accordance with
20807 the Ada rules, it provides the pragma @code{STORAGE_SIZE} as
20808 an alternative method for controlling the task stack size.
20809 The specification of the attribute @code{T'STORAGE_SIZE} is also
20810 supported in a manner compatible with HP Ada.
20811
20812 @node External Interrupts
20813 @subsection External Interrupts
20814
20815 @noindent
20816 On HP Ada, external interrupts can be associated with task entries.
20817 GNAT is compatible with HP Ada in its handling of external interrupts.
20818
20819 @node Pragmas and Pragma-Related Features
20820 @section Pragmas and Pragma-Related Features
20821
20822 @noindent
20823 Both HP Ada and GNAT supply all language-defined pragmas
20824 as specified by the Ada 83 standard. GNAT also supplies all
20825 language-defined pragmas introduced by Ada 95 and Ada 2005.
20826 In addition, GNAT implements the implementation-defined pragmas
20827 from HP Ada 83.
20828
20829 @itemize @bullet
20830 @item  @code{AST_ENTRY}
20831
20832 @item  @code{COMMON_OBJECT}
20833
20834 @item  @code{COMPONENT_ALIGNMENT}
20835
20836 @item  @code{EXPORT_EXCEPTION}
20837
20838 @item  @code{EXPORT_FUNCTION}
20839
20840 @item  @code{EXPORT_OBJECT}
20841
20842 @item  @code{EXPORT_PROCEDURE}
20843
20844 @item  @code{EXPORT_VALUED_PROCEDURE}
20845
20846 @item  @code{FLOAT_REPRESENTATION}
20847
20848 @item  @code{IDENT}
20849
20850 @item  @code{IMPORT_EXCEPTION}
20851
20852 @item  @code{IMPORT_FUNCTION}
20853
20854 @item  @code{IMPORT_OBJECT}
20855
20856 @item  @code{IMPORT_PROCEDURE}
20857
20858 @item  @code{IMPORT_VALUED_PROCEDURE}
20859
20860 @item  @code{INLINE_GENERIC}
20861
20862 @item  @code{INTERFACE_NAME}
20863
20864 @item  @code{LONG_FLOAT}
20865
20866 @item  @code{MAIN_STORAGE}
20867
20868 @item  @code{PASSIVE}
20869
20870 @item  @code{PSECT_OBJECT}
20871
20872 @item  @code{SHARE_GENERIC}
20873
20874 @item  @code{SUPPRESS_ALL}
20875
20876 @item  @code{TASK_STORAGE}
20877
20878 @item  @code{TIME_SLICE}
20879
20880 @item  @code{TITLE}
20881 @end itemize
20882
20883 @noindent
20884 These pragmas are all fully implemented, with the exception of @code{TITLE},
20885 @code{PASSIVE}, and @code{SHARE_GENERIC}, which are
20886 recognized, but which have no
20887 effect in GNAT. The effect of @code{PASSIVE} may be obtained by the
20888 use of Ada protected objects. In GNAT, all generics are inlined.
20889
20890 Unlike HP Ada, the GNAT ``@code{EXPORT_}@i{subprogram}'' pragmas require
20891 a separate subprogram specification which must appear before the
20892 subprogram body.
20893
20894 GNAT also supplies a number of implementation-defined pragmas including the
20895 following:
20896
20897 @itemize @bullet
20898 @item  @code{ABORT_DEFER}
20899
20900 @item  @code{ADA_83}
20901
20902 @item  @code{ADA_95}
20903
20904 @item  @code{ADA_05}
20905
20906 @item  @code{Ada_2005}
20907
20908 @item  @code{Ada_12}
20909
20910 @item  @code{Ada_2012}
20911
20912 @item  @code{ANNOTATE}
20913
20914 @item  @code{ASSERT}
20915
20916 @item  @code{C_PASS_BY_COPY}
20917
20918 @item  @code{CPP_CLASS}
20919
20920 @item  @code{CPP_CONSTRUCTOR}
20921
20922 @item  @code{CPP_DESTRUCTOR}
20923
20924 @item  @code{DEBUG}
20925
20926 @item  @code{EXTEND_SYSTEM}
20927
20928 @item  @code{LINKER_ALIAS}
20929
20930 @item  @code{LINKER_SECTION}
20931
20932 @item  @code{MACHINE_ATTRIBUTE}
20933
20934 @item  @code{NO_RETURN}
20935
20936 @item  @code{PURE_FUNCTION}
20937
20938 @item  @code{SOURCE_FILE_NAME}
20939
20940 @item  @code{SOURCE_REFERENCE}
20941
20942 @item  @code{TASK_INFO}
20943
20944 @item  @code{UNCHECKED_UNION}
20945
20946 @item  @code{UNIMPLEMENTED_UNIT}
20947
20948 @item  @code{UNIVERSAL_DATA}
20949
20950 @item  @code{UNSUPPRESS}
20951
20952 @item  @code{WARNINGS}
20953
20954 @item  @code{WEAK_EXTERNAL}
20955 @end itemize
20956
20957 @noindent
20958 For full details on these and other GNAT implementation-defined pragmas,
20959 see @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference
20960 Manual}.
20961
20962 @menu
20963 * Restrictions on the Pragma INLINE::
20964 * Restrictions on the Pragma INTERFACE::
20965 * Restrictions on the Pragma SYSTEM_NAME::
20966 @end menu
20967
20968 @node Restrictions on the Pragma INLINE
20969 @subsection Restrictions on Pragma @code{INLINE}
20970
20971 @noindent
20972 HP Ada enforces the following restrictions on the pragma @code{INLINE}:
20973 @itemize @bullet
20974 @item  Parameters cannot have a task type.
20975
20976 @item  Function results cannot be task types, unconstrained
20977 array types, or unconstrained types with discriminants.
20978
20979 @item  Bodies cannot declare the following:
20980 @itemize @bullet
20981 @item  Subprogram body or stub (imported subprogram is allowed)
20982
20983 @item  Tasks
20984
20985 @item  Generic declarations
20986
20987 @item  Instantiations
20988
20989 @item  Exceptions
20990
20991 @item  Access types (types derived from access types allowed)
20992
20993 @item  Array or record types
20994
20995 @item  Dependent tasks
20996
20997 @item  Direct recursive calls of subprogram or containing
20998 subprogram, directly or via a renaming
20999
21000 @end itemize
21001 @end itemize
21002
21003 @noindent
21004 In GNAT, the only restriction on pragma @code{INLINE} is that the
21005 body must occur before the call if both are in the same
21006 unit, and the size must be appropriately small. There are
21007 no other specific restrictions which cause subprograms to
21008 be incapable of being inlined.
21009
21010 @node  Restrictions on the Pragma INTERFACE
21011 @subsection  Restrictions on Pragma @code{INTERFACE}
21012
21013 @noindent
21014 The following restrictions on pragma @code{INTERFACE}
21015 are enforced by both HP Ada and GNAT:
21016 @itemize @bullet
21017 @item  Languages accepted: Ada, Bliss, C, Fortran, Default.
21018 Default is the default on OpenVMS Alpha systems.
21019
21020 @item  Parameter passing: Language specifies default
21021 mechanisms but can be overridden with an @code{EXPORT} pragma.
21022
21023 @itemize @bullet
21024 @item  Ada: Use internal Ada rules.
21025
21026 @item  Bliss, C: Parameters must be mode @code{in}; cannot be
21027 record or task type. Result cannot be a string, an
21028 array, or a record.
21029
21030 @item  Fortran: Parameters cannot have a task type. Result cannot
21031 be a string, an array, or a record.
21032 @end itemize
21033 @end itemize
21034
21035 @noindent
21036 GNAT is entirely upwards compatible with HP Ada, and in addition allows
21037 record parameters for all languages.
21038
21039 @node  Restrictions on the Pragma SYSTEM_NAME
21040 @subsection  Restrictions on Pragma @code{SYSTEM_NAME}
21041
21042 @noindent
21043 For HP Ada for OpenVMS Alpha, the enumeration literal
21044 for the type @code{NAME} is @code{OPENVMS_AXP}.
21045 In GNAT, the enumeration
21046 literal for the type @code{NAME} is @code{SYSTEM_NAME_GNAT}.
21047
21048 @node  Library of Predefined Units
21049 @section  Library of Predefined Units
21050
21051 @noindent
21052 A library of predefined units is provided as part of the
21053 HP Ada and GNAT implementations. HP Ada does not provide
21054 the package @code{MACHINE_CODE} but instead recommends importing
21055 assembler code.
21056
21057 The GNAT versions of the HP Ada Run-Time Library (@code{ADA$PREDEFINED:})
21058 units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
21059 version.
21060 The HP Ada Predefined Library units are modified to remove post-Ada 83
21061 incompatibilities and to make them interoperable with GNAT
21062 (@pxref{Changes to DECLIB}, for details).
21063 The units are located in the @file{DECLIB} directory.
21064
21065 The GNAT RTL is contained in
21066 the @file{ADALIB} directory, and
21067 the default search path is set up to find @code{DECLIB} units in preference
21068 to @code{ADALIB} units with the same name (@code{TEXT_IO},
21069 @code{SEQUENTIAL_IO}, and @code{DIRECT_IO}, for example).
21070
21071 @menu
21072 * Changes to DECLIB::
21073 @end menu
21074
21075 @node Changes to DECLIB
21076 @subsection Changes to @code{DECLIB}
21077
21078 @noindent
21079 The changes made to the HP Ada predefined library for GNAT and post-Ada 83
21080 compatibility are minor and include the following:
21081
21082 @itemize @bullet
21083 @item  Adjusting the location of pragmas and record representation
21084 clauses to obey Ada 95 (and thus Ada 2005) rules
21085
21086 @item  Adding the proper notation to generic formal parameters
21087 that take unconstrained types in instantiation
21088
21089 @item  Adding pragma @code{ELABORATE_BODY} to package specs
21090 that have package bodies not otherwise allowed
21091
21092 @item  Replacing occurrences of the identifier ``@code{PROTECTED}'' by
21093 ``@code{PROTECTD}''.
21094 Currently these are found only in the @code{STARLET} package spec.
21095
21096 @item Changing @code{SYSTEM.ADDRESS} to @code{SYSTEM.SHORT_ADDRESS}
21097 where the address size is constrained to 32 bits.
21098 @end itemize
21099
21100 @noindent
21101 None of the above changes is visible to users.
21102
21103 @node Bindings
21104 @section Bindings
21105
21106 @noindent
21107 On OpenVMS Alpha, HP Ada provides the following strongly-typed bindings:
21108 @itemize @bullet
21109
21110 @item  Command Language Interpreter (CLI interface)
21111
21112 @item  DECtalk Run-Time Library (DTK interface)
21113
21114 @item  Librarian utility routines (LBR interface)
21115
21116 @item  General Purpose Run-Time Library (LIB interface)
21117
21118 @item  Math Run-Time Library (MTH interface)
21119
21120 @item  National Character Set Run-Time Library (NCS interface)
21121
21122 @item  Compiled Code Support Run-Time Library (OTS interface)
21123
21124 @item  Parallel Processing Run-Time Library (PPL interface)
21125
21126 @item  Screen Management Run-Time Library (SMG interface)
21127
21128 @item  Sort Run-Time Library (SOR interface)
21129
21130 @item  String Run-Time Library (STR interface)
21131
21132 @item STARLET System Library
21133 @findex Starlet
21134
21135 @item  X Window System Version 11R4 and 11R5 (X, XLIB interface)
21136
21137 @item  X Windows Toolkit (XT interface)
21138
21139 @item  X/Motif Version 1.1.3 and 1.2 (XM interface)
21140 @end itemize
21141
21142 @noindent
21143 GNAT provides implementations of these HP bindings in the @code{DECLIB}
21144 directory, on both the Alpha and I64 OpenVMS platforms.
21145
21146 The X components of DECLIB compatibility package are located in a separate
21147 library, called XDECGNAT, which is not linked with by default; this library
21148 must be explicitly linked with any application that makes use of any X facilities,
21149 with a command similar to
21150
21151 @code{GNAT MAKE USE_X /LINK /LIBRARY=XDECGNAT}
21152
21153 The X/Motif bindings used to build @code{DECLIB} are whatever versions are
21154 in the
21155 HP Ada @file{ADA$PREDEFINED} directory with extension @file{.ADC}.
21156 A pragma @code{Linker_Options} has been added to packages @code{Xm},
21157 @code{Xt}, and @code{X_Lib}
21158 causing the default X/Motif sharable image libraries to be linked in. This
21159 is done via options files named @file{xm.opt}, @file{xt.opt}, and
21160 @file{x_lib.opt} (also located in the @file{DECLIB} directory).
21161
21162 It may be necessary to edit these options files to update or correct the
21163 library names if, for example, the newer X/Motif bindings from
21164 @file{ADA$EXAMPLES}
21165 had been (previous to installing GNAT) copied and renamed to supersede the
21166 default @file{ADA$PREDEFINED} versions.
21167
21168 @menu
21169 * Shared Libraries and Options Files::
21170 * Interfaces to C::
21171 @end menu
21172
21173 @node Shared Libraries and Options Files
21174 @subsection Shared Libraries and Options Files
21175
21176 @noindent
21177 When using the HP Ada
21178 predefined X and Motif bindings, the linking with their sharable images is
21179 done automatically by @command{GNAT LINK}.
21180 When using other X and Motif bindings, you need
21181 to add the corresponding sharable images to the command line for
21182 @code{GNAT LINK}. When linking with shared libraries, or with
21183 @file{.OPT} files, you must
21184 also add them to the command line for @command{GNAT LINK}.
21185
21186 A shared library to be used with GNAT is built in the same way as other
21187 libraries under VMS. The VMS Link command can be used in standard fashion.
21188
21189 @node Interfaces to C
21190 @subsection Interfaces to C
21191
21192 @noindent
21193 HP Ada
21194 provides the following Ada types and operations:
21195
21196 @itemize @bullet
21197 @item C types package (@code{C_TYPES})
21198
21199 @item C strings (@code{C_TYPES.NULL_TERMINATED})
21200
21201 @item Other_types (@code{SHORT_INT})
21202 @end itemize
21203
21204 @noindent
21205 Interfacing to C with GNAT, you can use the above approach
21206 described for HP Ada or the facilities of Annex B of
21207 the @cite{Ada Reference Manual} (packages @code{INTERFACES.C},
21208 @code{INTERFACES.C.STRINGS} and @code{INTERFACES.C.POINTERS}). For more
21209 information, see @ref{Interfacing to C,,, gnat_rm, GNAT Reference Manual}.
21210
21211 The @option{-gnatF} qualifier forces default and explicit
21212 @code{External_Name} parameters in pragmas @code{Import} and @code{Export}
21213 to be uppercased for compatibility with the default behavior
21214 of HP C. The qualifier has no effect on @code{Link_Name} parameters.
21215
21216 @node Main Program Definition
21217 @section Main Program Definition
21218
21219 @noindent
21220 The following section discusses differences in the
21221 definition of main programs on HP Ada and GNAT.
21222 On HP Ada, main programs are defined to meet the
21223 following conditions:
21224 @itemize @bullet
21225 @item  Procedure with no formal parameters (returns @code{0} upon
21226 normal completion)
21227
21228 @item  Procedure with no formal parameters (returns @code{42} when
21229 an unhandled exception is raised)
21230
21231 @item  Function with no formal parameters whose returned value
21232 is of a discrete type
21233
21234 @item  Procedure with one @code{out} formal of a discrete type for
21235 which a specification of pragma @code{EXPORT_VALUED_PROCEDURE} is given.
21236
21237 @end itemize
21238
21239 @noindent
21240 When declared with the pragma @code{EXPORT_VALUED_PROCEDURE},
21241 a main function or main procedure returns a discrete
21242 value whose size is less than 64 bits (32 on VAX systems),
21243 the value is zero- or sign-extended as appropriate.
21244 On GNAT, main programs are defined as follows:
21245 @itemize @bullet
21246 @item  Must be a non-generic, parameterless subprogram that
21247 is either a procedure or function returning an Ada
21248 @code{STANDARD.INTEGER} (the predefined type)
21249
21250 @item  Cannot be a generic subprogram or an instantiation of a
21251 generic subprogram
21252 @end itemize
21253
21254 @node Implementation-Defined Attributes
21255 @section Implementation-Defined Attributes
21256
21257 @noindent
21258 GNAT provides all HP Ada implementation-defined
21259 attributes.
21260
21261 @node Compiler and Run-Time Interfacing
21262 @section Compiler and Run-Time Interfacing
21263
21264 @noindent
21265 HP Ada provides the following qualifiers to pass options to the linker
21266 (ACS LINK):
21267 @itemize @bullet
21268 @item  @option{/WAIT} and @option{/SUBMIT}
21269
21270 @item  @option{/COMMAND}
21271
21272 @item  @option{/@r{[}NO@r{]}MAP}
21273
21274 @item  @option{/OUTPUT=@var{file-spec}}
21275
21276 @item  @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
21277 @end itemize
21278
21279 @noindent
21280 To pass options to the linker, GNAT provides the following
21281 switches:
21282
21283 @itemize @bullet
21284 @item   @option{/EXECUTABLE=@var{exec-name}}
21285
21286 @item   @option{/VERBOSE}
21287
21288 @item   @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
21289 @end itemize
21290
21291 @noindent
21292 For more information on these switches, see
21293 @ref{Switches for gnatlink}.
21294 In HP Ada, the command-line switch @option{/OPTIMIZE} is available
21295 to control optimization. HP Ada also supplies the
21296 following pragmas:
21297 @itemize @bullet
21298 @item  @code{OPTIMIZE}
21299
21300 @item  @code{INLINE}
21301
21302 @item  @code{INLINE_GENERIC}
21303
21304 @item  @code{SUPPRESS_ALL}
21305
21306 @item  @code{PASSIVE}
21307 @end itemize
21308
21309 @noindent
21310 In GNAT, optimization is controlled strictly by command
21311 line parameters, as described in the corresponding section of this guide.
21312 The HP pragmas for control of optimization are
21313 recognized but ignored.
21314
21315 Note that in GNAT, the default is optimization off, whereas in HP Ada
21316 the default is that optimization is turned on.
21317
21318 @node Program Compilation and Library Management
21319 @section Program Compilation and Library Management
21320
21321 @noindent
21322 HP Ada and GNAT provide a comparable set of commands to
21323 build programs. HP Ada also provides a program library,
21324 which is a concept that does not exist on GNAT. Instead,
21325 GNAT provides directories of sources that are compiled as
21326 needed.
21327
21328 The following table summarizes
21329 the HP Ada commands and provides
21330 equivalent GNAT commands. In this table, some GNAT
21331 equivalents reflect the fact that GNAT does not use the
21332 concept of a program library. Instead, it uses a model
21333 in which collections of source and object files are used
21334 in a manner consistent with other languages like C and
21335 Fortran. Therefore, standard system file commands are used
21336 to manipulate these elements. Those GNAT commands are marked with
21337 an asterisk.
21338 Note that, unlike HP Ada, none of the GNAT commands accepts wild cards.
21339
21340 @need 1500
21341 @multitable @columnfractions .35 .65
21342
21343 @item @emph{HP Ada Command}
21344 @tab @emph{GNAT Equivalent / Description}
21345
21346 @item @command{ADA}
21347 @tab @command{GNAT COMPILE}@*
21348 Invokes the compiler to compile one or more Ada source files.
21349
21350 @item @command{ACS ATTACH}@*
21351 @tab [No equivalent]@*
21352 Switches control of terminal from current process running the program
21353 library manager.
21354
21355 @item @command{ACS CHECK}
21356 @tab @command{GNAT MAKE /DEPENDENCY_LIST}@*
21357 Forms the execution closure of one
21358 or more compiled units and checks completeness and currency.
21359
21360 @item @command{ACS COMPILE}
21361 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
21362 Forms the execution closure of one or
21363 more specified units, checks completeness and currency,
21364 identifies units that have revised source files, compiles same,
21365 and recompiles units that are or will become obsolete.
21366 Also completes incomplete generic instantiations.
21367
21368 @item @command{ACS COPY FOREIGN}
21369 @tab Copy (*)@*
21370 Copies a foreign object file into the program library as a
21371 library unit body.
21372
21373 @item @command{ACS COPY UNIT}
21374 @tab Copy (*)@*
21375 Copies a compiled unit from one program library to another.
21376
21377 @item @command{ACS CREATE LIBRARY}
21378 @tab Create /directory (*)@*
21379 Creates a program library.
21380
21381 @item @command{ACS CREATE SUBLIBRARY}
21382 @tab Create /directory (*)@*
21383 Creates a program sublibrary.
21384
21385 @item @command{ACS DELETE LIBRARY}
21386 @tab @*
21387 Deletes a program library and its contents.
21388
21389 @item @command{ACS DELETE SUBLIBRARY}
21390 @tab @*
21391 Deletes a program sublibrary and its contents.
21392
21393 @item @command{ACS DELETE UNIT}
21394 @tab Delete file (*)@*
21395 On OpenVMS systems, deletes one or more compiled units from
21396 the current program library.
21397
21398 @item @command{ACS DIRECTORY}
21399 @tab Directory (*)@*
21400 On OpenVMS systems, lists units contained in the current
21401 program library.
21402
21403 @item @command{ACS ENTER FOREIGN}
21404 @tab Copy (*)@*
21405 Allows the import of a foreign body as an Ada library
21406 spec and enters a reference to a pointer.
21407
21408 @item @command{ACS ENTER UNIT}
21409 @tab Copy (*)@*
21410 Enters a reference (pointer) from the current program library to
21411 a unit compiled into another program library.
21412
21413 @item @command{ACS EXIT}
21414 @tab [No equivalent]@*
21415 Exits from the program library manager.
21416
21417 @item @command{ACS EXPORT}
21418 @tab Copy (*)@*
21419 Creates an object file that contains system-specific object code
21420 for one or more units. With GNAT, object files can simply be copied
21421 into the desired directory.
21422
21423 @item @command{ACS EXTRACT SOURCE}
21424 @tab Copy (*)@*
21425 Allows access to the copied source file for each Ada compilation unit
21426
21427 @item @command{ACS HELP}
21428 @tab @command{HELP GNAT}@*
21429 Provides online help.
21430
21431 @item @command{ACS LINK}
21432 @tab @command{GNAT LINK}@*
21433 Links an object file containing Ada units into an executable file.
21434
21435 @item @command{ACS LOAD}
21436 @tab Copy (*)@*
21437 Loads (partially compiles) Ada units into the program library.
21438 Allows loading a program from a collection of files into a library
21439 without knowing the relationship among units.
21440
21441 @item @command{ACS MERGE}
21442 @tab Copy (*)@*
21443 Merges into the current program library, one or more units from
21444 another library where they were modified.
21445
21446 @item @command{ACS RECOMPILE}
21447 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
21448 Recompiles from   external or copied source files any obsolete
21449 unit in the closure. Also, completes any incomplete generic
21450 instantiations.
21451
21452 @item @command{ACS REENTER}
21453 @tab @command{GNAT MAKE}@*
21454 Reenters current references to units compiled after last entered
21455 with the @command{ACS ENTER UNIT} command.
21456
21457 @item @command{ACS SET LIBRARY}
21458 @tab Set default (*)@*
21459 Defines a program library to be the compilation context as well
21460 as the target library for compiler output and commands in general.
21461
21462 @item @command{ACS SET PRAGMA}
21463 @tab Edit @file{gnat.adc} (*)@*
21464 Redefines specified  values of the library characteristics
21465 @code{LONG_ FLOAT}, @code{MEMORY_SIZE}, @code{SYSTEM_NAME},
21466 and @code{Float_Representation}.
21467
21468 @item @command{ACS SET SOURCE}
21469 @tab Define @code{ADA_INCLUDE_PATH} path (*)@*
21470 Defines the source file search list for the @command{ACS COMPILE} command.
21471
21472 @item @command{ACS SHOW LIBRARY}
21473 @tab Directory (*)@*
21474 Lists information about one or more program libraries.
21475
21476 @item @command{ACS SHOW PROGRAM}
21477 @tab [No equivalent]@*
21478 Lists information about the execution closure of one or
21479 more units in the program library.
21480
21481 @item @command{ACS SHOW SOURCE}
21482 @tab Show logical @code{ADA_INCLUDE_PATH}@*
21483 Shows the source file search used when compiling units.
21484
21485 @item @command{ACS SHOW VERSION}
21486 @tab Compile with @option{VERBOSE} option
21487 Displays the version number of the compiler and program library
21488 manager used.
21489
21490 @item @command{ACS SPAWN}
21491 @tab [No equivalent]@*
21492 Creates a subprocess of the current process (same as @command{DCL SPAWN}
21493 command).
21494
21495 @item @command{ACS VERIFY}
21496 @tab [No equivalent]@*
21497 Performs a series of consistency checks on a program library to
21498 determine whether the library structure and library files are in
21499 valid form.
21500 @end multitable
21501
21502 @noindent
21503
21504 @node Input-Output
21505 @section Input-Output
21506
21507 @noindent
21508 On OpenVMS Alpha systems, HP Ada uses OpenVMS Record
21509 Management Services (RMS) to perform operations on
21510 external files.
21511
21512 @noindent
21513 HP Ada and GNAT predefine an identical set of input-
21514 output packages. To make the use of the
21515 generic @code{TEXT_IO} operations more convenient, HP Ada
21516 provides predefined library packages that instantiate the
21517 integer and floating-point operations for the predefined
21518 integer and floating-point types as shown in the following table.
21519
21520 @multitable @columnfractions .45 .55
21521 @item @emph{Package Name} @tab Instantiation
21522
21523 @item @code{INTEGER_TEXT_IO}
21524 @tab @code{INTEGER_IO(INTEGER)}
21525
21526 @item @code{SHORT_INTEGER_TEXT_IO}
21527 @tab @code{INTEGER_IO(SHORT_INTEGER)}
21528
21529 @item @code{SHORT_SHORT_INTEGER_TEXT_IO}
21530 @tab @code{INTEGER_IO(SHORT_SHORT_INTEGER)}
21531
21532 @item @code{FLOAT_TEXT_IO}
21533 @tab @code{FLOAT_IO(FLOAT)}
21534
21535 @item @code{LONG_FLOAT_TEXT_IO}
21536 @tab @code{FLOAT_IO(LONG_FLOAT)}
21537 @end multitable
21538
21539 @noindent
21540 The HP Ada predefined packages and their operations
21541 are implemented using OpenVMS Alpha files and input-output
21542 facilities. HP Ada supports asynchronous input-output on OpenVMS Alpha.
21543 Familiarity with the following is recommended:
21544 @itemize @bullet
21545 @item  RMS file organizations and access methods
21546
21547 @item  OpenVMS file specifications and directories
21548
21549 @item  OpenVMS File Definition Language (FDL)
21550 @end itemize
21551
21552 @noindent
21553 GNAT provides I/O facilities that are completely
21554 compatible with HP Ada. The distribution includes the
21555 standard HP Ada versions of all I/O packages, operating
21556 in a manner compatible with HP Ada. In particular, the
21557 following packages are by default the HP Ada (Ada 83)
21558 versions of these packages rather than the renamings
21559 suggested in Annex J of the Ada Reference Manual:
21560 @itemize @bullet
21561 @item  @code{TEXT_IO}
21562
21563 @item  @code{SEQUENTIAL_IO}
21564
21565 @item  @code{DIRECT_IO}
21566 @end itemize
21567
21568 @noindent
21569 The use of the standard child package syntax (for
21570 example, @code{ADA.TEXT_IO}) retrieves the post-Ada 83 versions of these
21571 packages.
21572 GNAT provides HP-compatible predefined instantiations
21573 of the @code{TEXT_IO} packages, and also
21574 provides the standard predefined instantiations required
21575 by the @cite{Ada Reference Manual}.
21576
21577 For further information on how GNAT interfaces to the file
21578 system or how I/O is implemented in programs written in
21579 mixed languages, see @ref{Implementation of the Standard I/O,,,
21580 gnat_rm, GNAT Reference Manual}.
21581 This chapter covers the following:
21582 @itemize @bullet
21583 @item  Standard I/O packages
21584
21585 @item  @code{FORM} strings
21586
21587 @item  @code{ADA.DIRECT_IO}
21588
21589 @item  @code{ADA.SEQUENTIAL_IO}
21590
21591 @item  @code{ADA.TEXT_IO}
21592
21593 @item  Stream pointer positioning
21594
21595 @item  Reading and writing non-regular files
21596
21597 @item  @code{GET_IMMEDIATE}
21598
21599 @item  Treating @code{TEXT_IO} files as streams
21600
21601 @item  Shared files
21602
21603 @item  Open modes
21604 @end itemize
21605
21606 @node Implementation Limits
21607 @section Implementation Limits
21608
21609 @noindent
21610 The following table lists implementation limits for HP Ada
21611 and GNAT systems.
21612 @multitable @columnfractions .60 .20 .20
21613 @sp 1
21614 @item  @emph{Compilation Parameter}
21615 @tab   @emph{HP Ada}
21616 @tab   @emph{GNAT}
21617 @sp 1
21618
21619 @item  In a subprogram or entry  declaration, maximum number of
21620 formal parameters that are of an unconstrained record type
21621 @tab   32
21622 @tab   No set limit
21623 @sp 1
21624
21625 @item  Maximum identifier length (number of characters)
21626 @tab   255
21627 @tab   32766
21628 @sp 1
21629
21630 @item  Maximum number of characters in a source line
21631 @tab   255
21632 @tab   32766
21633 @sp 1
21634
21635 @item  Maximum collection size   (number of bytes)
21636 @tab   2**31-1
21637 @tab   2**31-1
21638 @sp 1
21639
21640 @item  Maximum number of discriminants for a record type
21641 @tab   245
21642 @tab   No set limit
21643 @sp 1
21644
21645 @item  Maximum number of formal parameters in an entry or
21646 subprogram declaration
21647 @tab   246
21648 @tab    No set limit
21649 @sp 1
21650
21651 @item  Maximum number of dimensions in an array type
21652 @tab   255
21653 @tab   No set limit
21654 @sp 1
21655
21656 @item  Maximum number of library  units and subunits in a compilation.
21657 @tab   4095
21658 @tab   No set limit
21659 @sp 1
21660
21661 @item  Maximum number of library units and subunits in an execution.
21662 @tab   16383
21663 @tab   No set limit
21664 @sp 1
21665
21666 @item  Maximum number of objects declared with the pragma @code{COMMON_OBJECT}
21667 or @code{PSECT_OBJECT}
21668 @tab   32757
21669 @tab   No set limit
21670 @sp 1
21671
21672 @item  Maximum number of enumeration literals in an enumeration type
21673 definition
21674 @tab   65535
21675 @tab   No set limit
21676 @sp 1
21677
21678 @item  Maximum number of lines in a source file
21679 @tab   65534
21680 @tab   No set limit
21681 @sp 1
21682
21683 @item  Maximum number of bits in any object
21684 @tab   2**31-1
21685 @tab   2**31-1
21686 @sp 1
21687
21688 @item  Maximum size of the static portion of a stack frame (approximate)
21689 @tab   2**31-1
21690 @tab   2**31-1
21691 @end multitable
21692
21693 @node Tools and Utilities
21694 @section Tools and Utilities
21695
21696 @noindent
21697 The following table lists some of the OpenVMS development tools
21698 available for HP Ada, and the corresponding tools for
21699 use with @value{EDITION} on Alpha and I64 platforms.
21700 Aside from the debugger, all the OpenVMS tools identified are part
21701 of the DECset package.
21702
21703 @iftex
21704 @c Specify table in TeX since Texinfo does a poor job
21705 @tex
21706 \smallskip
21707 \smallskip
21708 \settabs\+Language-Sensitive Editor\quad
21709    &Product with HP Ada\quad
21710    &\cr
21711 \+\it Tool
21712    &\it Product with HP Ada
21713    & \it Product with @value{EDITION}\cr
21714 \smallskip
21715 \+Code Management System
21716    &HP CMS
21717    & HP CMS\cr
21718 \smallskip
21719 \+Language-Sensitive Editor
21720    &HP LSE
21721    & emacs or HP LSE (Alpha)\cr
21722 \+
21723    &
21724    & HP LSE (I64)\cr
21725 \smallskip
21726 \+Debugger
21727    &OpenVMS Debug
21728    & gdb (Alpha),\cr
21729 \+
21730    &
21731    & OpenVMS Debug (I64)\cr
21732 \smallskip
21733 \+Source Code Analyzer /
21734    &HP SCA
21735    & GNAT XREF\cr
21736 \+Cross Referencer
21737    &
21738    &\cr
21739 \smallskip
21740 \+Test Manager
21741    &HP Digital Test
21742    & HP DTM\cr
21743 \+
21744    &Manager (DTM)
21745    &\cr
21746 \smallskip
21747 \+Performance and
21748    & HP PCA
21749    & HP PCA\cr
21750 \+Coverage Analyzer
21751    &
21752    &\cr
21753 \smallskip
21754 \+Module Management
21755    & HP MMS
21756    & Not applicable\cr
21757 \+ System
21758    &
21759    &\cr
21760 \smallskip
21761 \smallskip
21762 @end tex
21763 @end iftex
21764
21765 @ifnottex
21766 @c This is the Texinfo version of the table.  It renders poorly in pdf, hence
21767 @c the TeX version above for the printed version
21768 @flushleft
21769 @c @multitable @columnfractions .3 .4 .4
21770 @multitable {Source Code Analyzer /}{Tool with HP Ada}{Tool with @value{EDITION}}
21771 @item @i{Tool}
21772 @tab @i{Tool with HP Ada}
21773 @tab @i{Tool with @value{EDITION}}
21774 @item Code Management@*System
21775 @tab HP CMS
21776 @tab HP CMS
21777 @item Language-Sensitive@*Editor
21778 @tab HP LSE
21779 @tab emacs or HP LSE (Alpha)
21780 @item
21781 @tab
21782 @tab HP LSE (I64)
21783 @item Debugger
21784 @tab OpenVMS Debug
21785 @tab gdb (Alpha),
21786 @item
21787 @tab
21788 @tab OpenVMS Debug (I64)
21789 @item Source Code Analyzer /@*Cross Referencer
21790 @tab HP SCA
21791 @tab GNAT XREF
21792 @item Test Manager
21793 @tab HP Digital Test@*Manager (DTM)
21794 @tab HP DTM
21795 @item Performance and@*Coverage Analyzer
21796 @tab HP PCA
21797 @tab HP PCA
21798 @item Module Management@*System
21799 @tab HP MMS
21800 @tab Not applicable
21801 @end multitable
21802 @end flushleft
21803 @end ifnottex
21804
21805 @end ifset
21806
21807 @c **************************************
21808 @node Platform-Specific Information for the Run-Time Libraries
21809 @appendix Platform-Specific Information for the Run-Time Libraries
21810 @cindex Tasking and threads libraries
21811 @cindex Threads libraries and tasking
21812 @cindex Run-time libraries (platform-specific information)
21813
21814 @noindent
21815 The GNAT run-time implementation may vary with respect to both the
21816 underlying threads library and the exception handling scheme.
21817 For threads support, one or more of the following are supplied:
21818 @itemize @bullet
21819 @item @b{native threads library}, a binding to the thread package from
21820 the underlying operating system
21821
21822 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
21823 POSIX thread package
21824 @end itemize
21825
21826 @noindent
21827 For exception handling, either or both of two models are supplied:
21828 @itemize @bullet
21829 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
21830 Most programs should experience a substantial speed improvement by
21831 being compiled with a ZCX run-time.
21832 This is especially true for
21833 tasking applications or applications with many exception handlers.}
21834 @cindex Zero-Cost Exceptions
21835 @cindex ZCX (Zero-Cost Exceptions)
21836 which uses binder-generated tables that
21837 are interrogated at run time to locate a handler
21838
21839 @item @b{setjmp / longjmp} (``SJLJ''),
21840 @cindex setjmp/longjmp Exception Model
21841 @cindex SJLJ (setjmp/longjmp Exception Model)
21842 which uses dynamically-set data to establish
21843 the set of handlers
21844 @end itemize
21845
21846 @noindent
21847 This appendix summarizes which combinations of threads and exception support
21848 are supplied on various GNAT platforms.
21849 It then shows how to select a particular library either
21850 permanently or temporarily,
21851 explains the properties of (and tradeoffs among) the various threads
21852 libraries, and provides some additional
21853 information about several specific platforms.
21854
21855 @menu
21856 * Summary of Run-Time Configurations::
21857 * Specifying a Run-Time Library::
21858 * Choosing the Scheduling Policy::
21859 * Solaris-Specific Considerations::
21860 * Linux-Specific Considerations::
21861 * AIX-Specific Considerations::
21862 * Irix-Specific Considerations::
21863 * RTX-Specific Considerations::
21864 * HP-UX-Specific Considerations::
21865 @end menu
21866
21867 @node Summary of Run-Time Configurations
21868 @section Summary of Run-Time Configurations
21869
21870 @multitable @columnfractions .30 .70
21871 @item @b{alpha-openvms}
21872 @item @code{@ @ }@i{rts-native (default)}
21873 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
21874 @item @code{@ @ @ @ }Exceptions @tab ZCX
21875 @*
21876 @item @b{alpha-tru64}
21877 @item @code{@ @ }@i{rts-native (default)}
21878 @item @code{@ @ @ @ }Tasking    @tab native TRU64 threads
21879 @item @code{@ @ @ @ }Exceptions @tab ZCX
21880 @*
21881 @item @code{@ @ }@i{rts-sjlj}
21882 @item @code{@ @ @ @ }Tasking    @tab native TRU64 threads
21883 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21884 @*
21885 @item @b{ia64-hp_linux}
21886 @item @code{@ @ }@i{rts-native (default)}
21887 @item @code{@ @ @ @ }Tasking    @tab pthread library
21888 @item @code{@ @ @ @ }Exceptions @tab ZCX
21889 @*
21890 @item @b{ia64-hpux}
21891 @item @code{@ @ }@i{rts-native (default)}
21892 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
21893 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21894 @*
21895 @item @b{ia64-openvms}
21896 @item @code{@ @ }@i{rts-native (default)}
21897 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
21898 @item @code{@ @ @ @ }Exceptions @tab ZCX
21899 @*
21900 @item @b{ia64-sgi_linux}
21901 @item @code{@ @ }@i{rts-native (default)}
21902 @item @code{@ @ @ @ }Tasking    @tab pthread library
21903 @item @code{@ @ @ @ }Exceptions @tab ZCX
21904 @*
21905 @item @b{mips-irix}
21906 @item @code{@ @ }@i{rts-native (default)}
21907 @item @code{@ @ @ @ }Tasking    @tab native IRIX threads
21908 @item @code{@ @ @ @ }Exceptions @tab ZCX
21909 @*
21910 @item @b{pa-hpux}
21911 @item @code{@ @ }@i{rts-native (default)}
21912 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
21913 @item @code{@ @ @ @ }Exceptions @tab ZCX
21914 @*
21915 @item @code{@ @ }@i{rts-sjlj}
21916 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
21917 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21918 @*
21919 @item @b{ppc-aix}
21920 @item @code{@ @ }@i{rts-native (default)}
21921 @item @code{@ @ @ @ }Tasking    @tab native AIX threads
21922 @item @code{@ @ @ @ }Exceptions @tab ZCX
21923 @*
21924 @item @code{@ @ }@i{rts-sjlj}
21925 @item @code{@ @ @ @ }Tasking    @tab native AIX threads
21926 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21927 @*
21928 @item @b{ppc-darwin}
21929 @item @code{@ @ }@i{rts-native (default)}
21930 @item @code{@ @ @ @ }Tasking    @tab native MacOS threads
21931 @item @code{@ @ @ @ }Exceptions @tab ZCX
21932 @*
21933 @item @b{sparc-solaris}  @tab
21934 @item @code{@ @ }@i{rts-native (default)}
21935 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
21936 @item @code{@ @ @ @ }Exceptions @tab ZCX
21937 @*
21938 @item @code{@ @ }@i{rts-pthread}
21939 @item @code{@ @ @ @ }Tasking    @tab pthread library
21940 @item @code{@ @ @ @ }Exceptions @tab ZCX
21941 @*
21942 @item @code{@ @ }@i{rts-sjlj}
21943 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
21944 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21945 @*
21946 @item @b{sparc64-solaris}  @tab
21947 @item @code{@ @ }@i{rts-native (default)}
21948 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
21949 @item @code{@ @ @ @ }Exceptions @tab ZCX
21950 @*
21951 @item @b{x86-linux}
21952 @item @code{@ @ }@i{rts-native (default)}
21953 @item @code{@ @ @ @ }Tasking    @tab pthread library
21954 @item @code{@ @ @ @ }Exceptions @tab ZCX
21955 @*
21956 @item @code{@ @ }@i{rts-sjlj}
21957 @item @code{@ @ @ @ }Tasking    @tab pthread library
21958 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21959 @*
21960 @item @b{x86-lynx}
21961 @item @code{@ @ }@i{rts-native (default)}
21962 @item @code{@ @ @ @ }Tasking    @tab native LynxOS threads
21963 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21964 @*
21965 @item @b{x86-solaris}
21966 @item @code{@ @ }@i{rts-native (default)}
21967 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads
21968 @item @code{@ @ @ @ }Exceptions @tab ZCX
21969 @*
21970 @item @code{@ @ }@i{rts-sjlj}
21971 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
21972 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21973 @*
21974 @item @b{x86-windows}
21975 @item @code{@ @ }@i{rts-native (default)}
21976 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
21977 @item @code{@ @ @ @ }Exceptions @tab ZCX
21978 @*
21979 @item @code{@ @ }@i{rts-sjlj}
21980 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
21981 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21982 @*
21983 @item @b{x86-windows-rtx}
21984 @item @code{@ @ }@i{rts-rtx-rtss (default)}
21985 @item @code{@ @ @ @ }Tasking    @tab RTX real-time subsystem RTSS threads (kernel mode)
21986 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21987 @*
21988 @item @code{@ @ }@i{rts-rtx-w32}
21989 @item @code{@ @ @ @ }Tasking    @tab RTX Win32 threads (user mode)
21990 @item @code{@ @ @ @ }Exceptions @tab ZCX
21991 @*
21992 @item @b{x86_64-linux}
21993 @item @code{@ @ }@i{rts-native (default)}
21994 @item @code{@ @ @ @ }Tasking    @tab pthread library
21995 @item @code{@ @ @ @ }Exceptions @tab ZCX
21996 @*
21997 @item @code{@ @ }@i{rts-sjlj}
21998 @item @code{@ @ @ @ }Tasking    @tab pthread library
21999 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22000 @*
22001 @end multitable
22002
22003 @node Specifying a Run-Time Library
22004 @section Specifying a Run-Time Library
22005
22006 @noindent
22007 The @file{adainclude} subdirectory containing the sources of the GNAT
22008 run-time library, and the @file{adalib} subdirectory containing the
22009 @file{ALI} files and the static and/or shared GNAT library, are located
22010 in the gcc target-dependent area:
22011
22012 @smallexample
22013 target=$prefix/lib/gcc/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
22014 @end smallexample
22015
22016 @noindent
22017 As indicated above, on some platforms several run-time libraries are supplied.
22018 These libraries are installed in the target dependent area and
22019 contain a complete source and binary subdirectory. The detailed description
22020 below explains the differences between the different libraries in terms of
22021 their thread support.
22022
22023 The default run-time library (when GNAT is installed) is @emph{rts-native}.
22024 This default run time is selected by the means of soft links.
22025 For example on x86-linux:
22026
22027 @smallexample
22028 @group
22029  $(target-dir)
22030      |
22031      +--- adainclude----------+
22032      |                        |
22033      +--- adalib-----------+  |
22034      |                     |  |
22035      +--- rts-native       |  |
22036      |    |                |  |
22037      |    +--- adainclude <---+
22038      |    |                |
22039      |    +--- adalib <----+
22040      |
22041      +--- rts-sjlj
22042           |
22043           +--- adainclude
22044           |
22045           +--- adalib
22046 @end group
22047 @end smallexample
22048
22049 @noindent
22050 If the @i{rts-sjlj} library is to be selected on a permanent basis,
22051 these soft links can be modified with the following commands:
22052
22053 @smallexample
22054 $ cd $target
22055 $ rm -f adainclude adalib
22056 $ ln -s rts-sjlj/adainclude adainclude
22057 $ ln -s rts-sjlj/adalib adalib
22058 @end smallexample
22059
22060 @noindent
22061 Alternatively, you can specify @file{rts-sjlj/adainclude} in the file
22062 @file{$target/ada_source_path} and @file{rts-sjlj/adalib} in
22063 @file{$target/ada_object_path}.
22064
22065 Selecting another run-time library temporarily can be
22066 achieved by using the @option{--RTS} switch, e.g., @option{--RTS=sjlj}
22067 @cindex @option{--RTS} option
22068
22069 @node Choosing the Scheduling Policy
22070 @section Choosing the Scheduling Policy
22071
22072 @noindent
22073 When using a POSIX threads implementation, you have a choice of several
22074 scheduling policies: @code{SCHED_FIFO},
22075 @cindex @code{SCHED_FIFO} scheduling policy
22076 @code{SCHED_RR}
22077 @cindex @code{SCHED_RR} scheduling policy
22078 and @code{SCHED_OTHER}.
22079 @cindex @code{SCHED_OTHER} scheduling policy
22080 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
22081 or @code{SCHED_RR} requires special (e.g., root) privileges.
22082
22083 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
22084 @code{SCHED_FIFO},
22085 @cindex @code{SCHED_FIFO} scheduling policy
22086 you can use one of the following:
22087
22088 @itemize @bullet
22089 @item
22090 @code{pragma Time_Slice (0.0)}
22091 @cindex pragma Time_Slice
22092 @item
22093 the corresponding binder option @option{-T0}
22094 @cindex @option{-T0} option
22095 @item
22096 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
22097 @cindex pragma Task_Dispatching_Policy
22098 @end itemize
22099
22100 @noindent
22101 To specify @code{SCHED_RR},
22102 @cindex @code{SCHED_RR} scheduling policy
22103 you should use @code{pragma Time_Slice} with a
22104 value greater than @code{0.0}, or else use the corresponding @option{-T}
22105 binder option.
22106
22107 @node Solaris-Specific Considerations
22108 @section Solaris-Specific Considerations
22109 @cindex Solaris Sparc threads libraries
22110
22111 @noindent
22112 This section addresses some topics related to the various threads libraries
22113 on Sparc Solaris.
22114
22115 @menu
22116 * Solaris Threads Issues::
22117 @end menu
22118
22119 @node Solaris Threads Issues
22120 @subsection Solaris Threads Issues
22121
22122 @noindent
22123 GNAT under Solaris/Sparc 32 bits comes with an alternate tasking run-time
22124 library based on POSIX threads --- @emph{rts-pthread}.
22125 @cindex rts-pthread threads library
22126 This run-time library has the advantage of being mostly shared across all
22127 POSIX-compliant thread implementations, and it also provides under
22128 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
22129 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
22130 and @code{PTHREAD_PRIO_PROTECT}
22131 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
22132 semantics that can be selected using the predefined pragma
22133 @code{Locking_Policy}
22134 @cindex pragma Locking_Policy (under rts-pthread)
22135 with respectively
22136 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
22137 @cindex @code{Inheritance_Locking} (under rts-pthread)
22138 @cindex @code{Ceiling_Locking} (under rts-pthread)
22139
22140 As explained above, the native run-time library is based on the Solaris thread
22141 library (@code{libthread}) and is the default library.
22142
22143 When the Solaris threads library is used (this is the default), programs
22144 compiled with GNAT can automatically take advantage of
22145 and can thus execute on multiple processors.
22146 The user can alternatively specify a processor on which the program should run
22147 to emulate a single-processor system. The multiprocessor / uniprocessor choice
22148 is made by
22149 setting the environment variable @env{GNAT_PROCESSOR}
22150 @cindex @env{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
22151 to one of the following:
22152
22153 @table @code
22154 @item -2
22155 Use the default configuration (run the program on all
22156 available processors) - this is the same as having @code{GNAT_PROCESSOR}
22157 unset
22158
22159 @item -1
22160 Let the run-time implementation choose one processor and run the program on
22161 that processor
22162
22163 @item 0 .. Last_Proc
22164 Run the program on the specified processor.
22165 @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
22166 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
22167 @end table
22168
22169 @node Linux-Specific Considerations
22170 @section Linux-Specific Considerations
22171 @cindex Linux threads libraries
22172
22173 @noindent
22174 On GNU/Linux without NPTL support (usually system with GNU C Library
22175 older than 2.3), the signal model is not POSIX compliant, which means
22176 that to send a signal to the process, you need to send the signal to all
22177 threads, e.g.@: by using @code{killpg()}.
22178
22179 @node AIX-Specific Considerations
22180 @section AIX-Specific Considerations
22181 @cindex AIX resolver library
22182
22183 @noindent
22184 On AIX, the resolver library initializes some internal structure on
22185 the first call to @code{get*by*} functions, which are used to implement
22186 @code{GNAT.Sockets.Get_Host_By_Name} and
22187 @code{GNAT.Sockets.Get_Host_By_Address}.
22188 If such initialization occurs within an Ada task, and the stack size for
22189 the task is the default size, a stack overflow may occur.
22190
22191 To avoid this overflow, the user should either ensure that the first call
22192 to @code{GNAT.Sockets.Get_Host_By_Name} or
22193 @code{GNAT.Sockets.Get_Host_By_Addrss}
22194 occurs in the environment task, or use @code{pragma Storage_Size} to
22195 specify a sufficiently large size for the stack of the task that contains
22196 this call.
22197
22198 @node Irix-Specific Considerations
22199 @section Irix-Specific Considerations
22200 @cindex Irix libraries
22201
22202 @noindent
22203 The GCC support libraries coming with the Irix compiler have moved to
22204 their canonical place with respect to the general Irix ABI related
22205 conventions. Running applications built with the default shared GNAT
22206 run-time now requires the LD_LIBRARY_PATH environment variable to
22207 include this location. A possible way to achieve this is to issue the
22208 following command line on a bash prompt:
22209
22210 @smallexample
22211 @group
22212 $  LD_LIBRARY_PATH=$LD_LIBRARY_PATH:`dirname \`gcc --print-file-name=libgcc_s.so\``
22213 @end group
22214 @end smallexample
22215
22216 @node RTX-Specific Considerations
22217 @section RTX-Specific Considerations
22218 @cindex RTX libraries
22219
22220 @noindent
22221 The Real-time Extension (RTX) to Windows is based on the Windows Win32
22222 API. Applications can be built to work in two different modes:
22223
22224 @itemize @bullet
22225 @item
22226 Windows executables that run in Ring 3 to utilize memory protection
22227 (@emph{rts-rtx-w32}).
22228
22229 @item
22230 Real-time subsystem (RTSS) executables that run in Ring 0, where
22231 performance can be optimized with RTSS applications taking precedent
22232 over all Windows applications (@emph{rts-rtx-rtss}). This mode requires
22233 the Microsoft linker to handle RTSS libraries.
22234
22235 @end itemize
22236
22237 @node HP-UX-Specific Considerations
22238 @section HP-UX-Specific Considerations
22239 @cindex HP-UX Scheduling
22240
22241 @noindent
22242 On HP-UX, appropriate privileges are required to change the scheduling
22243 parameters of a task. The calling process must have appropriate
22244 privileges or be a member of a group having @code{PRIV_RTSCHED} access to
22245 successfully change the scheduling parameters.
22246
22247 By default, GNAT uses the @code{SCHED_HPUX} policy. To have access to the
22248 priority range 0-31 either the @code{FIFO_Within_Priorities} or the
22249 @code{Round_Robin_Within_Priorities} scheduling policies need to be set.
22250
22251 To specify the @code{FIFO_Within_Priorities} scheduling policy you can use
22252 one of the following:
22253
22254 @itemize @bullet
22255 @item
22256 @code{pragma Time_Slice (0.0)}
22257 @cindex pragma Time_Slice
22258 @item
22259 the corresponding binder option @option{-T0}
22260 @cindex @option{-T0} option
22261 @item
22262 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
22263 @cindex pragma Task_Dispatching_Policy
22264 @end itemize
22265
22266 @noindent
22267 To specify the @code{Round_Robin_Within_Priorities}, scheduling policy
22268 you should use @code{pragma Time_Slice} with a
22269 value greater than @code{0.0}, or use the corresponding @option{-T}
22270 binder option, or set the @code{pragma Task_Dispatching_Policy
22271 (Round_Robin_Within_Priorities)}.
22272
22273 @c *******************************
22274 @node Example of Binder Output File
22275 @appendix Example of Binder Output File
22276
22277 @noindent
22278 This Appendix displays the source code for @command{gnatbind}'s output
22279 file generated for a simple ``Hello World'' program.
22280 Comments have been added for clarification purposes.
22281
22282 @smallexample @c adanocomment
22283 @iftex
22284 @leftskip=0cm
22285 @end iftex
22286 --  The package is called Ada_Main unless this name is actually used
22287 --  as a unit name in the partition, in which case some other unique
22288 --  name is used.
22289
22290 with System;
22291 package ada_main is
22292
22293    Elab_Final_Code : Integer;
22294    pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
22295
22296    --  The main program saves the parameters (argument count,
22297    --  argument values, environment pointer) in global variables
22298    --  for later access by other units including
22299    --  Ada.Command_Line.
22300
22301    gnat_argc : Integer;
22302    gnat_argv : System.Address;
22303    gnat_envp : System.Address;
22304
22305    --  The actual variables are stored in a library routine. This
22306    --  is useful for some shared library situations, where there
22307    --  are problems if variables are not in the library.
22308
22309    pragma Import (C, gnat_argc);
22310    pragma Import (C, gnat_argv);
22311    pragma Import (C, gnat_envp);
22312
22313    --  The exit status is similarly an external location
22314
22315    gnat_exit_status : Integer;
22316    pragma Import (C, gnat_exit_status);
22317
22318    GNAT_Version : constant String :=
22319                     "GNAT Version: 6.0.0w (20061115)";
22320    pragma Export (C, GNAT_Version, "__gnat_version");
22321
22322    --  This is the generated adafinal routine that performs
22323    --  finalization at the end of execution. In the case where
22324    --  Ada is the main program, this main program makes a call
22325    --  to adafinal at program termination.
22326
22327    procedure adafinal;
22328    pragma Export (C, adafinal, "adafinal");
22329
22330    --  This is the generated adainit routine that performs
22331    --  initialization at the start of execution. In the case
22332    --  where Ada is the main program, this main program makes
22333    --  a call to adainit at program startup.
22334
22335    procedure adainit;
22336    pragma Export (C, adainit, "adainit");
22337
22338    --  This routine is called at the start of execution. It is
22339    --  a dummy routine that is used by the debugger to breakpoint
22340    --  at the start of execution.
22341
22342    procedure Break_Start;
22343    pragma Import (C, Break_Start, "__gnat_break_start");
22344
22345    --  This is the actual generated main program (it would be
22346    --  suppressed if the no main program switch were used). As
22347    --  required by standard system conventions, this program has
22348    --  the external name main.
22349
22350    function main
22351      (argc : Integer;
22352       argv : System.Address;
22353       envp : System.Address)
22354       return Integer;
22355    pragma Export (C, main, "main");
22356
22357    --  The following set of constants give the version
22358    --  identification values for every unit in the bound
22359    --  partition. This identification is computed from all
22360    --  dependent semantic units, and corresponds to the
22361    --  string that would be returned by use of the
22362    --  Body_Version or Version attributes.
22363
22364    type Version_32 is mod 2 ** 32;
22365    u00001 : constant Version_32 := 16#7880BEB3#;
22366    u00002 : constant Version_32 := 16#0D24CBD0#;
22367    u00003 : constant Version_32 := 16#3283DBEB#;
22368    u00004 : constant Version_32 := 16#2359F9ED#;
22369    u00005 : constant Version_32 := 16#664FB847#;
22370    u00006 : constant Version_32 := 16#68E803DF#;
22371    u00007 : constant Version_32 := 16#5572E604#;
22372    u00008 : constant Version_32 := 16#46B173D8#;
22373    u00009 : constant Version_32 := 16#156A40CF#;
22374    u00010 : constant Version_32 := 16#033DABE0#;
22375    u00011 : constant Version_32 := 16#6AB38FEA#;
22376    u00012 : constant Version_32 := 16#22B6217D#;
22377    u00013 : constant Version_32 := 16#68A22947#;
22378    u00014 : constant Version_32 := 16#18CC4A56#;
22379    u00015 : constant Version_32 := 16#08258E1B#;
22380    u00016 : constant Version_32 := 16#367D5222#;
22381    u00017 : constant Version_32 := 16#20C9ECA4#;
22382    u00018 : constant Version_32 := 16#50D32CB6#;
22383    u00019 : constant Version_32 := 16#39A8BB77#;
22384    u00020 : constant Version_32 := 16#5CF8FA2B#;
22385    u00021 : constant Version_32 := 16#2F1EB794#;
22386    u00022 : constant Version_32 := 16#31AB6444#;
22387    u00023 : constant Version_32 := 16#1574B6E9#;
22388    u00024 : constant Version_32 := 16#5109C189#;
22389    u00025 : constant Version_32 := 16#56D770CD#;
22390    u00026 : constant Version_32 := 16#02F9DE3D#;
22391    u00027 : constant Version_32 := 16#08AB6B2C#;
22392    u00028 : constant Version_32 := 16#3FA37670#;
22393    u00029 : constant Version_32 := 16#476457A0#;
22394    u00030 : constant Version_32 := 16#731E1B6E#;
22395    u00031 : constant Version_32 := 16#23C2E789#;
22396    u00032 : constant Version_32 := 16#0F1BD6A1#;
22397    u00033 : constant Version_32 := 16#7C25DE96#;
22398    u00034 : constant Version_32 := 16#39ADFFA2#;
22399    u00035 : constant Version_32 := 16#571DE3E7#;
22400    u00036 : constant Version_32 := 16#5EB646AB#;
22401    u00037 : constant Version_32 := 16#4249379B#;
22402    u00038 : constant Version_32 := 16#0357E00A#;
22403    u00039 : constant Version_32 := 16#3784FB72#;
22404    u00040 : constant Version_32 := 16#2E723019#;
22405    u00041 : constant Version_32 := 16#623358EA#;
22406    u00042 : constant Version_32 := 16#107F9465#;
22407    u00043 : constant Version_32 := 16#6843F68A#;
22408    u00044 : constant Version_32 := 16#63305874#;
22409    u00045 : constant Version_32 := 16#31E56CE1#;
22410    u00046 : constant Version_32 := 16#02917970#;
22411    u00047 : constant Version_32 := 16#6CCBA70E#;
22412    u00048 : constant Version_32 := 16#41CD4204#;
22413    u00049 : constant Version_32 := 16#572E3F58#;
22414    u00050 : constant Version_32 := 16#20729FF5#;
22415    u00051 : constant Version_32 := 16#1D4F93E8#;
22416    u00052 : constant Version_32 := 16#30B2EC3D#;
22417    u00053 : constant Version_32 := 16#34054F96#;
22418    u00054 : constant Version_32 := 16#5A199860#;
22419    u00055 : constant Version_32 := 16#0E7F912B#;
22420    u00056 : constant Version_32 := 16#5760634A#;
22421    u00057 : constant Version_32 := 16#5D851835#;
22422
22423    --  The following Export pragmas export the version numbers
22424    --  with symbolic names ending in B (for body) or S
22425    --  (for spec) so that they can be located in a link. The
22426    --  information provided here is sufficient to track down
22427    --  the exact versions of units used in a given build.
22428
22429    pragma Export (C, u00001, "helloB");
22430    pragma Export (C, u00002, "system__standard_libraryB");
22431    pragma Export (C, u00003, "system__standard_libraryS");
22432    pragma Export (C, u00004, "adaS");
22433    pragma Export (C, u00005, "ada__text_ioB");
22434    pragma Export (C, u00006, "ada__text_ioS");
22435    pragma Export (C, u00007, "ada__exceptionsB");
22436    pragma Export (C, u00008, "ada__exceptionsS");
22437    pragma Export (C, u00009, "gnatS");
22438    pragma Export (C, u00010, "gnat__heap_sort_aB");
22439    pragma Export (C, u00011, "gnat__heap_sort_aS");
22440    pragma Export (C, u00012, "systemS");
22441    pragma Export (C, u00013, "system__exception_tableB");
22442    pragma Export (C, u00014, "system__exception_tableS");
22443    pragma Export (C, u00015, "gnat__htableB");
22444    pragma Export (C, u00016, "gnat__htableS");
22445    pragma Export (C, u00017, "system__exceptionsS");
22446    pragma Export (C, u00018, "system__machine_state_operationsB");
22447    pragma Export (C, u00019, "system__machine_state_operationsS");
22448    pragma Export (C, u00020, "system__machine_codeS");
22449    pragma Export (C, u00021, "system__storage_elementsB");
22450    pragma Export (C, u00022, "system__storage_elementsS");
22451    pragma Export (C, u00023, "system__secondary_stackB");
22452    pragma Export (C, u00024, "system__secondary_stackS");
22453    pragma Export (C, u00025, "system__parametersB");
22454    pragma Export (C, u00026, "system__parametersS");
22455    pragma Export (C, u00027, "system__soft_linksB");
22456    pragma Export (C, u00028, "system__soft_linksS");
22457    pragma Export (C, u00029, "system__stack_checkingB");
22458    pragma Export (C, u00030, "system__stack_checkingS");
22459    pragma Export (C, u00031, "system__tracebackB");
22460    pragma Export (C, u00032, "system__tracebackS");
22461    pragma Export (C, u00033, "ada__streamsS");
22462    pragma Export (C, u00034, "ada__tagsB");
22463    pragma Export (C, u00035, "ada__tagsS");
22464    pragma Export (C, u00036, "system__string_opsB");
22465    pragma Export (C, u00037, "system__string_opsS");
22466    pragma Export (C, u00038, "interfacesS");
22467    pragma Export (C, u00039, "interfaces__c_streamsB");
22468    pragma Export (C, u00040, "interfaces__c_streamsS");
22469    pragma Export (C, u00041, "system__file_ioB");
22470    pragma Export (C, u00042, "system__file_ioS");
22471    pragma Export (C, u00043, "ada__finalizationB");
22472    pragma Export (C, u00044, "ada__finalizationS");
22473    pragma Export (C, u00045, "system__finalization_rootB");
22474    pragma Export (C, u00046, "system__finalization_rootS");
22475    pragma Export (C, u00047, "system__finalization_implementationB");
22476    pragma Export (C, u00048, "system__finalization_implementationS");
22477    pragma Export (C, u00049, "system__string_ops_concat_3B");
22478    pragma Export (C, u00050, "system__string_ops_concat_3S");
22479    pragma Export (C, u00051, "system__stream_attributesB");
22480    pragma Export (C, u00052, "system__stream_attributesS");
22481    pragma Export (C, u00053, "ada__io_exceptionsS");
22482    pragma Export (C, u00054, "system__unsigned_typesS");
22483    pragma Export (C, u00055, "system__file_control_blockS");
22484    pragma Export (C, u00056, "ada__finalization__list_controllerB");
22485    pragma Export (C, u00057, "ada__finalization__list_controllerS");
22486
22487    -- BEGIN ELABORATION ORDER
22488    -- ada (spec)
22489    -- gnat (spec)
22490    -- gnat.heap_sort_a (spec)
22491    -- gnat.heap_sort_a (body)
22492    -- gnat.htable (spec)
22493    -- gnat.htable (body)
22494    -- interfaces (spec)
22495    -- system (spec)
22496    -- system.machine_code (spec)
22497    -- system.parameters (spec)
22498    -- system.parameters (body)
22499    -- interfaces.c_streams (spec)
22500    -- interfaces.c_streams (body)
22501    -- system.standard_library (spec)
22502    -- ada.exceptions (spec)
22503    -- system.exception_table (spec)
22504    -- system.exception_table (body)
22505    -- ada.io_exceptions (spec)
22506    -- system.exceptions (spec)
22507    -- system.storage_elements (spec)
22508    -- system.storage_elements (body)
22509    -- system.machine_state_operations (spec)
22510    -- system.machine_state_operations (body)
22511    -- system.secondary_stack (spec)
22512    -- system.stack_checking (spec)
22513    -- system.soft_links (spec)
22514    -- system.soft_links (body)
22515    -- system.stack_checking (body)
22516    -- system.secondary_stack (body)
22517    -- system.standard_library (body)
22518    -- system.string_ops (spec)
22519    -- system.string_ops (body)
22520    -- ada.tags (spec)
22521    -- ada.tags (body)
22522    -- ada.streams (spec)
22523    -- system.finalization_root (spec)
22524    -- system.finalization_root (body)
22525    -- system.string_ops_concat_3 (spec)
22526    -- system.string_ops_concat_3 (body)
22527    -- system.traceback (spec)
22528    -- system.traceback (body)
22529    -- ada.exceptions (body)
22530    -- system.unsigned_types (spec)
22531    -- system.stream_attributes (spec)
22532    -- system.stream_attributes (body)
22533    -- system.finalization_implementation (spec)
22534    -- system.finalization_implementation (body)
22535    -- ada.finalization (spec)
22536    -- ada.finalization (body)
22537    -- ada.finalization.list_controller (spec)
22538    -- ada.finalization.list_controller (body)
22539    -- system.file_control_block (spec)
22540    -- system.file_io (spec)
22541    -- system.file_io (body)
22542    -- ada.text_io (spec)
22543    -- ada.text_io (body)
22544    -- hello (body)
22545    -- END ELABORATION ORDER
22546
22547 end ada_main;
22548
22549 --  The following source file name pragmas allow the generated file
22550 --  names to be unique for different main programs. They are needed
22551 --  since the package name will always be Ada_Main.
22552
22553 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
22554 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
22555
22556 --  Generated package body for Ada_Main starts here
22557
22558 package body ada_main is
22559
22560    --  The actual finalization is performed by calling the
22561    --  library routine in System.Standard_Library.Adafinal
22562
22563    procedure Do_Finalize;
22564    pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
22565
22566    -------------
22567    -- adainit --
22568    -------------
22569
22570 @findex adainit
22571    procedure adainit is
22572
22573       --  These booleans are set to True once the associated unit has
22574       --  been elaborated. It is also used to avoid elaborating the
22575       --  same unit twice.
22576
22577       E040 : Boolean;
22578       pragma Import (Ada, E040, "interfaces__c_streams_E");
22579
22580       E008 : Boolean;
22581       pragma Import (Ada, E008, "ada__exceptions_E");
22582
22583       E014 : Boolean;
22584       pragma Import (Ada, E014, "system__exception_table_E");
22585
22586       E053 : Boolean;
22587       pragma Import (Ada, E053, "ada__io_exceptions_E");
22588
22589       E017 : Boolean;
22590       pragma Import (Ada, E017, "system__exceptions_E");
22591
22592       E024 : Boolean;
22593       pragma Import (Ada, E024, "system__secondary_stack_E");
22594
22595       E030 : Boolean;
22596       pragma Import (Ada, E030, "system__stack_checking_E");
22597
22598       E028 : Boolean;
22599       pragma Import (Ada, E028, "system__soft_links_E");
22600
22601       E035 : Boolean;
22602       pragma Import (Ada, E035, "ada__tags_E");
22603
22604       E033 : Boolean;
22605       pragma Import (Ada, E033, "ada__streams_E");
22606
22607       E046 : Boolean;
22608       pragma Import (Ada, E046, "system__finalization_root_E");
22609
22610       E048 : Boolean;
22611       pragma Import (Ada, E048, "system__finalization_implementation_E");
22612
22613       E044 : Boolean;
22614       pragma Import (Ada, E044, "ada__finalization_E");
22615
22616       E057 : Boolean;
22617       pragma Import (Ada, E057, "ada__finalization__list_controller_E");
22618
22619       E055 : Boolean;
22620       pragma Import (Ada, E055, "system__file_control_block_E");
22621
22622       E042 : Boolean;
22623       pragma Import (Ada, E042, "system__file_io_E");
22624
22625       E006 : Boolean;
22626       pragma Import (Ada, E006, "ada__text_io_E");
22627
22628       --  Set_Globals is a library routine that stores away the
22629       --  value of the indicated set of global values in global
22630       --  variables within the library.
22631
22632       procedure Set_Globals
22633         (Main_Priority            : Integer;
22634          Time_Slice_Value         : Integer;
22635          WC_Encoding              : Character;
22636          Locking_Policy           : Character;
22637          Queuing_Policy           : Character;
22638          Task_Dispatching_Policy  : Character;
22639          Adafinal                 : System.Address;
22640          Unreserve_All_Interrupts : Integer;
22641          Exception_Tracebacks     : Integer);
22642 @findex __gnat_set_globals
22643       pragma Import (C, Set_Globals, "__gnat_set_globals");
22644
22645       --  SDP_Table_Build is a library routine used to build the
22646       --  exception tables. See unit Ada.Exceptions in files
22647       --  a-except.ads/adb for full details of how zero cost
22648       --  exception handling works. This procedure, the call to
22649       --  it, and the two following tables are all omitted if the
22650       --  build is in longjmp/setjmp exception mode.
22651
22652 @findex SDP_Table_Build
22653 @findex Zero Cost Exceptions
22654       procedure SDP_Table_Build
22655         (SDP_Addresses   : System.Address;
22656          SDP_Count       : Natural;
22657          Elab_Addresses  : System.Address;
22658          Elab_Addr_Count : Natural);
22659       pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
22660
22661       --  Table of Unit_Exception_Table addresses. Used for zero
22662       --  cost exception handling to build the top level table.
22663
22664       ST : aliased constant array (1 .. 23) of System.Address := (
22665         Hello'UET_Address,
22666         Ada.Text_Io'UET_Address,
22667         Ada.Exceptions'UET_Address,
22668         Gnat.Heap_Sort_A'UET_Address,
22669         System.Exception_Table'UET_Address,
22670         System.Machine_State_Operations'UET_Address,
22671         System.Secondary_Stack'UET_Address,
22672         System.Parameters'UET_Address,
22673         System.Soft_Links'UET_Address,
22674         System.Stack_Checking'UET_Address,
22675         System.Traceback'UET_Address,
22676         Ada.Streams'UET_Address,
22677         Ada.Tags'UET_Address,
22678         System.String_Ops'UET_Address,
22679         Interfaces.C_Streams'UET_Address,
22680         System.File_Io'UET_Address,
22681         Ada.Finalization'UET_Address,
22682         System.Finalization_Root'UET_Address,
22683         System.Finalization_Implementation'UET_Address,
22684         System.String_Ops_Concat_3'UET_Address,
22685         System.Stream_Attributes'UET_Address,
22686         System.File_Control_Block'UET_Address,
22687         Ada.Finalization.List_Controller'UET_Address);
22688
22689       --  Table of addresses of elaboration routines. Used for
22690       --  zero cost exception handling to make sure these
22691       --  addresses are included in the top level procedure
22692       --  address table.
22693
22694       EA : aliased constant array (1 .. 23) of System.Address := (
22695         adainit'Code_Address,
22696         Do_Finalize'Code_Address,
22697         Ada.Exceptions'Elab_Spec'Address,
22698         System.Exceptions'Elab_Spec'Address,
22699         Interfaces.C_Streams'Elab_Spec'Address,
22700         System.Exception_Table'Elab_Body'Address,
22701         Ada.Io_Exceptions'Elab_Spec'Address,
22702         System.Stack_Checking'Elab_Spec'Address,
22703         System.Soft_Links'Elab_Body'Address,
22704         System.Secondary_Stack'Elab_Body'Address,
22705         Ada.Tags'Elab_Spec'Address,
22706         Ada.Tags'Elab_Body'Address,
22707         Ada.Streams'Elab_Spec'Address,
22708         System.Finalization_Root'Elab_Spec'Address,
22709         Ada.Exceptions'Elab_Body'Address,
22710         System.Finalization_Implementation'Elab_Spec'Address,
22711         System.Finalization_Implementation'Elab_Body'Address,
22712         Ada.Finalization'Elab_Spec'Address,
22713         Ada.Finalization.List_Controller'Elab_Spec'Address,
22714         System.File_Control_Block'Elab_Spec'Address,
22715         System.File_Io'Elab_Body'Address,
22716         Ada.Text_Io'Elab_Spec'Address,
22717         Ada.Text_Io'Elab_Body'Address);
22718
22719    --  Start of processing for adainit
22720
22721    begin
22722
22723       --  Call SDP_Table_Build to build the top level procedure
22724       --  table for zero cost exception handling (omitted in
22725       --  longjmp/setjmp mode).
22726
22727       SDP_Table_Build (ST'Address, 23, EA'Address, 23);
22728
22729       --  Call Set_Globals to record various information for
22730       --  this partition.  The values are derived by the binder
22731       --  from information stored in the ali files by the compiler.
22732
22733 @findex __gnat_set_globals
22734       Set_Globals
22735         (Main_Priority            => -1,
22736          --  Priority of main program, -1 if no pragma Priority used
22737
22738          Time_Slice_Value         => -1,
22739          --  Time slice from Time_Slice pragma, -1 if none used
22740
22741          WC_Encoding              => 'b',
22742          --  Wide_Character encoding used, default is brackets
22743
22744          Locking_Policy           => ' ',
22745          --  Locking_Policy used, default of space means not
22746          --  specified, otherwise it is the first character of
22747          --  the policy name.
22748
22749          Queuing_Policy           => ' ',
22750          --  Queuing_Policy used, default of space means not
22751          --  specified, otherwise it is the first character of
22752          --  the policy name.
22753
22754          Task_Dispatching_Policy  => ' ',
22755          --  Task_Dispatching_Policy used, default of space means
22756          --  not specified, otherwise first character of the
22757          --  policy name.
22758
22759          Adafinal                 => System.Null_Address,
22760          --  Address of Adafinal routine, not used anymore
22761
22762          Unreserve_All_Interrupts => 0,
22763          --  Set true if pragma Unreserve_All_Interrupts was used
22764
22765          Exception_Tracebacks     => 0);
22766          --  Indicates if exception tracebacks are enabled
22767
22768       Elab_Final_Code := 1;
22769
22770       --  Now we have the elaboration calls for all units in the partition.
22771       --  The Elab_Spec and Elab_Body attributes generate references to the
22772       --  implicit elaboration procedures generated by the compiler for
22773       --  each unit that requires elaboration.
22774
22775       if not E040 then
22776          Interfaces.C_Streams'Elab_Spec;
22777       end if;
22778       E040 := True;
22779       if not E008 then
22780          Ada.Exceptions'Elab_Spec;
22781       end if;
22782       if not E014 then
22783          System.Exception_Table'Elab_Body;
22784          E014 := True;
22785       end if;
22786       if not E053 then
22787          Ada.Io_Exceptions'Elab_Spec;
22788          E053 := True;
22789       end if;
22790       if not E017 then
22791          System.Exceptions'Elab_Spec;
22792          E017 := True;
22793       end if;
22794       if not E030 then
22795          System.Stack_Checking'Elab_Spec;
22796       end if;
22797       if not E028 then
22798          System.Soft_Links'Elab_Body;
22799          E028 := True;
22800       end if;
22801       E030 := True;
22802       if not E024 then
22803          System.Secondary_Stack'Elab_Body;
22804          E024 := True;
22805       end if;
22806       if not E035 then
22807          Ada.Tags'Elab_Spec;
22808       end if;
22809       if not E035 then
22810          Ada.Tags'Elab_Body;
22811          E035 := True;
22812       end if;
22813       if not E033 then
22814          Ada.Streams'Elab_Spec;
22815          E033 := True;
22816       end if;
22817       if not E046 then
22818          System.Finalization_Root'Elab_Spec;
22819       end if;
22820       E046 := True;
22821       if not E008 then
22822          Ada.Exceptions'Elab_Body;
22823          E008 := True;
22824       end if;
22825       if not E048 then
22826          System.Finalization_Implementation'Elab_Spec;
22827       end if;
22828       if not E048 then
22829          System.Finalization_Implementation'Elab_Body;
22830          E048 := True;
22831       end if;
22832       if not E044 then
22833          Ada.Finalization'Elab_Spec;
22834       end if;
22835       E044 := True;
22836       if not E057 then
22837          Ada.Finalization.List_Controller'Elab_Spec;
22838       end if;
22839       E057 := True;
22840       if not E055 then
22841          System.File_Control_Block'Elab_Spec;
22842          E055 := True;
22843       end if;
22844       if not E042 then
22845          System.File_Io'Elab_Body;
22846          E042 := True;
22847       end if;
22848       if not E006 then
22849          Ada.Text_Io'Elab_Spec;
22850       end if;
22851       if not E006 then
22852          Ada.Text_Io'Elab_Body;
22853          E006 := True;
22854       end if;
22855
22856       Elab_Final_Code := 0;
22857    end adainit;
22858
22859    --------------
22860    -- adafinal --
22861    --------------
22862
22863 @findex adafinal
22864    procedure adafinal is
22865    begin
22866       Do_Finalize;
22867    end adafinal;
22868
22869    ----------
22870    -- main --
22871    ----------
22872
22873    --  main is actually a function, as in the ANSI C standard,
22874    --  defined to return the exit status. The three parameters
22875    --  are the argument count, argument values and environment
22876    --  pointer.
22877
22878 @findex Main Program
22879    function main
22880      (argc : Integer;
22881       argv : System.Address;
22882       envp : System.Address)
22883       return Integer
22884    is
22885       --  The initialize routine performs low level system
22886       --  initialization using a standard library routine which
22887       --  sets up signal handling and performs any other
22888       --  required setup. The routine can be found in file
22889       --  a-init.c.
22890
22891 @findex __gnat_initialize
22892       procedure initialize;
22893       pragma Import (C, initialize, "__gnat_initialize");
22894
22895       --  The finalize routine performs low level system
22896       --  finalization using a standard library routine. The
22897       --  routine is found in file a-final.c and in the standard
22898       --  distribution is a dummy routine that does nothing, so
22899       --  really this is a hook for special user finalization.
22900
22901 @findex __gnat_finalize
22902       procedure finalize;
22903       pragma Import (C, finalize, "__gnat_finalize");
22904
22905       --  We get to the main program of the partition by using
22906       --  pragma Import because if we try to with the unit and
22907       --  call it Ada style, then not only do we waste time
22908       --  recompiling it, but also, we don't really know the right
22909       --  switches (e.g.@: identifier character set) to be used
22910       --  to compile it.
22911
22912       procedure Ada_Main_Program;
22913       pragma Import (Ada, Ada_Main_Program, "_ada_hello");
22914
22915    --  Start of processing for main
22916
22917    begin
22918       --  Save global variables
22919
22920       gnat_argc := argc;
22921       gnat_argv := argv;
22922       gnat_envp := envp;
22923
22924       --  Call low level system initialization
22925
22926       Initialize;
22927
22928       --  Call our generated Ada initialization routine
22929
22930       adainit;
22931
22932       --  This is the point at which we want the debugger to get
22933       --  control
22934
22935       Break_Start;
22936
22937       --  Now we call the main program of the partition
22938
22939       Ada_Main_Program;
22940
22941       --  Perform Ada finalization
22942
22943       adafinal;
22944
22945       --  Perform low level system finalization
22946
22947       Finalize;
22948
22949       --  Return the proper exit status
22950       return (gnat_exit_status);
22951    end;
22952
22953 --  This section is entirely comments, so it has no effect on the
22954 --  compilation of the Ada_Main package. It provides the list of
22955 --  object files and linker options, as well as some standard
22956 --  libraries needed for the link. The gnatlink utility parses
22957 --  this b~hello.adb file to read these comment lines to generate
22958 --  the appropriate command line arguments for the call to the
22959 --  system linker. The BEGIN/END lines are used for sentinels for
22960 --  this parsing operation.
22961
22962 --  The exact file names will of course depend on the environment,
22963 --  host/target and location of files on the host system.
22964
22965 @findex Object file list
22966 -- BEGIN Object file/option list
22967    --   ./hello.o
22968    --   -L./
22969    --   -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
22970    --   /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
22971 -- END Object file/option list
22972
22973 end ada_main;
22974 @end smallexample
22975
22976 @noindent
22977 The Ada code in the above example is exactly what is generated by the
22978 binder. We have added comments to more clearly indicate the function
22979 of each part of the generated @code{Ada_Main} package.
22980
22981 The code is standard Ada in all respects, and can be processed by any
22982 tools that handle Ada. In particular, it is possible to use the debugger
22983 in Ada mode to debug the generated @code{Ada_Main} package. For example,
22984 suppose that for reasons that you do not understand, your program is crashing
22985 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
22986 you can place a breakpoint on the call:
22987
22988 @smallexample @c ada
22989 Ada.Text_Io'Elab_Body;
22990 @end smallexample
22991
22992 @noindent
22993 and trace the elaboration routine for this package to find out where
22994 the problem might be (more usually of course you would be debugging
22995 elaboration code in your own application).
22996
22997 @node Elaboration Order Handling in GNAT
22998 @appendix Elaboration Order Handling in GNAT
22999 @cindex Order of elaboration
23000 @cindex Elaboration control
23001
23002 @menu
23003 * Elaboration Code::
23004 * Checking the Elaboration Order::
23005 * Controlling the Elaboration Order::
23006 * Controlling Elaboration in GNAT - Internal Calls::
23007 * Controlling Elaboration in GNAT - External Calls::
23008 * Default Behavior in GNAT - Ensuring Safety::
23009 * Treatment of Pragma Elaborate::
23010 * Elaboration Issues for Library Tasks::
23011 * Mixing Elaboration Models::
23012 * What to Do If the Default Elaboration Behavior Fails::
23013 * Elaboration for Access-to-Subprogram Values::
23014 * Summary of Procedures for Elaboration Control::
23015 * Other Elaboration Order Considerations::
23016 @end menu
23017
23018 @noindent
23019 This chapter describes the handling of elaboration code in Ada and
23020 in GNAT, and discusses how the order of elaboration of program units can
23021 be controlled in GNAT, either automatically or with explicit programming
23022 features.
23023
23024 @node Elaboration Code
23025 @section Elaboration Code
23026
23027 @noindent
23028 Ada provides rather general mechanisms for executing code at elaboration
23029 time, that is to say before the main program starts executing. Such code arises
23030 in three contexts:
23031
23032 @table @asis
23033 @item Initializers for variables.
23034 Variables declared at the library level, in package specs or bodies, can
23035 require initialization that is performed at elaboration time, as in:
23036 @smallexample @c ada
23037 @cartouche
23038 Sqrt_Half : Float := Sqrt (0.5);
23039 @end cartouche
23040 @end smallexample
23041
23042 @item Package initialization code
23043 Code in a @code{BEGIN-END} section at the outer level of a package body is
23044 executed as part of the package body elaboration code.
23045
23046 @item Library level task allocators
23047 Tasks that are declared using task allocators at the library level
23048 start executing immediately and hence can execute at elaboration time.
23049 @end table
23050
23051 @noindent
23052 Subprogram calls are possible in any of these contexts, which means that
23053 any arbitrary part of the program may be executed as part of the elaboration
23054 code. It is even possible to write a program which does all its work at
23055 elaboration time, with a null main program, although stylistically this
23056 would usually be considered an inappropriate way to structure
23057 a program.
23058
23059 An important concern arises in the context of elaboration code:
23060 we have to be sure that it is executed in an appropriate order. What we
23061 have is a series of elaboration code sections, potentially one section
23062 for each unit in the program. It is important that these execute
23063 in the correct order. Correctness here means that, taking the above
23064 example of the declaration of @code{Sqrt_Half},
23065 if some other piece of
23066 elaboration code references @code{Sqrt_Half},
23067 then it must run after the
23068 section of elaboration code that contains the declaration of
23069 @code{Sqrt_Half}.
23070
23071 There would never be any order of elaboration problem if we made a rule
23072 that whenever you @code{with} a unit, you must elaborate both the spec and body
23073 of that unit before elaborating the unit doing the @code{with}'ing:
23074
23075 @smallexample @c ada
23076 @group
23077 @cartouche
23078 with Unit_1;
23079 package Unit_2 is @dots{}
23080 @end cartouche
23081 @end group
23082 @end smallexample
23083
23084 @noindent
23085 would require that both the body and spec of @code{Unit_1} be elaborated
23086 before the spec of @code{Unit_2}. However, a rule like that would be far too
23087 restrictive. In particular, it would make it impossible to have routines
23088 in separate packages that were mutually recursive.
23089
23090 You might think that a clever enough compiler could look at the actual
23091 elaboration code and determine an appropriate correct order of elaboration,
23092 but in the general case, this is not possible. Consider the following
23093 example.
23094
23095 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
23096 that references
23097 the variable @code{Sqrt_1}, which is declared in the elaboration code
23098 of the body of @code{Unit_1}:
23099
23100 @smallexample @c ada
23101 @cartouche
23102 Sqrt_1 : Float := Sqrt (0.1);
23103 @end cartouche
23104 @end smallexample
23105
23106 @noindent
23107 The elaboration code of the body of @code{Unit_1} also contains:
23108
23109 @smallexample @c ada
23110 @group
23111 @cartouche
23112 if expression_1 = 1 then
23113    Q := Unit_2.Func_2;
23114 end if;
23115 @end cartouche
23116 @end group
23117 @end smallexample
23118
23119 @noindent
23120 @code{Unit_2} is exactly parallel,
23121 it has a procedure @code{Func_2} that references
23122 the variable @code{Sqrt_2}, which is declared in the elaboration code of
23123 the body @code{Unit_2}:
23124
23125 @smallexample @c ada
23126 @cartouche
23127 Sqrt_2 : Float := Sqrt (0.1);
23128 @end cartouche
23129 @end smallexample
23130
23131 @noindent
23132 The elaboration code of the body of @code{Unit_2} also contains:
23133
23134 @smallexample @c ada
23135 @group
23136 @cartouche
23137 if expression_2 = 2 then
23138    Q := Unit_1.Func_1;
23139 end if;
23140 @end cartouche
23141 @end group
23142 @end smallexample
23143
23144 @noindent
23145 Now the question is, which of the following orders of elaboration is
23146 acceptable:
23147
23148 @smallexample
23149 @group
23150 Spec of Unit_1
23151 Spec of Unit_2
23152 Body of Unit_1
23153 Body of Unit_2
23154 @end group
23155 @end smallexample
23156
23157 @noindent
23158 or
23159
23160 @smallexample
23161 @group
23162 Spec of Unit_2
23163 Spec of Unit_1
23164 Body of Unit_2
23165 Body of Unit_1
23166 @end group
23167 @end smallexample
23168
23169 @noindent
23170 If you carefully analyze the flow here, you will see that you cannot tell
23171 at compile time the answer to this question.
23172 If @code{expression_1} is not equal to 1,
23173 and @code{expression_2} is not equal to 2,
23174 then either order is acceptable, because neither of the function calls is
23175 executed. If both tests evaluate to true, then neither order is acceptable
23176 and in fact there is no correct order.
23177
23178 If one of the two expressions is true, and the other is false, then one
23179 of the above orders is correct, and the other is incorrect. For example,
23180 if @code{expression_1} /= 1 and @code{expression_2} = 2,
23181 then the call to @code{Func_1}
23182 will occur, but not the call to @code{Func_2.}
23183 This means that it is essential
23184 to elaborate the body of @code{Unit_1} before
23185 the body of @code{Unit_2}, so the first
23186 order of elaboration is correct and the second is wrong.
23187
23188 By making @code{expression_1} and @code{expression_2}
23189 depend on input data, or perhaps
23190 the time of day, we can make it impossible for the compiler or binder
23191 to figure out which of these expressions will be true, and hence it
23192 is impossible to guarantee a safe order of elaboration at run time.
23193
23194 @node Checking the Elaboration Order
23195 @section Checking the Elaboration Order
23196
23197 @noindent
23198 In some languages that involve the same kind of elaboration problems,
23199 e.g.@: Java and C++, the programmer is expected to worry about these
23200 ordering problems himself, and it is common to
23201 write a program in which an incorrect elaboration order  gives
23202 surprising results, because it references variables before they
23203 are initialized.
23204 Ada is designed to be a safe language, and a programmer-beware approach is
23205 clearly not sufficient. Consequently, the language provides three lines
23206 of defense:
23207
23208 @table @asis
23209 @item Standard rules
23210 Some standard rules restrict the possible choice of elaboration
23211 order. In particular, if you @code{with} a unit, then its spec is always
23212 elaborated before the unit doing the @code{with}. Similarly, a parent
23213 spec is always elaborated before the child spec, and finally
23214 a spec is always elaborated before its corresponding body.
23215
23216 @item Dynamic elaboration checks
23217 @cindex Elaboration checks
23218 @cindex Checks, elaboration
23219 Dynamic checks are made at run time, so that if some entity is accessed
23220 before it is elaborated (typically  by means of a subprogram call)
23221 then the exception (@code{Program_Error}) is raised.
23222
23223 @item Elaboration control
23224 Facilities are provided for the programmer to specify the desired order
23225 of elaboration.
23226 @end table
23227
23228 Let's look at these facilities in more detail. First, the rules for
23229 dynamic checking. One possible rule would be simply to say that the
23230 exception is raised if you access a variable which has not yet been
23231 elaborated. The trouble with this approach is that it could require
23232 expensive checks on every variable reference. Instead Ada has two
23233 rules which are a little more restrictive, but easier to check, and
23234 easier to state:
23235
23236 @table @asis
23237 @item Restrictions on calls
23238 A subprogram can only be called at elaboration time if its body
23239 has been elaborated. The rules for elaboration given above guarantee
23240 that the spec of the subprogram has been elaborated before the
23241 call, but not the body. If this rule is violated, then the
23242 exception @code{Program_Error} is raised.
23243
23244 @item Restrictions on instantiations
23245 A generic unit can only be instantiated if the body of the generic
23246 unit has been elaborated. Again, the rules for elaboration given above
23247 guarantee that the spec of the generic unit has been elaborated
23248 before the instantiation, but not the body. If this rule is
23249 violated, then the exception @code{Program_Error} is raised.
23250 @end table
23251
23252 @noindent
23253 The idea is that if the body has been elaborated, then any variables
23254 it references must have been elaborated; by checking for the body being
23255 elaborated we guarantee that none of its references causes any
23256 trouble. As we noted above, this is a little too restrictive, because a
23257 subprogram that has no non-local references in its body may in fact be safe
23258 to call. However, it really would be unsafe to rely on this, because
23259 it would mean that the caller was aware of details of the implementation
23260 in the body. This goes against the basic tenets of Ada.
23261
23262 A plausible implementation can be described as follows.
23263 A Boolean variable is associated with each subprogram
23264 and each generic unit. This variable is initialized to False, and is set to
23265 True at the point body is elaborated. Every call or instantiation checks the
23266 variable, and raises @code{Program_Error} if the variable is False.
23267
23268 Note that one might think that it would be good enough to have one Boolean
23269 variable for each package, but that would not deal with cases of trying
23270 to call a body in the same package as the call
23271 that has not been elaborated yet.
23272 Of course a compiler may be able to do enough analysis to optimize away
23273 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
23274 does such optimizations, but still the easiest conceptual model is to
23275 think of there being one variable per subprogram.
23276
23277 @node Controlling the Elaboration Order
23278 @section Controlling the Elaboration Order
23279
23280 @noindent
23281 In the previous section we discussed the rules in Ada which ensure
23282 that @code{Program_Error} is raised if an incorrect elaboration order is
23283 chosen. This prevents erroneous executions, but we need mechanisms to
23284 specify a correct execution and avoid the exception altogether.
23285 To achieve this, Ada provides a number of features for controlling
23286 the order of elaboration. We discuss these features in this section.
23287
23288 First, there are several ways of indicating to the compiler that a given
23289 unit has no elaboration problems:
23290
23291 @table @asis
23292 @item packages that do not require a body
23293 A library package that does not require a body does not permit
23294 a body (this rule was introduced in Ada 95).
23295 Thus if we have a such a package, as in:
23296
23297 @smallexample @c ada
23298 @group
23299 @cartouche
23300 package Definitions is
23301    generic
23302       type m is new integer;
23303    package Subp is
23304       type a is array (1 .. 10) of m;
23305       type b is array (1 .. 20) of m;
23306    end Subp;
23307 end Definitions;
23308 @end cartouche
23309 @end group
23310 @end smallexample
23311
23312 @noindent
23313 A package that @code{with}'s @code{Definitions} may safely instantiate
23314 @code{Definitions.Subp} because the compiler can determine that there
23315 definitely is no package body to worry about in this case
23316
23317 @item pragma Pure
23318 @cindex pragma Pure
23319 @findex Pure
23320 Places sufficient restrictions on a unit to guarantee that
23321 no call to any subprogram in the unit can result in an
23322 elaboration problem. This means that the compiler does not need
23323 to worry about the point of elaboration of such units, and in
23324 particular, does not need to check any calls to any subprograms
23325 in this unit.
23326
23327 @item pragma Preelaborate
23328 @findex Preelaborate
23329 @cindex pragma Preelaborate
23330 This pragma places slightly less stringent restrictions on a unit than
23331 does pragma Pure,
23332 but these restrictions are still sufficient to ensure that there
23333 are no elaboration problems with any calls to the unit.
23334
23335 @item pragma Elaborate_Body
23336 @findex Elaborate_Body
23337 @cindex pragma Elaborate_Body
23338 This pragma requires that the body of a unit be elaborated immediately
23339 after its spec. Suppose a unit @code{A} has such a pragma,
23340 and unit @code{B} does
23341 a @code{with} of unit @code{A}. Recall that the standard rules require
23342 the spec of unit @code{A}
23343 to be elaborated before the @code{with}'ing unit; given the pragma in
23344 @code{A}, we also know that the body of @code{A}
23345 will be elaborated before @code{B}, so
23346 that calls to @code{A} are safe and do not need a check.
23347 @end table
23348
23349 @noindent
23350 Note that,
23351 unlike pragma @code{Pure} and pragma @code{Preelaborate},
23352 the use of
23353 @code{Elaborate_Body} does not guarantee that the program is
23354 free of elaboration problems, because it may not be possible
23355 to satisfy the requested elaboration order.
23356 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
23357 If a programmer
23358 marks @code{Unit_1} as @code{Elaborate_Body},
23359 and not @code{Unit_2,} then the order of
23360 elaboration will be:
23361
23362 @smallexample
23363 @group
23364 Spec of Unit_2
23365 Spec of Unit_1
23366 Body of Unit_1
23367 Body of Unit_2
23368 @end group
23369 @end smallexample
23370
23371 @noindent
23372 Now that means that the call to @code{Func_1} in @code{Unit_2}
23373 need not be checked,
23374 it must be safe. But the call to @code{Func_2} in
23375 @code{Unit_1} may still fail if
23376 @code{Expression_1} is equal to 1,
23377 and the programmer must still take
23378 responsibility for this not being the case.
23379
23380 If all units carry a pragma @code{Elaborate_Body}, then all problems are
23381 eliminated, except for calls entirely within a body, which are
23382 in any case fully under programmer control. However, using the pragma
23383 everywhere is not always possible.
23384 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
23385 we marked both of them as having pragma @code{Elaborate_Body}, then
23386 clearly there would be no possible elaboration order.
23387
23388 The above pragmas allow a server to guarantee safe use by clients, and
23389 clearly this is the preferable approach. Consequently a good rule
23390 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
23391 and if this is not possible,
23392 mark them as @code{Elaborate_Body} if possible.
23393 As we have seen, there are situations where neither of these
23394 three pragmas can be used.
23395 So we also provide methods for clients to control the
23396 order of elaboration of the servers on which they depend:
23397
23398 @table @asis
23399 @item pragma Elaborate (unit)
23400 @findex Elaborate
23401 @cindex pragma Elaborate
23402 This pragma is placed in the context clause, after a @code{with} clause,
23403 and it requires that the body of the named unit be elaborated before
23404 the unit in which the pragma occurs. The idea is to use this pragma
23405 if the current unit calls at elaboration time, directly or indirectly,
23406 some subprogram in the named unit.
23407
23408 @item pragma Elaborate_All (unit)
23409 @findex Elaborate_All
23410 @cindex pragma Elaborate_All
23411 This is a stronger version of the Elaborate pragma. Consider the
23412 following example:
23413
23414 @smallexample
23415 Unit A @code{with}'s unit B and calls B.Func in elab code
23416 Unit B @code{with}'s unit C, and B.Func calls C.Func
23417 @end smallexample
23418
23419 @noindent
23420 Now if we put a pragma @code{Elaborate (B)}
23421 in unit @code{A}, this ensures that the
23422 body of @code{B} is elaborated before the call, but not the
23423 body of @code{C}, so
23424 the call to @code{C.Func} could still cause @code{Program_Error} to
23425 be raised.
23426
23427 The effect of a pragma @code{Elaborate_All} is stronger, it requires
23428 not only that the body of the named unit be elaborated before the
23429 unit doing the @code{with}, but also the bodies of all units that the
23430 named unit uses, following @code{with} links transitively. For example,
23431 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
23432 then it requires
23433 not only that the body of @code{B} be elaborated before @code{A},
23434 but also the
23435 body of @code{C}, because @code{B} @code{with}'s @code{C}.
23436 @end table
23437
23438 @noindent
23439 We are now in a position to give a usage rule in Ada for avoiding
23440 elaboration problems, at least if dynamic dispatching and access to
23441 subprogram values are not used. We will handle these cases separately
23442 later.
23443
23444 The rule is simple. If a unit has elaboration code that can directly or
23445 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
23446 a generic package in a @code{with}'ed unit,
23447 then if the @code{with}'ed unit does not have
23448 pragma @code{Pure} or @code{Preelaborate}, then the client should have
23449 a pragma @code{Elaborate_All}
23450 for the @code{with}'ed unit. By following this rule a client is
23451 assured that calls can be made without risk of an exception.
23452
23453 For generic subprogram instantiations, the rule can be relaxed to
23454 require only a pragma @code{Elaborate} since elaborating the body
23455 of a subprogram cannot cause any transitive elaboration (we are
23456 not calling the subprogram in this case, just elaborating its
23457 declaration).
23458
23459 If this rule is not followed, then a program may be in one of four
23460 states:
23461
23462 @table @asis
23463 @item No order exists
23464 No order of elaboration exists which follows the rules, taking into
23465 account any @code{Elaborate}, @code{Elaborate_All},
23466 or @code{Elaborate_Body} pragmas. In
23467 this case, an Ada compiler must diagnose the situation at bind
23468 time, and refuse to build an executable program.
23469
23470 @item One or more orders exist, all incorrect
23471 One or more acceptable elaboration orders exist, and all of them
23472 generate an elaboration order problem. In this case, the binder
23473 can build an executable program, but @code{Program_Error} will be raised
23474 when the program is run.
23475
23476 @item Several orders exist, some right, some incorrect
23477 One or more acceptable elaboration orders exists, and some of them
23478 work, and some do not. The programmer has not controlled
23479 the order of elaboration, so the binder may or may not pick one of
23480 the correct orders, and the program may or may not raise an
23481 exception when it is run. This is the worst case, because it means
23482 that the program may fail when moved to another compiler, or even
23483 another version of the same compiler.
23484
23485 @item One or more orders exists, all correct
23486 One ore more acceptable elaboration orders exist, and all of them
23487 work. In this case the program runs successfully. This state of
23488 affairs can be guaranteed by following the rule we gave above, but
23489 may be true even if the rule is not followed.
23490 @end table
23491
23492 @noindent
23493 Note that one additional advantage of following our rules on the use
23494 of @code{Elaborate} and @code{Elaborate_All}
23495 is that the program continues to stay in the ideal (all orders OK) state
23496 even if maintenance
23497 changes some bodies of some units. Conversely, if a program that does
23498 not follow this rule happens to be safe at some point, this state of affairs
23499 may deteriorate silently as a result of maintenance changes.
23500
23501 You may have noticed that the above discussion did not mention
23502 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
23503 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
23504 code in the body makes calls to some other unit, so it is still necessary
23505 to use @code{Elaborate_All} on such units.
23506
23507 @node Controlling Elaboration in GNAT - Internal Calls
23508 @section Controlling Elaboration in GNAT - Internal Calls
23509
23510 @noindent
23511 In the case of internal calls, i.e., calls within a single package, the
23512 programmer has full control over the order of elaboration, and it is up
23513 to the programmer to elaborate declarations in an appropriate order. For
23514 example writing:
23515
23516 @smallexample @c ada
23517 @group
23518 @cartouche
23519 function One return Float;
23520
23521 Q : Float := One;
23522
23523 function One return Float is
23524 begin
23525      return 1.0;
23526 end One;
23527 @end cartouche
23528 @end group
23529 @end smallexample
23530
23531 @noindent
23532 will obviously raise @code{Program_Error} at run time, because function
23533 One will be called before its body is elaborated. In this case GNAT will
23534 generate a warning that the call will raise @code{Program_Error}:
23535
23536 @smallexample
23537 @group
23538 @cartouche
23539  1. procedure y is
23540  2.    function One return Float;
23541  3.
23542  4.    Q : Float := One;
23543                     |
23544     >>> warning: cannot call "One" before body is elaborated
23545     >>> warning: Program_Error will be raised at run time
23546
23547  5.
23548  6.    function One return Float is
23549  7.    begin
23550  8.         return 1.0;
23551  9.    end One;
23552 10.
23553 11. begin
23554 12.    null;
23555 13. end;
23556 @end cartouche
23557 @end group
23558 @end smallexample
23559
23560 @noindent
23561 Note that in this particular case, it is likely that the call is safe, because
23562 the function @code{One} does not access any global variables.
23563 Nevertheless in Ada, we do not want the validity of the check to depend on
23564 the contents of the body (think about the separate compilation case), so this
23565 is still wrong, as we discussed in the previous sections.
23566
23567 The error is easily corrected by rearranging the declarations so that the
23568 body of @code{One} appears before the declaration containing the call
23569 (note that in Ada 95 and Ada 2005,
23570 declarations can appear in any order, so there is no restriction that
23571 would prevent this reordering, and if we write:
23572
23573 @smallexample @c ada
23574 @group
23575 @cartouche
23576 function One return Float;
23577
23578 function One return Float is
23579 begin
23580      return 1.0;
23581 end One;
23582
23583 Q : Float := One;
23584 @end cartouche
23585 @end group
23586 @end smallexample
23587
23588 @noindent
23589 then all is well, no warning is generated, and no
23590 @code{Program_Error} exception
23591 will be raised.
23592 Things are more complicated when a chain of subprograms is executed:
23593
23594 @smallexample @c ada
23595 @group
23596 @cartouche
23597 function A return Integer;
23598 function B return Integer;
23599 function C return Integer;
23600
23601 function B return Integer is begin return A; end;
23602 function C return Integer is begin return B; end;
23603
23604 X : Integer := C;
23605
23606 function A return Integer is begin return 1; end;
23607 @end cartouche
23608 @end group
23609 @end smallexample
23610
23611 @noindent
23612 Now the call to @code{C}
23613 at elaboration time in the declaration of @code{X} is correct, because
23614 the body of @code{C} is already elaborated,
23615 and the call to @code{B} within the body of
23616 @code{C} is correct, but the call
23617 to @code{A} within the body of @code{B} is incorrect, because the body
23618 of @code{A} has not been elaborated, so @code{Program_Error}
23619 will be raised on the call to @code{A}.
23620 In this case GNAT will generate a
23621 warning that @code{Program_Error} may be
23622 raised at the point of the call. Let's look at the warning:
23623
23624 @smallexample
23625 @group
23626 @cartouche
23627  1. procedure x is
23628  2.    function A return Integer;
23629  3.    function B return Integer;
23630  4.    function C return Integer;
23631  5.
23632  6.    function B return Integer is begin return A; end;
23633                                                     |
23634     >>> warning: call to "A" before body is elaborated may
23635                  raise Program_Error
23636     >>> warning: "B" called at line 7
23637     >>> warning: "C" called at line 9
23638
23639  7.    function C return Integer is begin return B; end;
23640  8.
23641  9.    X : Integer := C;
23642 10.
23643 11.    function A return Integer is begin return 1; end;
23644 12.
23645 13. begin
23646 14.    null;
23647 15. end;
23648 @end cartouche
23649 @end group
23650 @end smallexample
23651
23652 @noindent
23653 Note that the message here says ``may raise'', instead of the direct case,
23654 where the message says ``will be raised''. That's because whether
23655 @code{A} is
23656 actually called depends in general on run-time flow of control.
23657 For example, if the body of @code{B} said
23658
23659 @smallexample @c ada
23660 @group
23661 @cartouche
23662 function B return Integer is
23663 begin
23664    if some-condition-depending-on-input-data then
23665       return A;
23666    else
23667       return 1;
23668    end if;
23669 end B;
23670 @end cartouche
23671 @end group
23672 @end smallexample
23673
23674 @noindent
23675 then we could not know until run time whether the incorrect call to A would
23676 actually occur, so @code{Program_Error} might
23677 or might not be raised. It is possible for a compiler to
23678 do a better job of analyzing bodies, to
23679 determine whether or not @code{Program_Error}
23680 might be raised, but it certainly
23681 couldn't do a perfect job (that would require solving the halting problem
23682 and is provably impossible), and because this is a warning anyway, it does
23683 not seem worth the effort to do the analysis. Cases in which it
23684 would be relevant are rare.
23685
23686 In practice, warnings of either of the forms given
23687 above will usually correspond to
23688 real errors, and should be examined carefully and eliminated.
23689 In the rare case where a warning is bogus, it can be suppressed by any of
23690 the following methods:
23691
23692 @itemize @bullet
23693 @item
23694 Compile with the @option{-gnatws} switch set
23695
23696 @item
23697 Suppress @code{Elaboration_Check} for the called subprogram
23698
23699 @item
23700 Use pragma @code{Warnings_Off} to turn warnings off for the call
23701 @end itemize
23702
23703 @noindent
23704 For the internal elaboration check case,
23705 GNAT by default generates the
23706 necessary run-time checks to ensure
23707 that @code{Program_Error} is raised if any
23708 call fails an elaboration check. Of course this can only happen if a
23709 warning has been issued as described above. The use of pragma
23710 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
23711 some of these checks, meaning that it may be possible (but is not
23712 guaranteed) for a program to be able to call a subprogram whose body
23713 is not yet elaborated, without raising a @code{Program_Error} exception.
23714
23715 @node Controlling Elaboration in GNAT - External Calls
23716 @section Controlling Elaboration in GNAT - External Calls
23717
23718 @noindent
23719 The previous section discussed the case in which the execution of a
23720 particular thread of elaboration code occurred entirely within a
23721 single unit. This is the easy case to handle, because a programmer
23722 has direct and total control over the order of elaboration, and
23723 furthermore, checks need only be generated in cases which are rare
23724 and which the compiler can easily detect.
23725 The situation is more complex when separate compilation is taken into account.
23726 Consider the following:
23727
23728 @smallexample @c ada
23729 @cartouche
23730 @group
23731 package Math is
23732    function Sqrt (Arg : Float) return Float;
23733 end Math;
23734
23735 package body Math is
23736    function Sqrt (Arg : Float) return Float is
23737    begin
23738          @dots{}
23739    end Sqrt;
23740 end Math;
23741 @end group
23742 @group
23743 with Math;
23744 package Stuff is
23745    X : Float := Math.Sqrt (0.5);
23746 end Stuff;
23747
23748 with Stuff;
23749 procedure Main is
23750 begin
23751    @dots{}
23752 end Main;
23753 @end group
23754 @end cartouche
23755 @end smallexample
23756
23757 @noindent
23758 where @code{Main} is the main program. When this program is executed, the
23759 elaboration code must first be executed, and one of the jobs of the
23760 binder is to determine the order in which the units of a program are
23761 to be elaborated. In this case we have four units: the spec and body
23762 of @code{Math},
23763 the spec of @code{Stuff} and the body of @code{Main}).
23764 In what order should the four separate sections of elaboration code
23765 be executed?
23766
23767 There are some restrictions in the order of elaboration that the binder
23768 can choose. In particular, if unit U has a @code{with}
23769 for a package @code{X}, then you
23770 are assured that the spec of @code{X}
23771 is elaborated before U , but you are
23772 not assured that the body of @code{X}
23773 is elaborated before U.
23774 This means that in the above case, the binder is allowed to choose the
23775 order:
23776
23777 @smallexample
23778 spec of Math
23779 spec of Stuff
23780 body of Math
23781 body of Main
23782 @end smallexample
23783
23784 @noindent
23785 but that's not good, because now the call to @code{Math.Sqrt}
23786 that happens during
23787 the elaboration of the @code{Stuff}
23788 spec happens before the body of @code{Math.Sqrt} is
23789 elaborated, and hence causes @code{Program_Error} exception to be raised.
23790 At first glance, one might say that the binder is misbehaving, because
23791 obviously you want to elaborate the body of something you @code{with}
23792 first, but
23793 that is not a general rule that can be followed in all cases. Consider
23794
23795 @smallexample @c ada
23796 @group
23797 @cartouche
23798 package X is @dots{}
23799
23800 package Y is @dots{}
23801
23802 with X;
23803 package body Y is @dots{}
23804
23805 with Y;
23806 package body X is @dots{}
23807 @end cartouche
23808 @end group
23809 @end smallexample
23810
23811 @noindent
23812 This is a common arrangement, and, apart from the order of elaboration
23813 problems that might arise in connection with elaboration code, this works fine.
23814 A rule that says that you must first elaborate the body of anything you
23815 @code{with} cannot work in this case:
23816 the body of @code{X} @code{with}'s @code{Y},
23817 which means you would have to
23818 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
23819 which means
23820 you have to elaborate the body of @code{X} first, but @dots{} and we have a
23821 loop that cannot be broken.
23822
23823 It is true that the binder can in many cases guess an order of elaboration
23824 that is unlikely to cause a @code{Program_Error}
23825 exception to be raised, and it tries to do so (in the
23826 above example of @code{Math/Stuff/Spec}, the GNAT binder will
23827 by default
23828 elaborate the body of @code{Math} right after its spec, so all will be well).
23829
23830 However, a program that blindly relies on the binder to be helpful can
23831 get into trouble, as we discussed in the previous sections, so
23832 GNAT
23833 provides a number of facilities for assisting the programmer in
23834 developing programs that are robust with respect to elaboration order.
23835
23836 @node Default Behavior in GNAT - Ensuring Safety
23837 @section Default Behavior in GNAT - Ensuring Safety
23838
23839 @noindent
23840 The default behavior in GNAT ensures elaboration safety. In its
23841 default mode GNAT implements the
23842 rule we previously described as the right approach. Let's restate it:
23843
23844 @itemize
23845 @item
23846 @emph{If a unit has elaboration code that can directly or indirectly make a
23847 call to a subprogram in a @code{with}'ed unit, or instantiate a generic
23848 package in a @code{with}'ed unit, then if the @code{with}'ed unit
23849 does not have pragma @code{Pure} or
23850 @code{Preelaborate}, then the client should have an
23851 @code{Elaborate_All} pragma for the @code{with}'ed unit.}
23852
23853 @emph{In the case of instantiating a generic subprogram, it is always
23854 sufficient to have only an @code{Elaborate} pragma for the
23855 @code{with}'ed unit.}
23856 @end itemize
23857
23858 @noindent
23859 By following this rule a client is assured that calls and instantiations
23860 can be made without risk of an exception.
23861
23862 In this mode GNAT traces all calls that are potentially made from
23863 elaboration code, and puts in any missing implicit @code{Elaborate}
23864 and @code{Elaborate_All} pragmas.
23865 The advantage of this approach is that no elaboration problems
23866 are possible if the binder can find an elaboration order that is
23867 consistent with these implicit @code{Elaborate} and
23868 @code{Elaborate_All} pragmas. The
23869 disadvantage of this approach is that no such order may exist.
23870
23871 If the binder does not generate any diagnostics, then it means that it has
23872 found an elaboration order that is guaranteed to be safe. However, the binder
23873 may still be relying on implicitly generated @code{Elaborate} and
23874 @code{Elaborate_All} pragmas so portability to other compilers than GNAT is not
23875 guaranteed.
23876
23877 If it is important to guarantee portability, then the compilations should
23878 use the
23879 @option{-gnatwl}
23880 (warn on elaboration problems) switch. This will cause warning messages
23881 to be generated indicating the missing @code{Elaborate} and
23882 @code{Elaborate_All} pragmas.
23883 Consider the following source program:
23884
23885 @smallexample @c ada
23886 @group
23887 @cartouche
23888 with k;
23889 package j is
23890   m : integer := k.r;
23891 end;
23892 @end cartouche
23893 @end group
23894 @end smallexample
23895
23896 @noindent
23897 where it is clear that there
23898 should be a pragma @code{Elaborate_All}
23899 for unit @code{k}. An implicit pragma will be generated, and it is
23900 likely that the binder will be able to honor it. However, if you want
23901 to port this program to some other Ada compiler than GNAT.
23902 it is safer to include the pragma explicitly in the source. If this
23903 unit is compiled with the
23904 @option{-gnatwl}
23905 switch, then the compiler outputs a warning:
23906
23907 @smallexample
23908 @group
23909 @cartouche
23910 1. with k;
23911 2. package j is
23912 3.   m : integer := k.r;
23913                      |
23914    >>> warning: call to "r" may raise Program_Error
23915    >>> warning: missing pragma Elaborate_All for "k"
23916
23917 4. end;
23918 @end cartouche
23919 @end group
23920 @end smallexample
23921
23922 @noindent
23923 and these warnings can be used as a guide for supplying manually
23924 the missing pragmas. It is usually a bad idea to use this warning
23925 option during development. That's because it will warn you when
23926 you need to put in a pragma, but cannot warn you when it is time
23927 to take it out. So the use of pragma @code{Elaborate_All} may lead to
23928 unnecessary dependencies and even false circularities.
23929
23930 This default mode is more restrictive than the Ada Reference
23931 Manual, and it is possible to construct programs which will compile
23932 using the dynamic model described there, but will run into a
23933 circularity using the safer static model we have described.
23934
23935 Of course any Ada compiler must be able to operate in a mode
23936 consistent with the requirements of the Ada Reference Manual,
23937 and in particular must have the capability of implementing the
23938 standard dynamic model of elaboration with run-time checks.
23939
23940 In GNAT, this standard mode can be achieved either by the use of
23941 the @option{-gnatE} switch on the compiler (@command{gcc} or
23942 @command{gnatmake}) command, or by the use of the configuration pragma:
23943
23944 @smallexample @c ada
23945 pragma Elaboration_Checks (DYNAMIC);
23946 @end smallexample
23947
23948 @noindent
23949 Either approach will cause the unit affected to be compiled using the
23950 standard dynamic run-time elaboration checks described in the Ada
23951 Reference Manual. The static model is generally preferable, since it
23952 is clearly safer to rely on compile and link time checks rather than
23953 run-time checks. However, in the case of legacy code, it may be
23954 difficult to meet the requirements of the static model. This
23955 issue is further discussed in
23956 @ref{What to Do If the Default Elaboration Behavior Fails}.
23957
23958 Note that the static model provides a strict subset of the allowed
23959 behavior and programs of the Ada Reference Manual, so if you do
23960 adhere to the static model and no circularities exist,
23961 then you are assured that your program will
23962 work using the dynamic model, providing that you remove any
23963 pragma Elaborate statements from the source.
23964
23965 @node Treatment of Pragma Elaborate
23966 @section Treatment of Pragma Elaborate
23967 @cindex Pragma Elaborate
23968
23969 @noindent
23970 The use of @code{pragma Elaborate}
23971 should generally be avoided in Ada 95 and Ada 2005 programs,
23972 since there is no guarantee that transitive calls
23973 will be properly handled. Indeed at one point, this pragma was placed
23974 in Annex J (Obsolescent Features), on the grounds that it is never useful.
23975
23976 Now that's a bit restrictive. In practice, the case in which
23977 @code{pragma Elaborate} is useful is when the caller knows that there
23978 are no transitive calls, or that the called unit contains all necessary
23979 transitive @code{pragma Elaborate} statements, and legacy code often
23980 contains such uses.
23981
23982 Strictly speaking the static mode in GNAT should ignore such pragmas,
23983 since there is no assurance at compile time that the necessary safety
23984 conditions are met. In practice, this would cause GNAT to be incompatible
23985 with correctly written Ada 83 code that had all necessary
23986 @code{pragma Elaborate} statements in place. Consequently, we made the
23987 decision that GNAT in its default mode will believe that if it encounters
23988 a @code{pragma Elaborate} then the programmer knows what they are doing,
23989 and it will trust that no elaboration errors can occur.
23990
23991 The result of this decision is two-fold. First to be safe using the
23992 static mode, you should remove all @code{pragma Elaborate} statements.
23993 Second, when fixing circularities in existing code, you can selectively
23994 use @code{pragma Elaborate} statements to convince the static mode of
23995 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
23996 statement.
23997
23998 When using the static mode with @option{-gnatwl}, any use of
23999 @code{pragma Elaborate} will generate a warning about possible
24000 problems.
24001
24002 @node Elaboration Issues for Library Tasks
24003 @section Elaboration Issues for Library Tasks
24004 @cindex Library tasks, elaboration issues
24005 @cindex Elaboration of library tasks
24006
24007 @noindent
24008 In this section we examine special elaboration issues that arise for
24009 programs that declare library level tasks.
24010
24011 Generally the model of execution of an Ada program is that all units are
24012 elaborated, and then execution of the program starts. However, the
24013 declaration of library tasks definitely does not fit this model. The
24014 reason for this is that library tasks start as soon as they are declared
24015 (more precisely, as soon as the statement part of the enclosing package
24016 body is reached), that is to say before elaboration
24017 of the program is complete. This means that if such a task calls a
24018 subprogram, or an entry in another task, the callee may or may not be
24019 elaborated yet, and in the standard
24020 Reference Manual model of dynamic elaboration checks, you can even
24021 get timing dependent Program_Error exceptions, since there can be
24022 a race between the elaboration code and the task code.
24023
24024 The static model of elaboration in GNAT seeks to avoid all such
24025 dynamic behavior, by being conservative, and the conservative
24026 approach in this particular case is to assume that all the code
24027 in a task body is potentially executed at elaboration time if
24028 a task is declared at the library level.
24029
24030 This can definitely result in unexpected circularities. Consider
24031 the following example
24032
24033 @smallexample @c ada
24034 package Decls is
24035   task Lib_Task is
24036      entry Start;
24037   end Lib_Task;
24038
24039   type My_Int is new Integer;
24040
24041   function Ident (M : My_Int) return My_Int;
24042 end Decls;
24043
24044 with Utils;
24045 package body Decls is
24046   task body Lib_Task is
24047   begin
24048      accept Start;
24049      Utils.Put_Val (2);
24050   end Lib_Task;
24051
24052   function Ident (M : My_Int) return My_Int is
24053   begin
24054      return M;
24055   end Ident;
24056 end Decls;
24057
24058 with Decls;
24059 package Utils is
24060   procedure Put_Val (Arg : Decls.My_Int);
24061 end Utils;
24062
24063 with Text_IO;
24064 package body Utils is
24065   procedure Put_Val (Arg : Decls.My_Int) is
24066   begin
24067      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
24068   end Put_Val;
24069 end Utils;
24070
24071 with Decls;
24072 procedure Main is
24073 begin
24074    Decls.Lib_Task.Start;
24075 end;
24076 @end smallexample
24077
24078 @noindent
24079 If the above example is compiled in the default static elaboration
24080 mode, then a circularity occurs. The circularity comes from the call
24081 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
24082 this call occurs in elaboration code, we need an implicit pragma
24083 @code{Elaborate_All} for @code{Utils}. This means that not only must
24084 the spec and body of @code{Utils} be elaborated before the body
24085 of @code{Decls}, but also the spec and body of any unit that is
24086 @code{with'ed} by the body of @code{Utils} must also be elaborated before
24087 the body of @code{Decls}. This is the transitive implication of
24088 pragma @code{Elaborate_All} and it makes sense, because in general
24089 the body of @code{Put_Val} might have a call to something in a
24090 @code{with'ed} unit.
24091
24092 In this case, the body of Utils (actually its spec) @code{with's}
24093 @code{Decls}. Unfortunately this means that the body of @code{Decls}
24094 must be elaborated before itself, in case there is a call from the
24095 body of @code{Utils}.
24096
24097 Here is the exact chain of events we are worrying about:
24098
24099 @enumerate
24100 @item
24101 In the body of @code{Decls} a call is made from within the body of a library
24102 task to a subprogram in the package @code{Utils}. Since this call may
24103 occur at elaboration time (given that the task is activated at elaboration
24104 time), we have to assume the worst, i.e., that the
24105 call does happen at elaboration time.
24106
24107 @item
24108 This means that the body and spec of @code{Util} must be elaborated before
24109 the body of @code{Decls} so that this call does not cause an access before
24110 elaboration.
24111
24112 @item
24113 Within the body of @code{Util}, specifically within the body of
24114 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
24115 by this package.
24116
24117 @item
24118 One such @code{with}'ed package is package @code{Decls}, so there
24119 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
24120 In fact there is such a call in this example, but we would have to
24121 assume that there was such a call even if it were not there, since
24122 we are not supposed to write the body of @code{Decls} knowing what
24123 is in the body of @code{Utils}; certainly in the case of the
24124 static elaboration model, the compiler does not know what is in
24125 other bodies and must assume the worst.
24126
24127 @item
24128 This means that the spec and body of @code{Decls} must also be
24129 elaborated before we elaborate the unit containing the call, but
24130 that unit is @code{Decls}! This means that the body of @code{Decls}
24131 must be elaborated before itself, and that's a circularity.
24132 @end enumerate
24133
24134 @noindent
24135 Indeed, if you add an explicit pragma @code{Elaborate_All} for @code{Utils} in
24136 the body of @code{Decls} you will get a true Ada Reference Manual
24137 circularity that makes the program illegal.
24138
24139 In practice, we have found that problems with the static model of
24140 elaboration in existing code often arise from library tasks, so
24141 we must address this particular situation.
24142
24143 Note that if we compile and run the program above, using the dynamic model of
24144 elaboration (that is to say use the @option{-gnatE} switch),
24145 then it compiles, binds,
24146 links, and runs, printing the expected result of 2. Therefore in some sense
24147 the circularity here is only apparent, and we need to capture
24148 the properties of this program that  distinguish it from other library-level
24149 tasks that have real elaboration problems.
24150
24151 We have four possible answers to this question:
24152
24153 @itemize @bullet
24154
24155 @item
24156 Use the dynamic model of elaboration.
24157
24158 If we use the @option{-gnatE} switch, then as noted above, the program works.
24159 Why is this? If we examine the task body, it is apparent that the task cannot
24160 proceed past the
24161 @code{accept} statement until after elaboration has been completed, because
24162 the corresponding entry call comes from the main program, not earlier.
24163 This is why the dynamic model works here. But that's really giving
24164 up on a precise analysis, and we prefer to take this approach only if we cannot
24165 solve the
24166 problem in any other manner. So let us examine two ways to reorganize
24167 the program to avoid the potential elaboration problem.
24168
24169 @item
24170 Split library tasks into separate packages.
24171
24172 Write separate packages, so that library tasks are isolated from
24173 other declarations as much as possible. Let us look at a variation on
24174 the above program.
24175
24176 @smallexample @c ada
24177 package Decls1 is
24178   task Lib_Task is
24179      entry Start;
24180   end Lib_Task;
24181 end Decls1;
24182
24183 with Utils;
24184 package body Decls1 is
24185   task body Lib_Task is
24186   begin
24187      accept Start;
24188      Utils.Put_Val (2);
24189   end Lib_Task;
24190 end Decls1;
24191
24192 package Decls2 is
24193   type My_Int is new Integer;
24194   function Ident (M : My_Int) return My_Int;
24195 end Decls2;
24196
24197 with Utils;
24198 package body Decls2 is
24199   function Ident (M : My_Int) return My_Int is
24200   begin
24201      return M;
24202   end Ident;
24203 end Decls2;
24204
24205 with Decls2;
24206 package Utils is
24207   procedure Put_Val (Arg : Decls2.My_Int);
24208 end Utils;
24209
24210 with Text_IO;
24211 package body Utils is
24212   procedure Put_Val (Arg : Decls2.My_Int) is
24213   begin
24214      Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
24215   end Put_Val;
24216 end Utils;
24217
24218 with Decls1;
24219 procedure Main is
24220 begin
24221    Decls1.Lib_Task.Start;
24222 end;
24223 @end smallexample
24224
24225 @noindent
24226 All we have done is to split @code{Decls} into two packages, one
24227 containing the library task, and one containing everything else. Now
24228 there is no cycle, and the program compiles, binds, links and executes
24229 using the default static model of elaboration.
24230
24231 @item
24232 Declare separate task types.
24233
24234 A significant part of the problem arises because of the use of the
24235 single task declaration form. This means that the elaboration of
24236 the task type, and the elaboration of the task itself (i.e.@: the
24237 creation of the task) happen at the same time. A good rule
24238 of style in Ada is to always create explicit task types. By
24239 following the additional step of placing task objects in separate
24240 packages from the task type declaration, many elaboration problems
24241 are avoided. Here is another modified example of the example program:
24242
24243 @smallexample @c ada
24244 package Decls is
24245   task type Lib_Task_Type is
24246      entry Start;
24247   end Lib_Task_Type;
24248
24249   type My_Int is new Integer;
24250
24251   function Ident (M : My_Int) return My_Int;
24252 end Decls;
24253
24254 with Utils;
24255 package body Decls is
24256   task body Lib_Task_Type is
24257   begin
24258      accept Start;
24259      Utils.Put_Val (2);
24260   end Lib_Task_Type;
24261
24262   function Ident (M : My_Int) return My_Int is
24263   begin
24264      return M;
24265   end Ident;
24266 end Decls;
24267
24268 with Decls;
24269 package Utils is
24270   procedure Put_Val (Arg : Decls.My_Int);
24271 end Utils;
24272
24273 with Text_IO;
24274 package body Utils is
24275   procedure Put_Val (Arg : Decls.My_Int) is
24276   begin
24277      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
24278   end Put_Val;
24279 end Utils;
24280
24281 with Decls;
24282 package Declst is
24283    Lib_Task : Decls.Lib_Task_Type;
24284 end Declst;
24285
24286 with Declst;
24287 procedure Main is
24288 begin
24289    Declst.Lib_Task.Start;
24290 end;
24291 @end smallexample
24292
24293 @noindent
24294 What we have done here is to replace the @code{task} declaration in
24295 package @code{Decls} with a @code{task type} declaration. Then we
24296 introduce a separate package @code{Declst} to contain the actual
24297 task object. This separates the elaboration issues for
24298 the @code{task type}
24299 declaration, which causes no trouble, from the elaboration issues
24300 of the task object, which is also unproblematic, since it is now independent
24301 of the elaboration of  @code{Utils}.
24302 This separation of concerns also corresponds to
24303 a generally sound engineering principle of separating declarations
24304 from instances. This version of the program also compiles, binds, links,
24305 and executes, generating the expected output.
24306
24307 @item
24308 Use No_Entry_Calls_In_Elaboration_Code restriction.
24309 @cindex No_Entry_Calls_In_Elaboration_Code
24310
24311 The previous two approaches described how a program can be restructured
24312 to avoid the special problems caused by library task bodies. in practice,
24313 however, such restructuring may be difficult to apply to existing legacy code,
24314 so we must consider solutions that do not require massive rewriting.
24315
24316 Let us consider more carefully why our original sample program works
24317 under the dynamic model of elaboration. The reason is that the code
24318 in the task body blocks immediately on the @code{accept}
24319 statement. Now of course there is nothing to prohibit elaboration
24320 code from making entry calls (for example from another library level task),
24321 so we cannot tell in isolation that
24322 the task will not execute the accept statement  during elaboration.
24323
24324 However, in practice it is very unusual to see elaboration code
24325 make any entry calls, and the pattern of tasks starting
24326 at elaboration time and then immediately blocking on @code{accept} or
24327 @code{select} statements is very common. What this means is that
24328 the compiler is being too pessimistic when it analyzes the
24329 whole package body as though it might be executed at elaboration
24330 time.
24331
24332 If we know that the elaboration code contains no entry calls, (a very safe
24333 assumption most of the time, that could almost be made the default
24334 behavior), then we can compile all units of the program under control
24335 of the following configuration pragma:
24336
24337 @smallexample
24338 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
24339 @end smallexample
24340
24341 @noindent
24342 This pragma can be placed in the @file{gnat.adc} file in the usual
24343 manner. If we take our original unmodified program and compile it
24344 in the presence of a @file{gnat.adc} containing the above pragma,
24345 then once again, we can compile, bind, link, and execute, obtaining
24346 the expected result. In the presence of this pragma, the compiler does
24347 not trace calls in a task body, that appear after the first @code{accept}
24348 or @code{select} statement, and therefore does not report a potential
24349 circularity in the original program.
24350
24351 The compiler will check to the extent it can that the above
24352 restriction is not violated, but it is not always possible to do a
24353 complete check at compile time, so it is important to use this
24354 pragma only if the stated restriction is in fact met, that is to say
24355 no task receives an entry call before elaboration of all units is completed.
24356
24357 @end itemize
24358
24359 @node Mixing Elaboration Models
24360 @section Mixing Elaboration Models
24361 @noindent
24362 So far, we have assumed that the entire program is either compiled
24363 using the dynamic model or static model, ensuring consistency. It
24364 is possible to mix the two models, but rules have to be followed
24365 if this mixing is done to ensure that elaboration checks are not
24366 omitted.
24367
24368 The basic rule is that @emph{a unit compiled with the static model cannot
24369 be @code{with'ed} by a unit compiled with the dynamic model}. The
24370 reason for this is that in the static model, a unit assumes that
24371 its clients guarantee to use (the equivalent of) pragma
24372 @code{Elaborate_All} so that no elaboration checks are required
24373 in inner subprograms, and this assumption is violated if the
24374 client is compiled with dynamic checks.
24375
24376 The precise rule is as follows. A unit that is compiled with dynamic
24377 checks can only @code{with} a unit that meets at least one of the
24378 following criteria:
24379
24380 @itemize @bullet
24381
24382 @item
24383 The @code{with'ed} unit is itself compiled with dynamic elaboration
24384 checks (that is with the @option{-gnatE} switch.
24385
24386 @item
24387 The @code{with'ed} unit is an internal GNAT implementation unit from
24388 the System, Interfaces, Ada, or GNAT hierarchies.
24389
24390 @item
24391 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
24392
24393 @item
24394 The @code{with'ing} unit (that is the client) has an explicit pragma
24395 @code{Elaborate_All} for the @code{with'ed} unit.
24396
24397 @end itemize
24398
24399 @noindent
24400 If this rule is violated, that is if a unit with dynamic elaboration
24401 checks @code{with's} a unit that does not meet one of the above four
24402 criteria, then the binder (@code{gnatbind}) will issue a warning
24403 similar to that in the following example:
24404
24405 @smallexample
24406 warning: "x.ads" has dynamic elaboration checks and with's
24407 warning:   "y.ads" which has static elaboration checks
24408 @end smallexample
24409
24410 @noindent
24411 These warnings indicate that the rule has been violated, and that as a result
24412 elaboration checks may be missed in the resulting executable file.
24413 This warning may be suppressed using the @option{-ws} binder switch
24414 in the usual manner.
24415
24416 One useful application of this mixing rule is in the case of a subsystem
24417 which does not itself @code{with} units from the remainder of the
24418 application. In this case, the entire subsystem can be compiled with
24419 dynamic checks to resolve a circularity in the subsystem, while
24420 allowing the main application that uses this subsystem to be compiled
24421 using the more reliable default static model.
24422
24423 @node What to Do If the Default Elaboration Behavior Fails
24424 @section What to Do If the Default Elaboration Behavior Fails
24425
24426 @noindent
24427 If the binder cannot find an acceptable order, it outputs detailed
24428 diagnostics. For example:
24429 @smallexample
24430 @group
24431 @iftex
24432 @leftskip=0cm
24433 @end iftex
24434 error: elaboration circularity detected
24435 info:   "proc (body)" must be elaborated before "pack (body)"
24436 info:     reason: Elaborate_All probably needed in unit "pack (body)"
24437 info:     recompile "pack (body)" with -gnatwl
24438 info:                             for full details
24439 info:       "proc (body)"
24440 info:         is needed by its spec:
24441 info:       "proc (spec)"
24442 info:         which is withed by:
24443 info:       "pack (body)"
24444 info:  "pack (body)" must be elaborated before "proc (body)"
24445 info:     reason: pragma Elaborate in unit "proc (body)"
24446 @end group
24447
24448 @end smallexample
24449
24450 @noindent
24451 In this case we have a cycle that the binder cannot break. On the one
24452 hand, there is an explicit pragma Elaborate in @code{proc} for
24453 @code{pack}. This means that the body of @code{pack} must be elaborated
24454 before the body of @code{proc}. On the other hand, there is elaboration
24455 code in @code{pack} that calls a subprogram in @code{proc}. This means
24456 that for maximum safety, there should really be a pragma
24457 Elaborate_All in @code{pack} for @code{proc} which would require that
24458 the body of @code{proc} be elaborated before the body of
24459 @code{pack}. Clearly both requirements cannot be satisfied.
24460 Faced with a circularity of this kind, you have three different options.
24461
24462 @table @asis
24463 @item Fix the program
24464 The most desirable option from the point of view of long-term maintenance
24465 is to rearrange the program so that the elaboration problems are avoided.
24466 One useful technique is to place the elaboration code into separate
24467 child packages. Another is to move some of the initialization code to
24468 explicitly called subprograms, where the program controls the order
24469 of initialization explicitly. Although this is the most desirable option,
24470 it may be impractical and involve too much modification, especially in
24471 the case of complex legacy code.
24472
24473 @item Perform dynamic checks
24474 If the compilations are done using the
24475 @option{-gnatE}
24476 (dynamic elaboration check) switch, then GNAT behaves in a quite different
24477 manner. Dynamic checks are generated for all calls that could possibly result
24478 in raising an exception. With this switch, the compiler does not generate
24479 implicit @code{Elaborate} or @code{Elaborate_All} pragmas. The behavior then is
24480 exactly as specified in the @cite{Ada Reference Manual}.
24481 The binder will generate
24482 an executable program that may or may not raise @code{Program_Error}, and then
24483 it is the programmer's job to ensure that it does not raise an exception. Note
24484 that it is important to compile all units with the switch, it cannot be used
24485 selectively.
24486
24487 @item Suppress checks
24488 The drawback of dynamic checks is that they generate a
24489 significant overhead at run time, both in space and time. If you
24490 are absolutely sure that your program cannot raise any elaboration
24491 exceptions, and you still want to use the dynamic elaboration model,
24492 then you can use the configuration pragma
24493 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
24494 example this pragma could be placed in the @file{gnat.adc} file.
24495
24496 @item Suppress checks selectively
24497 When you know that certain calls or instantiations in elaboration code cannot
24498 possibly lead to an elaboration error, and the binder nevertheless complains
24499 about implicit @code{Elaborate} and @code{Elaborate_All} pragmas that lead to
24500 elaboration circularities, it is possible to remove those warnings locally and
24501 obtain a program that will bind. Clearly this can be unsafe, and it is the
24502 responsibility of the programmer to make sure that the resulting program has no
24503 elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can be
24504 used with different granularity to suppress warnings and break elaboration
24505 circularities:
24506
24507 @itemize @bullet
24508 @item
24509 Place the pragma that names the called subprogram in the declarative part
24510 that contains the call.
24511
24512 @item
24513 Place the pragma in the declarative part, without naming an entity. This
24514 disables warnings on all calls in the corresponding  declarative region.
24515
24516 @item
24517 Place the pragma in the package spec that declares the called subprogram,
24518 and name the subprogram. This disables warnings on all elaboration calls to
24519 that subprogram.
24520
24521 @item
24522 Place the pragma in the package spec that declares the called subprogram,
24523 without naming any entity. This disables warnings on all elaboration calls to
24524 all subprograms declared in this spec.
24525
24526 @item Use Pragma Elaborate
24527 As previously described in section @xref{Treatment of Pragma Elaborate},
24528 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
24529 that no elaboration checks are required on calls to the designated unit.
24530 There may be cases in which the caller knows that no transitive calls
24531 can occur, so that a @code{pragma Elaborate} will be sufficient in a
24532 case where @code{pragma Elaborate_All} would cause a circularity.
24533 @end itemize
24534
24535 @noindent
24536 These five cases are listed in order of decreasing safety, and therefore
24537 require increasing programmer care in their application. Consider the
24538 following program:
24539
24540 @smallexample @c adanocomment
24541 package Pack1 is
24542   function F1 return Integer;
24543   X1 : Integer;
24544 end Pack1;
24545
24546 package Pack2 is
24547   function F2 return Integer;
24548   function Pure (x : integer) return integer;
24549   --  pragma Suppress (Elaboration_Check, On => Pure);  -- (3)
24550   --  pragma Suppress (Elaboration_Check);              -- (4)
24551 end Pack2;
24552
24553 with Pack2;
24554 package body Pack1 is
24555   function F1 return Integer is
24556   begin
24557     return 100;
24558   end F1;
24559   Val : integer := Pack2.Pure (11);    --  Elab. call (1)
24560 begin
24561   declare
24562     --  pragma Suppress(Elaboration_Check, Pack2.F2);   -- (1)
24563     --  pragma Suppress(Elaboration_Check);             -- (2)
24564   begin
24565     X1 := Pack2.F2 + 1;                --  Elab. call (2)
24566   end;
24567 end Pack1;
24568
24569 with Pack1;
24570 package body Pack2 is
24571   function F2 return Integer is
24572   begin
24573      return Pack1.F1;
24574   end F2;
24575   function Pure (x : integer) return integer is
24576   begin
24577      return x ** 3 - 3 * x;
24578   end;
24579 end Pack2;
24580
24581 with Pack1, Ada.Text_IO;
24582 procedure Proc3 is
24583 begin
24584   Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
24585 end Proc3;
24586 @end smallexample
24587 In the absence of any pragmas, an attempt to bind this program produces
24588 the following diagnostics:
24589 @smallexample
24590 @group
24591 @iftex
24592 @leftskip=.5cm
24593 @end iftex
24594 error: elaboration circularity detected
24595 info:    "pack1 (body)" must be elaborated before "pack1 (body)"
24596 info:       reason: Elaborate_All probably needed in unit "pack1 (body)"
24597 info:       recompile "pack1 (body)" with -gnatwl for full details
24598 info:          "pack1 (body)"
24599 info:             must be elaborated along with its spec:
24600 info:          "pack1 (spec)"
24601 info:             which is withed by:
24602 info:          "pack2 (body)"
24603 info:             which must be elaborated along with its spec:
24604 info:          "pack2 (spec)"
24605 info:             which is withed by:
24606 info:          "pack1 (body)"
24607 @end group
24608 @end smallexample
24609 The sources of the circularity are the two calls to @code{Pack2.Pure} and
24610 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
24611 F2 is safe, even though F2 calls F1, because the call appears after the
24612 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
24613 remove the warning on the call. It is also possible to use pragma (2)
24614 because there are no other potentially unsafe calls in the block.
24615
24616 @noindent
24617 The call to @code{Pure} is safe because this function does not depend on the
24618 state of @code{Pack2}. Therefore any call to this function is safe, and it
24619 is correct to place pragma (3) in the corresponding package spec.
24620
24621 @noindent
24622 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
24623 warnings on all calls to functions declared therein. Note that this is not
24624 necessarily safe, and requires more detailed examination of the subprogram
24625 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
24626 be already elaborated.
24627 @end table
24628
24629 @noindent
24630 It is hard to generalize on which of these four approaches should be
24631 taken. Obviously if it is possible to fix the program so that the default
24632 treatment works, this is preferable, but this may not always be practical.
24633 It is certainly simple enough to use
24634 @option{-gnatE}
24635 but the danger in this case is that, even if the GNAT binder
24636 finds a correct elaboration order, it may not always do so,
24637 and certainly a binder from another Ada compiler might not. A
24638 combination of testing and analysis (for which the warnings generated
24639 with the
24640 @option{-gnatwl}
24641 switch can be useful) must be used to ensure that the program is free
24642 of errors. One switch that is useful in this testing is the
24643 @option{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
24644 switch for
24645 @code{gnatbind}.
24646 Normally the binder tries to find an order that has the best chance
24647 of avoiding elaboration problems. However, if this switch is used, the binder
24648 plays a devil's advocate role, and tries to choose the order that
24649 has the best chance of failing. If your program works even with this
24650 switch, then it has a better chance of being error free, but this is still
24651 not a guarantee.
24652
24653 For an example of this approach in action, consider the C-tests (executable
24654 tests) from the ACVC suite. If these are compiled and run with the default
24655 treatment, then all but one of them succeed without generating any error
24656 diagnostics from the binder. However, there is one test that fails, and
24657 this is not surprising, because the whole point of this test is to ensure
24658 that the compiler can handle cases where it is impossible to determine
24659 a correct order statically, and it checks that an exception is indeed
24660 raised at run time.
24661
24662 This one test must be compiled and run using the
24663 @option{-gnatE}
24664 switch, and then it passes. Alternatively, the entire suite can
24665 be run using this switch. It is never wrong to run with the dynamic
24666 elaboration switch if your code is correct, and we assume that the
24667 C-tests are indeed correct (it is less efficient, but efficiency is
24668 not a factor in running the ACVC tests.)
24669
24670 @node Elaboration for Access-to-Subprogram Values
24671 @section Elaboration for Access-to-Subprogram Values
24672 @cindex Access-to-subprogram
24673
24674 @noindent
24675 Access-to-subprogram types (introduced in Ada 95) complicate
24676 the handling of elaboration. The trouble is that it becomes
24677 impossible to tell at compile time which procedure
24678 is being called. This means that it is not possible for the binder
24679 to analyze the elaboration requirements in this case.
24680
24681 If at the point at which the access value is created
24682 (i.e., the evaluation of @code{P'Access} for a subprogram @code{P}),
24683 the body of the subprogram is
24684 known to have been elaborated, then the access value is safe, and its use
24685 does not require a check. This may be achieved by appropriate arrangement
24686 of the order of declarations if the subprogram is in the current unit,
24687 or, if the subprogram is in another unit, by using pragma
24688 @code{Pure}, @code{Preelaborate}, or @code{Elaborate_Body}
24689 on the referenced unit.
24690
24691 If the referenced body is not known to have been elaborated at the point
24692 the access value is created, then any use of the access value must do a
24693 dynamic check, and this dynamic check will fail and raise a
24694 @code{Program_Error} exception if the body has not been elaborated yet.
24695 GNAT will generate the necessary checks, and in addition, if the
24696 @option{-gnatwl}
24697 switch is set, will generate warnings that such checks are required.
24698
24699 The use of dynamic dispatching for tagged types similarly generates
24700 a requirement for dynamic checks, and premature calls to any primitive
24701 operation of a tagged type before the body of the operation has been
24702 elaborated, will result in the raising of @code{Program_Error}.
24703
24704 @node Summary of Procedures for Elaboration Control
24705 @section Summary of Procedures for Elaboration Control
24706 @cindex Elaboration control
24707
24708 @noindent
24709 First, compile your program with the default options, using none of
24710 the special elaboration control switches. If the binder successfully
24711 binds your program, then you can be confident that, apart from issues
24712 raised by the use of access-to-subprogram types and dynamic dispatching,
24713 the program is free of elaboration errors. If it is important that the
24714 program be portable, then use the
24715 @option{-gnatwl}
24716 switch to generate warnings about missing @code{Elaborate} or
24717 @code{Elaborate_All} pragmas, and supply the missing pragmas.
24718
24719 If the program fails to bind using the default static elaboration
24720 handling, then you can fix the program to eliminate the binder
24721 message, or recompile the entire program with the
24722 @option{-gnatE} switch to generate dynamic elaboration checks,
24723 and, if you are sure there really are no elaboration problems,
24724 use a global pragma @code{Suppress (Elaboration_Check)}.
24725
24726 @node Other Elaboration Order Considerations
24727 @section Other Elaboration Order Considerations
24728 @noindent
24729 This section has been entirely concerned with the issue of finding a valid
24730 elaboration order, as defined by the Ada Reference Manual. In a case
24731 where several elaboration orders are valid, the task is to find one
24732 of the possible valid elaboration orders (and the static model in GNAT
24733 will ensure that this is achieved).
24734
24735 The purpose of the elaboration rules in the Ada Reference Manual is to
24736 make sure that no entity is accessed before it has been elaborated. For
24737 a subprogram, this means that the spec and body must have been elaborated
24738 before the subprogram is called. For an object, this means that the object
24739 must have been elaborated before its value is read or written. A violation
24740 of either of these two requirements is an access before elaboration order,
24741 and this section has been all about avoiding such errors.
24742
24743 In the case where more than one order of elaboration is possible, in the
24744 sense that access before elaboration errors are avoided, then any one of
24745 the orders is ``correct'' in the sense that it meets the requirements of
24746 the Ada Reference Manual, and no such error occurs.
24747
24748 However, it may be the case for a given program, that there are
24749 constraints on the order of elaboration that come not from consideration
24750 of avoiding elaboration errors, but rather from extra-lingual logic
24751 requirements. Consider this example:
24752
24753 @smallexample @c ada
24754 with Init_Constants;
24755 package Constants is
24756    X : Integer := 0;
24757    Y : Integer := 0;
24758 end Constants;
24759
24760 package Init_Constants is
24761    procedure P; -- require a body
24762 end Init_Constants;
24763
24764 with Constants;
24765 package body Init_Constants is
24766    procedure P is begin null; end;
24767 begin
24768    Constants.X := 3;
24769    Constants.Y := 4;
24770 end Init_Constants;
24771
24772 with Constants;
24773 package Calc is
24774    Z : Integer := Constants.X + Constants.Y;
24775 end Calc;
24776
24777 with Calc;
24778 with Text_IO; use Text_IO;
24779 procedure Main is
24780 begin
24781    Put_Line (Calc.Z'Img);
24782 end Main;
24783 @end smallexample
24784
24785 @noindent
24786 In this example, there is more than one valid order of elaboration. For
24787 example both the following are correct orders:
24788
24789 @smallexample
24790 Init_Constants spec
24791 Constants spec
24792 Calc spec
24793 Init_Constants body
24794 Main body
24795
24796   and
24797
24798 Init_Constants spec
24799 Init_Constants body
24800 Constants spec
24801 Calc spec
24802 Main body
24803 @end smallexample
24804
24805 @noindent
24806 There is no language rule to prefer one or the other, both are correct
24807 from an order of elaboration point of view. But the programmatic effects
24808 of the two orders are very different. In the first, the elaboration routine
24809 of @code{Calc} initializes @code{Z} to zero, and then the main program
24810 runs with this value of zero. But in the second order, the elaboration
24811 routine of @code{Calc} runs after the body of Init_Constants has set
24812 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
24813 runs.
24814
24815 One could perhaps by applying pretty clever non-artificial intelligence
24816 to the situation guess that it is more likely that the second order of
24817 elaboration is the one desired, but there is no formal linguistic reason
24818 to prefer one over the other. In fact in this particular case, GNAT will
24819 prefer the second order, because of the rule that bodies are elaborated
24820 as soon as possible, but it's just luck that this is what was wanted
24821 (if indeed the second order was preferred).
24822
24823 If the program cares about the order of elaboration routines in a case like
24824 this, it is important to specify the order required. In this particular
24825 case, that could have been achieved by adding to the spec of Calc:
24826
24827 @smallexample @c ada
24828 pragma Elaborate_All (Constants);
24829 @end smallexample
24830
24831 @noindent
24832 which requires that the body (if any) and spec of @code{Constants},
24833 as well as the body and spec of any unit @code{with}'ed by
24834 @code{Constants} be elaborated before @code{Calc} is elaborated.
24835
24836 Clearly no automatic method can always guess which alternative you require,
24837 and if you are working with legacy code that had constraints of this kind
24838 which were not properly specified by adding @code{Elaborate} or
24839 @code{Elaborate_All} pragmas, then indeed it is possible that two different
24840 compilers can choose different orders.
24841
24842 However, GNAT does attempt to diagnose the common situation where there
24843 are uninitialized variables in the visible part of a package spec, and the
24844 corresponding package body has an elaboration block that directly or
24845 indirectly initialized one or more of these variables. This is the situation
24846 in which a pragma Elaborate_Body is usually desirable, and GNAT will generate
24847 a warning that suggests this addition if it detects this situation.
24848
24849 The @code{gnatbind}
24850 @option{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
24851 out problems. This switch causes bodies to be elaborated as late as possible
24852 instead of as early as possible. In the example above, it would have forced
24853 the choice of the first elaboration order. If you get different results
24854 when using this switch, and particularly if one set of results is right,
24855 and one is wrong as far as you are concerned, it shows that you have some
24856 missing @code{Elaborate} pragmas. For the example above, we have the
24857 following output:
24858
24859 @smallexample
24860 gnatmake -f -q main
24861 main
24862  7
24863 gnatmake -f -q main -bargs -p
24864 main
24865  0
24866 @end smallexample
24867
24868 @noindent
24869 It is of course quite unlikely that both these results are correct, so
24870 it is up to you in a case like this to investigate the source of the
24871 difference, by looking at the two elaboration orders that are chosen,
24872 and figuring out which is correct, and then adding the necessary
24873 @code{Elaborate} or @code{Elaborate_All} pragmas to ensure the desired order.
24874
24875
24876
24877 @c *******************************
24878 @node Conditional Compilation
24879 @appendix Conditional Compilation
24880 @c *******************************
24881 @cindex Conditional compilation
24882
24883 @noindent
24884 It is often necessary to arrange for a single source program
24885 to serve multiple purposes, where it is compiled in different
24886 ways to achieve these different goals. Some examples of the
24887 need for this feature are
24888
24889 @itemize @bullet
24890 @item  Adapting a program to a different hardware environment
24891 @item  Adapting a program to a different target architecture
24892 @item  Turning debugging features on and off
24893 @item  Arranging for a program to compile with different compilers
24894 @end itemize
24895
24896 @noindent
24897 In C, or C++, the typical approach would be to use the preprocessor
24898 that is defined as part of the language. The Ada language does not
24899 contain such a feature. This is not an oversight, but rather a very
24900 deliberate design decision, based on the experience that overuse of
24901 the preprocessing features in C and C++ can result in programs that
24902 are extremely difficult to maintain. For example, if we have ten
24903 switches that can be on or off, this means that there are a thousand
24904 separate programs, any one of which might not even be syntactically
24905 correct, and even if syntactically correct, the resulting program
24906 might not work correctly. Testing all combinations can quickly become
24907 impossible.
24908
24909 Nevertheless, the need to tailor programs certainly exists, and in
24910 this Appendix we will discuss how this can
24911 be achieved using Ada in general, and GNAT in particular.
24912
24913 @menu
24914 * Use of Boolean Constants::
24915 * Debugging - A Special Case::
24916 * Conditionalizing Declarations::
24917 * Use of Alternative Implementations::
24918 * Preprocessing::
24919 @end menu
24920
24921 @node Use of Boolean Constants
24922 @section Use of Boolean Constants
24923
24924 @noindent
24925 In the case where the difference is simply which code
24926 sequence is executed, the cleanest solution is to use Boolean
24927 constants to control which code is executed.
24928
24929 @smallexample @c ada
24930 @group
24931 FP_Initialize_Required : constant Boolean := True;
24932 @dots{}
24933 if FP_Initialize_Required then
24934 @dots{}
24935 end if;
24936 @end group
24937 @end smallexample
24938
24939 @noindent
24940 Not only will the code inside the @code{if} statement not be executed if
24941 the constant Boolean is @code{False}, but it will also be completely
24942 deleted from the program.
24943 However, the code is only deleted after the @code{if} statement
24944 has been checked for syntactic and semantic correctness.
24945 (In contrast, with preprocessors the code is deleted before the
24946 compiler ever gets to see it, so it is not checked until the switch
24947 is turned on.)
24948 @cindex Preprocessors (contrasted with conditional compilation)
24949
24950 Typically the Boolean constants will be in a separate package,
24951 something like:
24952
24953 @smallexample @c ada
24954 @group
24955 package Config is
24956    FP_Initialize_Required : constant Boolean := True;
24957    Reset_Available        : constant Boolean := False;
24958    @dots{}
24959 end Config;
24960 @end group
24961 @end smallexample
24962
24963 @noindent
24964 The @code{Config} package exists in multiple forms for the various targets,
24965 with an appropriate script selecting the version of @code{Config} needed.
24966 Then any other unit requiring conditional compilation can do a @code{with}
24967 of @code{Config} to make the constants visible.
24968
24969
24970 @node Debugging - A Special Case
24971 @section Debugging - A Special Case
24972
24973 @noindent
24974 A common use of conditional code is to execute statements (for example
24975 dynamic checks, or output of intermediate results) under control of a
24976 debug switch, so that the debugging behavior can be turned on and off.
24977 This can be done using a Boolean constant to control whether the code
24978 is active:
24979
24980 @smallexample @c ada
24981 @group
24982 if Debugging then
24983    Put_Line ("got to the first stage!");
24984 end if;
24985 @end group
24986 @end smallexample
24987
24988 @noindent
24989 or
24990
24991 @smallexample @c ada
24992 @group
24993 if Debugging and then Temperature > 999.0 then
24994    raise Temperature_Crazy;
24995 end if;
24996 @end group
24997 @end smallexample
24998
24999 @noindent
25000 Since this is a common case, there are special features to deal with
25001 this in a convenient manner. For the case of tests, Ada 2005 has added
25002 a pragma @code{Assert} that can be used for such tests. This pragma is modeled
25003 @cindex pragma @code{Assert}
25004 on the @code{Assert} pragma that has always been available in GNAT, so this
25005 feature may be used with GNAT even if you are not using Ada 2005 features.
25006 The use of pragma @code{Assert} is described in
25007 @ref{Pragma Assert,,, gnat_rm, GNAT Reference Manual}, but as an
25008 example, the last test could be written:
25009
25010 @smallexample @c ada
25011 pragma Assert (Temperature <= 999.0, "Temperature Crazy");
25012 @end smallexample
25013
25014 @noindent
25015 or simply
25016
25017 @smallexample @c ada
25018 pragma Assert (Temperature <= 999.0);
25019 @end smallexample
25020
25021 @noindent
25022 In both cases, if assertions are active and the temperature is excessive,
25023 the exception @code{Assert_Failure} will be raised, with the given string in
25024 the first case or a string indicating the location of the pragma in the second
25025 case used as the exception message.
25026
25027 You can turn assertions on and off by using the @code{Assertion_Policy}
25028 pragma.
25029 @cindex pragma @code{Assertion_Policy}
25030 This is an Ada 2005 pragma which is implemented in all modes by
25031 GNAT, but only in the latest versions of GNAT which include Ada 2005
25032 capability. Alternatively, you can use the @option{-gnata} switch
25033 @cindex @option{-gnata} switch
25034 to enable assertions from the command line (this is recognized by all versions
25035 of GNAT).
25036
25037 For the example above with the @code{Put_Line}, the GNAT-specific pragma
25038 @code{Debug} can be used:
25039 @cindex pragma @code{Debug}
25040
25041 @smallexample @c ada
25042 pragma Debug (Put_Line ("got to the first stage!"));
25043 @end smallexample
25044
25045 @noindent
25046 If debug pragmas are enabled, the argument, which must be of the form of
25047 a procedure call, is executed (in this case, @code{Put_Line} will be called).
25048 Only one call can be present, but of course a special debugging procedure
25049 containing any code you like can be included in the program and then
25050 called in a pragma @code{Debug} argument as needed.
25051
25052 One advantage of pragma @code{Debug} over the @code{if Debugging then}
25053 construct is that pragma @code{Debug} can appear in declarative contexts,
25054 such as at the very beginning of a procedure, before local declarations have
25055 been elaborated.
25056
25057 Debug pragmas are enabled using either the @option{-gnata} switch that also
25058 controls assertions, or with a separate Debug_Policy pragma.
25059 @cindex pragma @code{Debug_Policy}
25060 The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
25061 in Ada 95 and Ada 83 programs as well), and is analogous to
25062 pragma @code{Assertion_Policy} to control assertions.
25063
25064 @code{Assertion_Policy} and @code{Debug_Policy} are configuration pragmas,
25065 and thus they can appear in @file{gnat.adc} if you are not using a
25066 project file, or in the file designated to contain configuration pragmas
25067 in a project file.
25068 They then apply to all subsequent compilations. In practice the use of
25069 the @option{-gnata} switch is often the most convenient method of controlling
25070 the status of these pragmas.
25071
25072 Note that a pragma is not a statement, so in contexts where a statement
25073 sequence is required, you can't just write a pragma on its own. You have
25074 to add a @code{null} statement.
25075
25076 @smallexample @c ada
25077 @group
25078 if @dots{} then
25079    @dots{} -- some statements
25080 else
25081    pragma Assert (Num_Cases < 10);
25082    null;
25083 end if;
25084 @end group
25085 @end smallexample
25086
25087
25088 @node Conditionalizing Declarations
25089 @section Conditionalizing Declarations
25090
25091 @noindent
25092 In some cases, it may be necessary to conditionalize declarations to meet
25093 different requirements. For example we might want a bit string whose length
25094 is set to meet some hardware message requirement.
25095
25096 In some cases, it may be possible to do this using declare blocks controlled
25097 by conditional constants:
25098
25099 @smallexample @c ada
25100 @group
25101 if Small_Machine then
25102    declare
25103       X : Bit_String (1 .. 10);
25104    begin
25105       @dots{}
25106    end;
25107 else
25108    declare
25109       X : Large_Bit_String (1 .. 1000);
25110    begin
25111       @dots{}
25112    end;
25113 end if;
25114 @end group
25115 @end smallexample
25116
25117 @noindent
25118 Note that in this approach, both declarations are analyzed by the
25119 compiler so this can only be used where both declarations are legal,
25120 even though one of them will not be used.
25121
25122 Another approach is to define integer constants, e.g.@: @code{Bits_Per_Word},
25123 or Boolean constants, e.g.@: @code{Little_Endian}, and then write declarations
25124 that are parameterized by these constants. For example
25125
25126 @smallexample @c ada
25127 @group
25128 for Rec use
25129   Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
25130 end record;
25131 @end group
25132 @end smallexample
25133
25134 @noindent
25135 If @code{Bits_Per_Word} is set to 32, this generates either
25136
25137 @smallexample @c ada
25138 @group
25139 for Rec use
25140   Field1 at 0 range 0 .. 32;
25141 end record;
25142 @end group
25143 @end smallexample
25144
25145 @noindent
25146 for the big endian case, or
25147
25148 @smallexample @c ada
25149 @group
25150 for Rec use record
25151   Field1 at 0 range 10 .. 32;
25152 end record;
25153 @end group
25154 @end smallexample
25155
25156 @noindent
25157 for the little endian case. Since a powerful subset of Ada expression
25158 notation is usable for creating static constants, clever use of this
25159 feature can often solve quite difficult problems in conditionalizing
25160 compilation (note incidentally that in Ada 95, the little endian
25161 constant was introduced as @code{System.Default_Bit_Order}, so you do not
25162 need to define this one yourself).
25163
25164
25165 @node Use of Alternative Implementations
25166 @section Use of Alternative Implementations
25167
25168 @noindent
25169 In some cases, none of the approaches described above are adequate. This
25170 can occur for example if the set of declarations required is radically
25171 different for two different configurations.
25172
25173 In this situation, the official Ada way of dealing with conditionalizing
25174 such code is to write separate units for the different cases. As long as
25175 this does not result in excessive duplication of code, this can be done
25176 without creating maintenance problems. The approach is to share common
25177 code as far as possible, and then isolate the code and declarations
25178 that are different. Subunits are often a convenient method for breaking
25179 out a piece of a unit that is to be conditionalized, with separate files
25180 for different versions of the subunit for different targets, where the
25181 build script selects the right one to give to the compiler.
25182 @cindex Subunits (and conditional compilation)
25183
25184 As an example, consider a situation where a new feature in Ada 2005
25185 allows something to be done in a really nice way. But your code must be able
25186 to compile with an Ada 95 compiler. Conceptually you want to say:
25187
25188 @smallexample @c ada
25189 @group
25190 if Ada_2005 then
25191    @dots{} neat Ada 2005 code
25192 else
25193    @dots{} not quite as neat Ada 95 code
25194 end if;
25195 @end group
25196 @end smallexample
25197
25198 @noindent
25199 where @code{Ada_2005} is a Boolean constant.
25200
25201 But this won't work when @code{Ada_2005} is set to @code{False},
25202 since the @code{then} clause will be illegal for an Ada 95 compiler.
25203 (Recall that although such unreachable code would eventually be deleted
25204 by the compiler, it still needs to be legal.  If it uses features
25205 introduced in Ada 2005, it will be illegal in Ada 95.)
25206
25207 So instead we write
25208
25209 @smallexample @c ada
25210 procedure Insert is separate;
25211 @end smallexample
25212
25213 @noindent
25214 Then we have two files for the subunit @code{Insert}, with the two sets of
25215 code.
25216 If the package containing this is called @code{File_Queries}, then we might
25217 have two files
25218
25219 @itemize @bullet
25220 @item    @file{file_queries-insert-2005.adb}
25221 @item    @file{file_queries-insert-95.adb}
25222 @end itemize
25223
25224 @noindent
25225 and the build script renames the appropriate file to
25226
25227 @smallexample
25228 file_queries-insert.adb
25229 @end smallexample
25230
25231 @noindent
25232 and then carries out the compilation.
25233
25234 This can also be done with project files' naming schemes. For example:
25235
25236 @smallexample @c project
25237 For Body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
25238 @end smallexample
25239
25240 @noindent
25241 Note also that with project files it is desirable to use a different extension
25242 than @file{ads} / @file{adb} for alternative versions. Otherwise a naming
25243 conflict may arise through another commonly used feature: to declare as part
25244 of the project a set of directories containing all the sources obeying the
25245 default naming scheme.
25246
25247 The use of alternative units is certainly feasible in all situations,
25248 and for example the Ada part of the GNAT run-time is conditionalized
25249 based on the target architecture using this approach. As a specific example,
25250 consider the implementation of the AST feature in VMS. There is one
25251 spec:
25252
25253 @smallexample
25254 s-asthan.ads
25255 @end smallexample
25256
25257 @noindent
25258 which is the same for all architectures, and three bodies:
25259
25260 @table @file
25261 @item    s-asthan.adb
25262 used for all non-VMS operating systems
25263 @item    s-asthan-vms-alpha.adb
25264 used for VMS on the Alpha
25265 @item    s-asthan-vms-ia64.adb
25266 used for VMS on the ia64
25267 @end table
25268
25269 @noindent
25270 The dummy version @file{s-asthan.adb} simply raises exceptions noting that
25271 this operating system feature is not available, and the two remaining
25272 versions interface with the corresponding versions of VMS to provide
25273 VMS-compatible AST handling. The GNAT build script knows the architecture
25274 and operating system, and automatically selects the right version,
25275 renaming it if necessary to @file{s-asthan.adb} before the run-time build.
25276
25277 Another style for arranging alternative implementations is through Ada's
25278 access-to-subprogram facility.
25279 In case some functionality is to be conditionally included,
25280 you can declare an access-to-procedure variable @code{Ref} that is initialized
25281 to designate a ``do nothing'' procedure, and then invoke @code{Ref.all}
25282 when appropriate.
25283 In some library package, set @code{Ref} to @code{Proc'Access} for some
25284 procedure @code{Proc} that performs the relevant processing.
25285 The initialization only occurs if the library package is included in the
25286 program.
25287 The same idea can also be implemented using tagged types and dispatching
25288 calls.
25289
25290
25291 @node Preprocessing
25292 @section Preprocessing
25293 @cindex Preprocessing
25294
25295 @noindent
25296 Although it is quite possible to conditionalize code without the use of
25297 C-style preprocessing, as described earlier in this section, it is
25298 nevertheless convenient in some cases to use the C approach. Moreover,
25299 older Ada compilers have often provided some preprocessing capability,
25300 so legacy code may depend on this approach, even though it is not
25301 standard.
25302
25303 To accommodate such use, GNAT provides a preprocessor (modeled to a large
25304 extent on the various preprocessors that have been used
25305 with legacy code on other compilers, to enable easier transition).
25306
25307 The preprocessor may be used in two separate modes. It can be used quite
25308 separately from the compiler, to generate a separate output source file
25309 that is then fed to the compiler as a separate step. This is the
25310 @code{gnatprep} utility, whose use is fully described in
25311 @ref{Preprocessing Using gnatprep}.
25312 @cindex @code{gnatprep}
25313
25314 The preprocessing language allows such constructs as
25315
25316 @smallexample
25317 @group
25318 #if DEBUG or PRIORITY > 4 then
25319    bunch of declarations
25320 #else
25321    completely different bunch of declarations
25322 #end if;
25323 @end group
25324 @end smallexample
25325
25326 @noindent
25327 The values of the symbols @code{DEBUG} and @code{PRIORITY} can be
25328 defined either on the command line or in a separate file.
25329
25330 The other way of running the preprocessor is even closer to the C style and
25331 often more convenient. In this approach the preprocessing is integrated into
25332 the compilation process. The compiler is fed the preprocessor input which
25333 includes @code{#if} lines etc, and then the compiler carries out the
25334 preprocessing internally and processes the resulting output.
25335 For more details on this approach, see @ref{Integrated Preprocessing}.
25336
25337
25338 @c *******************************
25339 @node Inline Assembler
25340 @appendix Inline Assembler
25341 @c *******************************
25342
25343 @noindent
25344 If you need to write low-level software that interacts directly
25345 with the hardware, Ada provides two ways to incorporate assembly
25346 language code into your program.  First, you can import and invoke
25347 external routines written in assembly language, an Ada feature fully
25348 supported by GNAT@.  However, for small sections of code it may be simpler
25349 or more efficient to include assembly language statements directly
25350 in your Ada source program, using the facilities of the implementation-defined
25351 package @code{System.Machine_Code}, which incorporates the gcc
25352 Inline Assembler.  The Inline Assembler approach offers a number of advantages,
25353 including the following:
25354
25355 @itemize @bullet
25356 @item No need to use non-Ada tools
25357 @item Consistent interface over different targets
25358 @item Automatic usage of the proper calling conventions
25359 @item Access to Ada constants and variables
25360 @item Definition of intrinsic routines
25361 @item Possibility of inlining a subprogram comprising assembler code
25362 @item Code optimizer can take Inline Assembler code into account
25363 @end itemize
25364
25365 This chapter presents a series of examples to show you how to use
25366 the Inline Assembler.  Although it focuses on the Intel x86,
25367 the general approach applies also to other processors.
25368 It is assumed that you are familiar with Ada
25369 and with assembly language programming.
25370
25371 @menu
25372 * Basic Assembler Syntax::
25373 * A Simple Example of Inline Assembler::
25374 * Output Variables in Inline Assembler::
25375 * Input Variables in Inline Assembler::
25376 * Inlining Inline Assembler Code::
25377 * Other Asm Functionality::
25378 @end menu
25379
25380 @c ---------------------------------------------------------------------------
25381 @node Basic Assembler Syntax
25382 @section Basic Assembler Syntax
25383
25384 @noindent
25385 The assembler used by GNAT and gcc is based not on the Intel assembly
25386 language, but rather on a language that descends from the AT&T Unix
25387 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
25388 The following table summarizes the main features of @emph{as} syntax
25389 and points out the differences from the Intel conventions.
25390 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
25391 pre-processor) documentation for further information.
25392
25393 @table @asis
25394 @item Register names
25395 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
25396 @*
25397 Intel: No extra punctuation; for example @code{eax}
25398
25399 @item Immediate operand
25400 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
25401 @*
25402 Intel: No extra punctuation; for example @code{4}
25403
25404 @item Address
25405 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
25406 @*
25407 Intel: No extra punctuation; for example @code{loc}
25408
25409 @item Memory contents
25410 gcc / @emph{as}: No extra punctuation; for example @code{loc}
25411 @*
25412 Intel: Square brackets; for example @code{[loc]}
25413
25414 @item Register contents
25415 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
25416 @*
25417 Intel: Square brackets; for example @code{[eax]}
25418
25419 @item Hexadecimal numbers
25420 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
25421 @*
25422 Intel: Trailing ``h''; for example @code{A0h}
25423
25424 @item Operand size
25425 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
25426 a 16-bit word
25427 @*
25428 Intel: Implicit, deduced by assembler; for example @code{mov}
25429
25430 @item Instruction repetition
25431 gcc / @emph{as}: Split into two lines; for example
25432 @*
25433 @code{rep}
25434 @*
25435 @code{stosl}
25436 @*
25437 Intel: Keep on one line; for example @code{rep stosl}
25438
25439 @item Order of operands
25440 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
25441 @*
25442 Intel: Destination first; for example @code{mov eax, 4}
25443 @end table
25444
25445 @c ---------------------------------------------------------------------------
25446 @node A Simple Example of Inline Assembler
25447 @section A Simple Example of Inline Assembler
25448
25449 @noindent
25450 The following example will generate a single assembly language statement,
25451 @code{nop}, which does nothing.  Despite its lack of run-time effect,
25452 the example will be useful in illustrating the basics of
25453 the Inline Assembler facility.
25454
25455 @smallexample @c ada
25456 @group
25457 with System.Machine_Code; use System.Machine_Code;
25458 procedure Nothing is
25459 begin
25460    Asm ("nop");
25461 end Nothing;
25462 @end group
25463 @end smallexample
25464
25465 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
25466 here it takes one parameter, a @emph{template string} that must be a static
25467 expression and that will form the generated instruction.
25468 @code{Asm} may be regarded as a compile-time procedure that parses
25469 the template string and additional parameters (none here),
25470 from which it generates a sequence of assembly language instructions.
25471
25472 The examples in this chapter will illustrate several of the forms
25473 for invoking @code{Asm}; a complete specification of the syntax
25474 is found in @ref{Machine Code Insertions,,, gnat_rm, GNAT Reference
25475 Manual}.
25476
25477 Under the standard GNAT conventions, the @code{Nothing} procedure
25478 should be in a file named @file{nothing.adb}.
25479 You can build the executable in the usual way:
25480 @smallexample
25481 gnatmake nothing
25482 @end smallexample
25483 However, the interesting aspect of this example is not its run-time behavior
25484 but rather the generated assembly code.
25485 To see this output, invoke the compiler as follows:
25486 @smallexample
25487    gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
25488 @end smallexample
25489 where the options are:
25490
25491 @table @code
25492 @item -c
25493 compile only (no bind or link)
25494 @item -S
25495 generate assembler listing
25496 @item -fomit-frame-pointer
25497 do not set up separate stack frames
25498 @item -gnatp
25499 do not add runtime checks
25500 @end table
25501
25502 This gives a human-readable assembler version of the code. The resulting
25503 file will have the same name as the Ada source file, but with a @code{.s}
25504 extension. In our example, the file @file{nothing.s} has the following
25505 contents:
25506
25507 @smallexample
25508 @group
25509 .file "nothing.adb"
25510 gcc2_compiled.:
25511 ___gnu_compiled_ada:
25512 .text
25513    .align 4
25514 .globl __ada_nothing
25515 __ada_nothing:
25516 #APP
25517    nop
25518 #NO_APP
25519    jmp L1
25520    .align 2,0x90
25521 L1:
25522    ret
25523 @end group
25524 @end smallexample
25525
25526 The assembly code you included is clearly indicated by
25527 the compiler, between the @code{#APP} and @code{#NO_APP}
25528 delimiters. The character before the 'APP' and 'NOAPP'
25529 can differ on different targets. For example, GNU/Linux uses '#APP' while
25530 on NT you will see '/APP'.
25531
25532 If you make a mistake in your assembler code (such as using the
25533 wrong size modifier, or using a wrong operand for the instruction) GNAT
25534 will report this error in a temporary file, which will be deleted when
25535 the compilation is finished.  Generating an assembler file will help
25536 in such cases, since you can assemble this file separately using the
25537 @emph{as} assembler that comes with gcc.
25538
25539 Assembling the file using the command
25540
25541 @smallexample
25542 as @file{nothing.s}
25543 @end smallexample
25544 @noindent
25545 will give you error messages whose lines correspond to the assembler
25546 input file, so you can easily find and correct any mistakes you made.
25547 If there are no errors, @emph{as} will generate an object file
25548 @file{nothing.out}.
25549
25550 @c ---------------------------------------------------------------------------
25551 @node Output Variables in Inline Assembler
25552 @section Output Variables in Inline Assembler
25553
25554 @noindent
25555 The examples in this section, showing how to access the processor flags,
25556 illustrate how to specify the destination operands for assembly language
25557 statements.
25558
25559 @smallexample @c ada
25560 @group
25561 with Interfaces; use Interfaces;
25562 with Ada.Text_IO; use Ada.Text_IO;
25563 with System.Machine_Code; use System.Machine_Code;
25564 procedure Get_Flags is
25565    Flags : Unsigned_32;
25566    use ASCII;
25567 begin
25568    Asm ("pushfl"          & LF & HT & -- push flags on stack
25569         "popl %%eax"      & LF & HT & -- load eax with flags
25570         "movl %%eax, %0",             -- store flags in variable
25571         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25572    Put_Line ("Flags register:" & Flags'Img);
25573 end Get_Flags;
25574 @end group
25575 @end smallexample
25576
25577 In order to have a nicely aligned assembly listing, we have separated
25578 multiple assembler statements in the Asm template string with linefeed
25579 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
25580 The resulting section of the assembly output file is:
25581
25582 @smallexample
25583 @group
25584 #APP
25585    pushfl
25586    popl %eax
25587    movl %eax, -40(%ebp)
25588 #NO_APP
25589 @end group
25590 @end smallexample
25591
25592 It would have been legal to write the Asm invocation as:
25593
25594 @smallexample
25595 Asm ("pushfl popl %%eax movl %%eax, %0")
25596 @end smallexample
25597
25598 but in the generated assembler file, this would come out as:
25599
25600 @smallexample
25601 #APP
25602    pushfl popl %eax movl %eax, -40(%ebp)
25603 #NO_APP
25604 @end smallexample
25605
25606 which is not so convenient for the human reader.
25607
25608 We use Ada comments
25609 at the end of each line to explain what the assembler instructions
25610 actually do.  This is a useful convention.
25611
25612 When writing Inline Assembler instructions, you need to precede each register
25613 and variable name with a percent sign.  Since the assembler already requires
25614 a percent sign at the beginning of a register name, you need two consecutive
25615 percent signs for such names in the Asm template string, thus @code{%%eax}.
25616 In the generated assembly code, one of the percent signs will be stripped off.
25617
25618 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
25619 variables: operands you later define using @code{Input} or @code{Output}
25620 parameters to @code{Asm}.
25621 An output variable is illustrated in
25622 the third statement in the Asm template string:
25623 @smallexample
25624 movl %%eax, %0
25625 @end smallexample
25626 The intent is to store the contents of the eax register in a variable that can
25627 be accessed in Ada.  Simply writing @code{movl %%eax, Flags} would not
25628 necessarily work, since the compiler might optimize by using a register
25629 to hold Flags, and the expansion of the @code{movl} instruction would not be
25630 aware of this optimization.  The solution is not to store the result directly
25631 but rather to advise the compiler to choose the correct operand form;
25632 that is the purpose of the @code{%0} output variable.
25633
25634 Information about the output variable is supplied in the @code{Outputs}
25635 parameter to @code{Asm}:
25636 @smallexample
25637 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25638 @end smallexample
25639
25640 The output is defined by the @code{Asm_Output} attribute of the target type;
25641 the general format is
25642 @smallexample
25643 Type'Asm_Output (constraint_string, variable_name)
25644 @end smallexample
25645
25646 The constraint string directs the compiler how
25647 to store/access the associated variable.  In the example
25648 @smallexample
25649 Unsigned_32'Asm_Output ("=m", Flags);
25650 @end smallexample
25651 the @code{"m"} (memory) constraint tells the compiler that the variable
25652 @code{Flags} should be stored in a memory variable, thus preventing
25653 the optimizer from keeping it in a register.  In contrast,
25654 @smallexample
25655 Unsigned_32'Asm_Output ("=r", Flags);
25656 @end smallexample
25657 uses the @code{"r"} (register) constraint, telling the compiler to
25658 store the variable in a register.
25659
25660 If the constraint is preceded by the equal character (@strong{=}), it tells
25661 the compiler that the variable will be used to store data into it.
25662
25663 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
25664 allowing the optimizer to choose whatever it deems best.
25665
25666 There are a fairly large number of constraints, but the ones that are
25667 most useful (for the Intel x86 processor) are the following:
25668
25669 @table @code
25670 @item =
25671 output constraint
25672 @item g
25673 global (i.e.@: can be stored anywhere)
25674 @item m
25675 in memory
25676 @item I
25677 a constant
25678 @item a
25679 use eax
25680 @item b
25681 use ebx
25682 @item c
25683 use ecx
25684 @item d
25685 use edx
25686 @item S
25687 use esi
25688 @item D
25689 use edi
25690 @item r
25691 use one of eax, ebx, ecx or edx
25692 @item q
25693 use one of eax, ebx, ecx, edx, esi or edi
25694 @end table
25695
25696 The full set of constraints is described in the gcc and @emph{as}
25697 documentation; note that it is possible to combine certain constraints
25698 in one constraint string.
25699
25700 You specify the association of an output variable with an assembler operand
25701 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
25702 integer.  Thus in
25703 @smallexample @c ada
25704 @group
25705 Asm ("pushfl"          & LF & HT & -- push flags on stack
25706      "popl %%eax"      & LF & HT & -- load eax with flags
25707      "movl %%eax, %0",             -- store flags in variable
25708      Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25709 @end group
25710 @end smallexample
25711 @noindent
25712 @code{%0} will be replaced in the expanded code by the appropriate operand,
25713 whatever
25714 the compiler decided for the @code{Flags} variable.
25715
25716 In general, you may have any number of output variables:
25717 @itemize @bullet
25718 @item
25719 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
25720 @item
25721 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
25722 of @code{Asm_Output} attributes
25723 @end itemize
25724
25725 For example:
25726 @smallexample @c ada
25727 @group
25728 Asm ("movl %%eax, %0" & LF & HT &
25729      "movl %%ebx, %1" & LF & HT &
25730      "movl %%ecx, %2",
25731      Outputs => (Unsigned_32'Asm_Output ("=g", Var_A),   --  %0 = Var_A
25732                  Unsigned_32'Asm_Output ("=g", Var_B),   --  %1 = Var_B
25733                  Unsigned_32'Asm_Output ("=g", Var_C))); --  %2 = Var_C
25734 @end group
25735 @end smallexample
25736 @noindent
25737 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
25738 in the Ada program.
25739
25740 As a variation on the @code{Get_Flags} example, we can use the constraints
25741 string to direct the compiler to store the eax register into the @code{Flags}
25742 variable, instead of including the store instruction explicitly in the
25743 @code{Asm} template string:
25744
25745 @smallexample @c ada
25746 @group
25747 with Interfaces; use Interfaces;
25748 with Ada.Text_IO; use Ada.Text_IO;
25749 with System.Machine_Code; use System.Machine_Code;
25750 procedure Get_Flags_2 is
25751    Flags : Unsigned_32;
25752    use ASCII;
25753 begin
25754    Asm ("pushfl"      & LF & HT & -- push flags on stack
25755         "popl %%eax",             -- save flags in eax
25756         Outputs => Unsigned_32'Asm_Output ("=a", Flags));
25757    Put_Line ("Flags register:" & Flags'Img);
25758 end Get_Flags_2;
25759 @end group
25760 @end smallexample
25761
25762 @noindent
25763 The @code{"a"} constraint tells the compiler that the @code{Flags}
25764 variable will come from the eax register. Here is the resulting code:
25765
25766 @smallexample
25767 @group
25768 #APP
25769    pushfl
25770    popl %eax
25771 #NO_APP
25772    movl %eax,-40(%ebp)
25773 @end group
25774 @end smallexample
25775
25776 @noindent
25777 The compiler generated the store of eax into Flags after
25778 expanding the assembler code.
25779
25780 Actually, there was no need to pop the flags into the eax register;
25781 more simply, we could just pop the flags directly into the program variable:
25782
25783 @smallexample @c ada
25784 @group
25785 with Interfaces; use Interfaces;
25786 with Ada.Text_IO; use Ada.Text_IO;
25787 with System.Machine_Code; use System.Machine_Code;
25788 procedure Get_Flags_3 is
25789    Flags : Unsigned_32;
25790    use ASCII;
25791 begin
25792    Asm ("pushfl"  & LF & HT & -- push flags on stack
25793         "pop %0",             -- save flags in Flags
25794         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25795    Put_Line ("Flags register:" & Flags'Img);
25796 end Get_Flags_3;
25797 @end group
25798 @end smallexample
25799
25800 @c ---------------------------------------------------------------------------
25801 @node Input Variables in Inline Assembler
25802 @section Input Variables in Inline Assembler
25803
25804 @noindent
25805 The example in this section illustrates how to specify the source operands
25806 for assembly language statements.
25807 The program simply increments its input value by 1:
25808
25809 @smallexample @c ada
25810 @group
25811 with Interfaces; use Interfaces;
25812 with Ada.Text_IO; use Ada.Text_IO;
25813 with System.Machine_Code; use System.Machine_Code;
25814 procedure Increment is
25815
25816    function Incr (Value : Unsigned_32) return Unsigned_32 is
25817       Result : Unsigned_32;
25818    begin
25819       Asm ("incl %0",
25820            Inputs  => Unsigned_32'Asm_Input ("a", Value),
25821            Outputs => Unsigned_32'Asm_Output ("=a", Result));
25822       return Result;
25823    end Incr;
25824
25825    Value : Unsigned_32;
25826
25827 begin
25828    Value := 5;
25829    Put_Line ("Value before is" & Value'Img);
25830    Value := Incr (Value);
25831    Put_Line ("Value after is" & Value'Img);
25832 end Increment;
25833 @end group
25834 @end smallexample
25835
25836 The @code{Outputs} parameter to @code{Asm} specifies
25837 that the result will be in the eax register and that it is to be stored
25838 in the @code{Result} variable.
25839
25840 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
25841 but with an @code{Asm_Input} attribute.
25842 The @code{"="} constraint, indicating an output value, is not present.
25843
25844 You can have multiple input variables, in the same way that you can have more
25845 than one output variable.
25846
25847 The parameter count (%0, %1) etc, now starts at the first input
25848 statement, and continues with the output statements.
25849 When both parameters use the same variable, the
25850 compiler will treat them as the same %n operand, which is the case here.
25851
25852 Just as the @code{Outputs} parameter causes the register to be stored into the
25853 target variable after execution of the assembler statements, so does the
25854 @code{Inputs} parameter cause its variable to be loaded into the register
25855 before execution of the assembler statements.
25856
25857 Thus the effect of the @code{Asm} invocation is:
25858 @enumerate
25859 @item load the 32-bit value of @code{Value} into eax
25860 @item execute the @code{incl %eax} instruction
25861 @item store the contents of eax into the @code{Result} variable
25862 @end enumerate
25863
25864 The resulting assembler file (with @option{-O2} optimization) contains:
25865 @smallexample
25866 @group
25867 _increment__incr.1:
25868    subl $4,%esp
25869    movl 8(%esp),%eax
25870 #APP
25871    incl %eax
25872 #NO_APP
25873    movl %eax,%edx
25874    movl %ecx,(%esp)
25875    addl $4,%esp
25876    ret
25877 @end group
25878 @end smallexample
25879
25880 @c ---------------------------------------------------------------------------
25881 @node Inlining Inline Assembler Code
25882 @section Inlining Inline Assembler Code
25883
25884 @noindent
25885 For a short subprogram such as the @code{Incr} function in the previous
25886 section, the overhead of the call and return (creating / deleting the stack
25887 frame) can be significant, compared to the amount of code in the subprogram
25888 body.  A solution is to apply Ada's @code{Inline} pragma to the subprogram,
25889 which directs the compiler to expand invocations of the subprogram at the
25890 point(s) of call, instead of setting up a stack frame for out-of-line calls.
25891 Here is the resulting program:
25892
25893 @smallexample @c ada
25894 @group
25895 with Interfaces; use Interfaces;
25896 with Ada.Text_IO; use Ada.Text_IO;
25897 with System.Machine_Code; use System.Machine_Code;
25898 procedure Increment_2 is
25899
25900    function Incr (Value : Unsigned_32) return Unsigned_32 is
25901       Result : Unsigned_32;
25902    begin
25903       Asm ("incl %0",
25904            Inputs  => Unsigned_32'Asm_Input ("a", Value),
25905            Outputs => Unsigned_32'Asm_Output ("=a", Result));
25906       return Result;
25907    end Incr;
25908    pragma Inline (Increment);
25909
25910    Value : Unsigned_32;
25911
25912 begin
25913    Value := 5;
25914    Put_Line ("Value before is" & Value'Img);
25915    Value := Increment (Value);
25916    Put_Line ("Value after is" & Value'Img);
25917 end Increment_2;
25918 @end group
25919 @end smallexample
25920
25921 Compile the program with both optimization (@option{-O2}) and inlining
25922 (@option{-gnatn}) enabled.
25923
25924 The @code{Incr} function is still compiled as usual, but at the
25925 point in @code{Increment} where our function used to be called:
25926
25927 @smallexample
25928 @group
25929 pushl %edi
25930 call _increment__incr.1
25931 @end group
25932 @end smallexample
25933
25934 @noindent
25935 the code for the function body directly appears:
25936
25937 @smallexample
25938 @group
25939 movl %esi,%eax
25940 #APP
25941    incl %eax
25942 #NO_APP
25943    movl %eax,%edx
25944 @end group
25945 @end smallexample
25946
25947 @noindent
25948 thus saving the overhead of stack frame setup and an out-of-line call.
25949
25950 @c ---------------------------------------------------------------------------
25951 @node Other Asm Functionality
25952 @section Other @code{Asm} Functionality
25953
25954 @noindent
25955 This section describes two important parameters to the @code{Asm}
25956 procedure: @code{Clobber}, which identifies register usage;
25957 and @code{Volatile}, which inhibits unwanted optimizations.
25958
25959 @menu
25960 * The Clobber Parameter::
25961 * The Volatile Parameter::
25962 @end menu
25963
25964 @c ---------------------------------------------------------------------------
25965 @node The Clobber Parameter
25966 @subsection The @code{Clobber} Parameter
25967
25968 @noindent
25969 One of the dangers of intermixing assembly language and a compiled language
25970 such as Ada is that the compiler needs to be aware of which registers are
25971 being used by the assembly code.  In some cases, such as the earlier examples,
25972 the constraint string is sufficient to indicate register usage (e.g.,
25973 @code{"a"} for
25974 the eax register).  But more generally, the compiler needs an explicit
25975 identification of the registers that are used by the Inline Assembly
25976 statements.
25977
25978 Using a register that the compiler doesn't know about
25979 could be a side effect of an instruction (like @code{mull}
25980 storing its result in both eax and edx).
25981 It can also arise from explicit register usage in your
25982 assembly code; for example:
25983 @smallexample
25984 @group
25985 Asm ("movl %0, %%ebx" & LF & HT &
25986      "movl %%ebx, %1",
25987      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
25988      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out));
25989 @end group
25990 @end smallexample
25991 @noindent
25992 where the compiler (since it does not analyze the @code{Asm} template string)
25993 does not know you are using the ebx register.
25994
25995 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
25996 to identify the registers that will be used by your assembly code:
25997
25998 @smallexample
25999 @group
26000 Asm ("movl %0, %%ebx" & LF & HT &
26001      "movl %%ebx, %1",
26002      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
26003      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
26004      Clobber => "ebx");
26005 @end group
26006 @end smallexample
26007
26008 The Clobber parameter is a static string expression specifying the
26009 register(s) you are using.  Note that register names are @emph{not} prefixed
26010 by a percent sign. Also, if more than one register is used then their names
26011 are separated by commas; e.g., @code{"eax, ebx"}
26012
26013 The @code{Clobber} parameter has several additional uses:
26014 @enumerate
26015 @item Use ``register'' name @code{cc} to indicate that flags might have changed
26016 @item Use ``register'' name @code{memory} if you changed a memory location
26017 @end enumerate
26018
26019 @c ---------------------------------------------------------------------------
26020 @node The Volatile Parameter
26021 @subsection The @code{Volatile} Parameter
26022 @cindex Volatile parameter
26023
26024 @noindent
26025 Compiler optimizations in the presence of Inline Assembler may sometimes have
26026 unwanted effects.  For example, when an @code{Asm} invocation with an input
26027 variable is inside a loop, the compiler might move the loading of the input
26028 variable outside the loop, regarding it as a one-time initialization.
26029
26030 If this effect is not desired, you can disable such optimizations by setting
26031 the @code{Volatile} parameter to @code{True}; for example:
26032
26033 @smallexample @c ada
26034 @group
26035 Asm ("movl %0, %%ebx" & LF & HT &
26036      "movl %%ebx, %1",
26037      Inputs   => Unsigned_32'Asm_Input  ("g", Var_In),
26038      Outputs  => Unsigned_32'Asm_Output ("=g", Var_Out),
26039      Clobber  => "ebx",
26040      Volatile => True);
26041 @end group
26042 @end smallexample
26043
26044 By default, @code{Volatile} is set to @code{False} unless there is no
26045 @code{Outputs} parameter.
26046
26047 Although setting @code{Volatile} to @code{True} prevents unwanted
26048 optimizations, it will also disable other optimizations that might be
26049 important for efficiency. In general, you should set @code{Volatile}
26050 to @code{True} only if the compiler's optimizations have created
26051 problems.
26052 @c END OF INLINE ASSEMBLER CHAPTER
26053 @c ===============================
26054
26055 @c ***********************************
26056 @c * Compatibility and Porting Guide *
26057 @c ***********************************
26058 @node Compatibility and Porting Guide
26059 @appendix Compatibility and Porting Guide
26060
26061 @noindent
26062 This chapter describes the compatibility issues that may arise between
26063 GNAT and other Ada compilation systems (including those for Ada 83),
26064 and shows how GNAT can expedite porting
26065 applications developed in other Ada environments.
26066
26067 @menu
26068 * Compatibility with Ada 83::
26069 * Compatibility between Ada 95 and Ada 2005::
26070 * Implementation-dependent characteristics::
26071 * Compatibility with Other Ada Systems::
26072 * Representation Clauses::
26073 @ifclear vms
26074 @c Brief section is only in non-VMS version
26075 @c Full chapter is in VMS version
26076 * Compatibility with HP Ada 83::
26077 @end ifclear
26078 @ifset vms
26079 * Transitioning to 64-Bit GNAT for OpenVMS::
26080 @end ifset
26081 @end menu
26082
26083 @node Compatibility with Ada 83
26084 @section Compatibility with Ada 83
26085 @cindex Compatibility (between Ada 83 and Ada 95 / Ada 2005)
26086
26087 @noindent
26088 Ada 95 and Ada 2005 are highly upwards compatible with Ada 83.  In
26089 particular, the design intention was that the difficulties associated
26090 with moving from Ada 83 to Ada 95 or Ada 2005 should be no greater than those
26091 that occur when moving from one Ada 83 system to another.
26092
26093 However, there are a number of points at which there are minor
26094 incompatibilities.  The @cite{Ada 95 Annotated Reference Manual} contains
26095 full details of these issues,
26096 and should be consulted for a complete treatment.
26097 In practice the
26098 following subsections treat the most likely issues to be encountered.
26099
26100 @menu
26101 * Legal Ada 83 programs that are illegal in Ada 95::
26102 * More deterministic semantics::
26103 * Changed semantics::
26104 * Other language compatibility issues::
26105 @end menu
26106
26107 @node Legal Ada 83 programs that are illegal in Ada 95
26108 @subsection Legal Ada 83 programs that are illegal in Ada 95
26109
26110 Some legal Ada 83 programs are illegal (i.e., they will fail to compile) in
26111 Ada 95 and thus also in Ada 2005:
26112
26113 @table @emph
26114 @item Character literals
26115 Some uses of character literals are ambiguous.  Since Ada 95 has introduced
26116 @code{Wide_Character} as a new predefined character type, some uses of
26117 character literals that were legal in Ada 83 are illegal in Ada 95.
26118 For example:
26119 @smallexample @c ada
26120    for Char in 'A' .. 'Z' loop @dots{} end loop;
26121 @end smallexample
26122
26123 @noindent
26124 The problem is that @code{'A'} and @code{'Z'} could be from either
26125 @code{Character} or @code{Wide_Character}.  The simplest correction
26126 is to make the type explicit; e.g.:
26127 @smallexample @c ada
26128    for Char in Character range 'A' .. 'Z' loop @dots{} end loop;
26129 @end smallexample
26130
26131 @item New reserved words
26132 The identifiers @code{abstract}, @code{aliased}, @code{protected},
26133 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
26134 Existing Ada 83 code using any of these identifiers must be edited to
26135 use some alternative name.
26136
26137 @item Freezing rules
26138 The rules in Ada 95 are slightly different with regard to the point at
26139 which entities are frozen, and representation pragmas and clauses are
26140 not permitted past the freeze point.  This shows up most typically in
26141 the form of an error message complaining that a representation item
26142 appears too late, and the appropriate corrective action is to move
26143 the item nearer to the declaration of the entity to which it refers.
26144
26145 A particular case is that representation pragmas
26146 @ifset vms
26147 (including the
26148 extended HP Ada 83 compatibility pragmas such as @code{Export_Procedure})
26149 @end ifset
26150 cannot be applied to a subprogram body.  If necessary, a separate subprogram
26151 declaration must be introduced to which the pragma can be applied.
26152
26153 @item Optional bodies for library packages
26154 In Ada 83, a package that did not require a package body was nevertheless
26155 allowed to have one.  This lead to certain surprises in compiling large
26156 systems (situations in which the body could be unexpectedly ignored by the
26157 binder).  In Ada 95, if a package does not require a body then it is not
26158 permitted to have a body.  To fix this problem, simply remove a redundant
26159 body if it is empty, or, if it is non-empty, introduce a dummy declaration
26160 into the spec that makes the body required.  One approach is to add a private
26161 part to the package declaration (if necessary), and define a parameterless
26162 procedure called @code{Requires_Body}, which must then be given a dummy
26163 procedure body in the package body, which then becomes required.
26164 Another approach (assuming that this does not introduce elaboration
26165 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
26166 since one effect of this pragma is to require the presence of a package body.
26167
26168 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
26169 In Ada 95, the exception @code{Numeric_Error} is a renaming of
26170 @code{Constraint_Error}.
26171 This means that it is illegal to have separate exception handlers for
26172 the two exceptions.  The fix is simply to remove the handler for the
26173 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
26174 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
26175
26176 @item Indefinite subtypes in generics
26177 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
26178 as the actual for a generic formal private type, but then the instantiation
26179 would be illegal if there were any instances of declarations of variables
26180 of this type in the generic body.  In Ada 95, to avoid this clear violation
26181 of the methodological principle known as the ``contract model'',
26182 the generic declaration explicitly indicates whether
26183 or not such instantiations are permitted.  If a generic formal parameter
26184 has explicit unknown discriminants, indicated by using @code{(<>)} after the
26185 type name, then it can be instantiated with indefinite types, but no
26186 stand-alone variables can be declared of this type.  Any attempt to declare
26187 such a variable will result in an illegality at the time the generic is
26188 declared.  If the @code{(<>)} notation is not used, then it is illegal
26189 to instantiate the generic with an indefinite type.
26190 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
26191 It will show up as a compile time error, and
26192 the fix is usually simply to add the @code{(<>)} to the generic declaration.
26193 @end table
26194
26195 @node More deterministic semantics
26196 @subsection More deterministic semantics
26197
26198 @table @emph
26199 @item Conversions
26200 Conversions from real types to integer types round away from 0.  In Ada 83
26201 the conversion Integer(2.5) could deliver either 2 or 3 as its value.  This
26202 implementation freedom was intended to support unbiased rounding in
26203 statistical applications, but in practice it interfered with portability.
26204 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
26205 is required.  Numeric code may be affected by this change in semantics.
26206 Note, though, that this issue is no worse than already existed in Ada 83
26207 when porting code from one vendor to another.
26208
26209 @item Tasking
26210 The Real-Time Annex introduces a set of policies that define the behavior of
26211 features that were implementation dependent in Ada 83, such as the order in
26212 which open select branches are executed.
26213 @end table
26214
26215 @node Changed semantics
26216 @subsection Changed semantics
26217
26218 @noindent
26219 The worst kind of incompatibility is one where a program that is legal in
26220 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
26221 possible in Ada 83.  Fortunately this is extremely rare, but the one
26222 situation that you should be alert to is the change in the predefined type
26223 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
26224
26225 @table @emph
26226 @item Range of type @code{Character}
26227 The range of @code{Standard.Character} is now the full 256 characters
26228 of Latin-1, whereas in most Ada 83 implementations it was restricted
26229 to 128 characters. Although some of the effects of
26230 this change will be manifest in compile-time rejection of legal
26231 Ada 83 programs it is possible for a working Ada 83 program to have
26232 a different effect in Ada 95, one that was not permitted in Ada 83.
26233 As an example, the expression
26234 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
26235 delivers @code{255} as its value.
26236 In general, you should look at the logic of any
26237 character-processing Ada 83 program and see whether it needs to be adapted
26238 to work correctly with Latin-1.  Note that the predefined Ada 95 API has a
26239 character handling package that may be relevant if code needs to be adapted
26240 to account for the additional Latin-1 elements.
26241 The desirable fix is to
26242 modify the program to accommodate the full character set, but in some cases
26243 it may be convenient to define a subtype or derived type of Character that
26244 covers only the restricted range.
26245 @cindex Latin-1
26246 @end table
26247
26248 @node Other language compatibility issues
26249 @subsection Other language compatibility issues
26250
26251 @table @emph
26252 @item @option{-gnat83} switch
26253 All implementations of GNAT provide a switch that causes GNAT to operate
26254 in Ada 83 mode.  In this mode, some but not all compatibility problems
26255 of the type described above are handled automatically.  For example, the
26256 new reserved words introduced in Ada 95 and Ada 2005 are treated simply
26257 as identifiers as in Ada 83.
26258 However,
26259 in practice, it is usually advisable to make the necessary modifications
26260 to the program to remove the need for using this switch.
26261 See @ref{Compiling Different Versions of Ada}.
26262
26263 @item Support for removed Ada 83 pragmas and attributes
26264 A number of pragmas and attributes from Ada 83 were removed from Ada 95,
26265 generally because they were replaced by other mechanisms.  Ada 95 and Ada 2005
26266 compilers are allowed, but not required, to implement these missing
26267 elements.  In contrast with some other compilers, GNAT implements all
26268 such pragmas and attributes, eliminating this compatibility concern.  These
26269 include @code{pragma Interface} and the floating point type attributes
26270 (@code{Emax}, @code{Mantissa}, etc.), among other items.
26271 @end table
26272
26273
26274 @node Compatibility between Ada 95 and Ada 2005
26275 @section Compatibility between Ada 95 and Ada 2005
26276 @cindex Compatibility between Ada 95 and Ada 2005
26277
26278 @noindent
26279 Although Ada 2005 was designed to be upwards compatible with Ada 95, there are
26280 a number of incompatibilities. Several are enumerated below;
26281 for a complete description please see the
26282 Annotated Ada 2005 Reference Manual, or section 9.1.1 in
26283 @cite{Rationale for Ada 2005}.
26284
26285 @table @emph
26286 @item New reserved words.
26287 The words @code{interface}, @code{overriding} and @code{synchronized} are
26288 reserved in Ada 2005.
26289 A pre-Ada 2005 program that uses any of these as an identifier will be
26290 illegal.
26291
26292 @item New declarations in predefined packages.
26293 A number of packages in the predefined environment contain new declarations:
26294 @code{Ada.Exceptions}, @code{Ada.Real_Time}, @code{Ada.Strings},
26295 @code{Ada.Strings.Fixed}, @code{Ada.Strings.Bounded},
26296 @code{Ada.Strings.Unbounded}, @code{Ada.Strings.Wide_Fixed},
26297 @code{Ada.Strings.Wide_Bounded}, @code{Ada.Strings.Wide_Unbounded},
26298 @code{Ada.Tags}, @code{Ada.Text_IO}, and @code{Interfaces.C}.
26299 If an Ada 95 program does a @code{with} and @code{use} of any of these
26300 packages, the new declarations may cause name clashes.
26301
26302 @item Access parameters.
26303 A nondispatching subprogram with an access parameter cannot be renamed
26304 as a dispatching operation.  This was permitted in Ada 95.
26305
26306 @item Access types, discriminants, and constraints.
26307 Rule changes in this area have led to some incompatibilities; for example,
26308 constrained subtypes of some access types are not permitted in Ada 2005.
26309
26310 @item Aggregates for limited types.
26311 The allowance of aggregates for limited types in Ada 2005 raises the
26312 possibility of ambiguities in legal Ada 95 programs, since additional types
26313 now need to be considered in expression resolution.
26314
26315 @item Fixed-point multiplication and division.
26316 Certain expressions involving ``*'' or ``/'' for a fixed-point type, which
26317 were legal in Ada 95 and invoked the predefined versions of these operations,
26318 are now ambiguous.
26319 The ambiguity may be resolved either by applying a type conversion to the
26320 expression, or by explicitly invoking the operation from package
26321 @code{Standard}.
26322
26323 @item Return-by-reference types.
26324 The Ada 95 return-by-reference mechanism has been removed.  Instead, the user
26325 can declare a function returning a value from an anonymous access type.
26326 @end table
26327
26328
26329 @node Implementation-dependent characteristics
26330 @section Implementation-dependent characteristics
26331 @noindent
26332 Although the Ada language defines the semantics of each construct as
26333 precisely as practical, in some situations (for example for reasons of
26334 efficiency, or where the effect is heavily dependent on the host or target
26335 platform) the implementation is allowed some freedom.  In porting Ada 83
26336 code to GNAT, you need to be aware of whether / how the existing code
26337 exercised such implementation dependencies.  Such characteristics fall into
26338 several categories, and GNAT offers specific support in assisting the
26339 transition from certain Ada 83 compilers.
26340
26341 @menu
26342 * Implementation-defined pragmas::
26343 * Implementation-defined attributes::
26344 * Libraries::
26345 * Elaboration order::
26346 * Target-specific aspects::
26347 @end menu
26348
26349 @node Implementation-defined pragmas
26350 @subsection Implementation-defined pragmas
26351
26352 @noindent
26353 Ada compilers are allowed to supplement the language-defined pragmas, and
26354 these are a potential source of non-portability.  All GNAT-defined pragmas
26355 are described in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT
26356 Reference Manual}, and these include several that are specifically
26357 intended to correspond to other vendors' Ada 83 pragmas.
26358 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
26359 For compatibility with HP Ada 83, GNAT supplies the pragmas
26360 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
26361 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
26362 and @code{Volatile}.
26363 Other relevant pragmas include @code{External} and @code{Link_With}.
26364 Some vendor-specific
26365 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
26366 recognized, thus
26367 avoiding compiler rejection of units that contain such pragmas; they are not
26368 relevant in a GNAT context and hence are not otherwise implemented.
26369
26370 @node Implementation-defined attributes
26371 @subsection Implementation-defined attributes
26372
26373 Analogous to pragmas, the set of attributes may be extended by an
26374 implementation.  All GNAT-defined attributes are described in
26375 @ref{Implementation Defined Attributes,,, gnat_rm, GNAT Reference
26376 Manual}, and these include several that are specifically intended
26377 to correspond to other vendors' Ada 83 attributes.  For migrating from VADS,
26378 the attribute @code{VADS_Size} may be useful.  For compatibility with HP
26379 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
26380 @code{Type_Class}.
26381
26382 @node Libraries
26383 @subsection Libraries
26384 @noindent
26385 Vendors may supply libraries to supplement the standard Ada API.  If Ada 83
26386 code uses vendor-specific libraries then there are several ways to manage
26387 this in Ada 95 or Ada 2005:
26388 @enumerate
26389 @item
26390 If the source code for the libraries (specs and bodies) are
26391 available, then the libraries can be migrated in the same way as the
26392 application.
26393 @item
26394 If the source code for the specs but not the bodies are
26395 available, then you can reimplement the bodies.
26396 @item
26397 Some features introduced by Ada 95 obviate the need for library support.  For
26398 example most Ada 83 vendors supplied a package for unsigned integers.  The
26399 Ada 95 modular type feature is the preferred way to handle this need, so
26400 instead of migrating or reimplementing the unsigned integer package it may
26401 be preferable to retrofit the application using modular types.
26402 @end enumerate
26403
26404 @node Elaboration order
26405 @subsection Elaboration order
26406 @noindent
26407 The implementation can choose any elaboration order consistent with the unit
26408 dependency relationship.  This freedom means that some orders can result in
26409 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
26410 to invoke a subprogram its body has been elaborated, or to instantiate a
26411 generic before the generic body has been elaborated.  By default GNAT
26412 attempts to choose a safe order (one that will not encounter access before
26413 elaboration problems) by implicitly inserting @code{Elaborate} or
26414 @code{Elaborate_All} pragmas where
26415 needed.  However, this can lead to the creation of elaboration circularities
26416 and a resulting rejection of the program by gnatbind.  This issue is
26417 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
26418 In brief, there are several
26419 ways to deal with this situation:
26420
26421 @itemize @bullet
26422 @item
26423 Modify the program to eliminate the circularities, e.g.@: by moving
26424 elaboration-time code into explicitly-invoked procedures
26425 @item
26426 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
26427 @code{Elaborate} pragmas, and then inhibit the generation of implicit
26428 @code{Elaborate_All}
26429 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
26430 (by selectively suppressing elaboration checks via pragma
26431 @code{Suppress(Elaboration_Check)} when it is safe to do so).
26432 @end itemize
26433
26434 @node Target-specific aspects
26435 @subsection Target-specific aspects
26436 @noindent
26437 Low-level applications need to deal with machine addresses, data
26438 representations, interfacing with assembler code, and similar issues.  If
26439 such an Ada 83 application is being ported to different target hardware (for
26440 example where the byte endianness has changed) then you will need to
26441 carefully examine the program logic; the porting effort will heavily depend
26442 on the robustness of the original design.  Moreover, Ada 95 (and thus
26443 Ada 2005) are sometimes
26444 incompatible with typical Ada 83 compiler practices regarding implicit
26445 packing, the meaning of the Size attribute, and the size of access values.
26446 GNAT's approach to these issues is described in @ref{Representation Clauses}.
26447
26448 @node Compatibility with Other Ada Systems
26449 @section Compatibility with Other Ada Systems
26450
26451 @noindent
26452 If programs avoid the use of implementation dependent and
26453 implementation defined features, as documented in the @cite{Ada
26454 Reference Manual}, there should be a high degree of portability between
26455 GNAT and other Ada systems.  The following are specific items which
26456 have proved troublesome in moving Ada 95 programs from GNAT to other Ada 95
26457 compilers, but do not affect porting code to GNAT@.
26458 (As of @value{NOW}, GNAT is the only compiler available for Ada 2005;
26459 the following issues may or may not arise for Ada 2005 programs
26460 when other compilers appear.)
26461
26462 @table @emph
26463 @item Ada 83 Pragmas and Attributes
26464 Ada 95 compilers are allowed, but not required, to implement the missing
26465 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
26466 GNAT implements all such pragmas and attributes, eliminating this as
26467 a compatibility concern, but some other Ada 95 compilers reject these
26468 pragmas and attributes.
26469
26470 @item Specialized Needs Annexes
26471 GNAT implements the full set of special needs annexes.  At the
26472 current time, it is the only Ada 95 compiler to do so.  This means that
26473 programs making use of these features may not be portable to other Ada
26474 95 compilation systems.
26475
26476 @item Representation Clauses
26477 Some other Ada 95 compilers implement only the minimal set of
26478 representation clauses required by the Ada 95 reference manual.  GNAT goes
26479 far beyond this minimal set, as described in the next section.
26480 @end table
26481
26482 @node Representation Clauses
26483 @section Representation Clauses
26484
26485 @noindent
26486 The Ada 83 reference manual was quite vague in describing both the minimal
26487 required implementation of representation clauses, and also their precise
26488 effects.  Ada 95 (and thus also Ada 2005) are much more explicit, but the
26489 minimal set of capabilities required is still quite limited.
26490
26491 GNAT implements the full required set of capabilities in
26492 Ada 95 and Ada 2005, but also goes much further, and in particular
26493 an effort has been made to be compatible with existing Ada 83 usage to the
26494 greatest extent possible.
26495
26496 A few cases exist in which Ada 83 compiler behavior is incompatible with
26497 the requirements in Ada 95 (and thus also Ada 2005).  These are instances of
26498 intentional or accidental dependence on specific implementation dependent
26499 characteristics of these Ada 83 compilers.  The following is a list of
26500 the cases most likely to arise in existing Ada 83 code.
26501
26502 @table @emph
26503 @item Implicit Packing
26504 Some Ada 83 compilers allowed a Size specification to cause implicit
26505 packing of an array or record.  This could cause expensive implicit
26506 conversions for change of representation in the presence of derived
26507 types, and the Ada design intends to avoid this possibility.
26508 Subsequent AI's were issued to make it clear that such implicit
26509 change of representation in response to a Size clause is inadvisable,
26510 and this recommendation is represented explicitly in the Ada 95 (and Ada 2005)
26511 Reference Manuals as implementation advice that is followed by GNAT@.
26512 The problem will show up as an error
26513 message rejecting the size clause.  The fix is simply to provide
26514 the explicit pragma @code{Pack}, or for more fine tuned control, provide
26515 a Component_Size clause.
26516
26517 @item Meaning of Size Attribute
26518 The Size attribute in Ada 95 (and Ada 2005) for discrete types is defined as
26519 the minimal number of bits required to hold values of the type.  For example,
26520 on a 32-bit machine, the size of @code{Natural} will typically be 31 and not
26521 32 (since no sign bit is required).  Some Ada 83 compilers gave 31, and
26522 some 32 in this situation.  This problem will usually show up as a compile
26523 time error, but not always.  It is a good idea to check all uses of the
26524 'Size attribute when porting Ada 83 code.  The GNAT specific attribute
26525 Object_Size can provide a useful way of duplicating the behavior of
26526 some Ada 83 compiler systems.
26527
26528 @item Size of Access Types
26529 A common assumption in Ada 83 code is that an access type is in fact a pointer,
26530 and that therefore it will be the same size as a System.Address value.  This
26531 assumption is true for GNAT in most cases with one exception.  For the case of
26532 a pointer to an unconstrained array type (where the bounds may vary from one
26533 value of the access type to another), the default is to use a ``fat pointer'',
26534 which is represented as two separate pointers, one to the bounds, and one to
26535 the array.  This representation has a number of advantages, including improved
26536 efficiency.  However, it may cause some difficulties in porting existing Ada 83
26537 code which makes the assumption that, for example, pointers fit in 32 bits on
26538 a machine with 32-bit addressing.
26539
26540 To get around this problem, GNAT also permits the use of ``thin pointers'' for
26541 access types in this case (where the designated type is an unconstrained array
26542 type).  These thin pointers are indeed the same size as a System.Address value.
26543 To specify a thin pointer, use a size clause for the type, for example:
26544
26545 @smallexample @c ada
26546 type X is access all String;
26547 for X'Size use Standard'Address_Size;
26548 @end smallexample
26549
26550 @noindent
26551 which will cause the type X to be represented using a single pointer.
26552 When using this representation, the bounds are right behind the array.
26553 This representation is slightly less efficient, and does not allow quite
26554 such flexibility in the use of foreign pointers or in using the
26555 Unrestricted_Access attribute to create pointers to non-aliased objects.
26556 But for any standard portable use of the access type it will work in
26557 a functionally correct manner and allow porting of existing code.
26558 Note that another way of forcing a thin pointer representation
26559 is to use a component size clause for the element size in an array,
26560 or a record representation clause for an access field in a record.
26561 @end table
26562
26563 @ifclear vms
26564 @c This brief section is only in the non-VMS version
26565 @c The complete chapter on HP Ada is in the VMS version
26566 @node Compatibility with HP Ada 83
26567 @section Compatibility with HP Ada 83
26568
26569 @noindent
26570 The VMS version of GNAT fully implements all the pragmas and attributes
26571 provided by HP Ada 83, as well as providing the standard HP Ada 83
26572 libraries, including Starlet.  In addition, data layouts and parameter
26573 passing conventions are highly compatible.  This means that porting
26574 existing HP Ada 83 code to GNAT in VMS systems should be easier than
26575 most other porting efforts.  The following are some of the most
26576 significant differences between GNAT and HP Ada 83.
26577
26578 @table @emph
26579 @item Default floating-point representation
26580 In GNAT, the default floating-point format is IEEE, whereas in HP Ada 83,
26581 it is VMS format.  GNAT does implement the necessary pragmas
26582 (Long_Float, Float_Representation) for changing this default.
26583
26584 @item System
26585 The package System in GNAT exactly corresponds to the definition in the
26586 Ada 95 reference manual, which means that it excludes many of the
26587 HP Ada 83 extensions.  However, a separate package Aux_DEC is provided
26588 that contains the additional definitions, and a special pragma,
26589 Extend_System allows this package to be treated transparently as an
26590 extension of package System.
26591
26592 @item To_Address
26593 The definitions provided by Aux_DEC are exactly compatible with those
26594 in the HP Ada 83 version of System, with one exception.
26595 HP Ada provides the following declarations:
26596
26597 @smallexample @c ada
26598 TO_ADDRESS (INTEGER)
26599 TO_ADDRESS (UNSIGNED_LONGWORD)
26600 TO_ADDRESS (@i{universal_integer})
26601 @end smallexample
26602
26603 @noindent
26604 The version of TO_ADDRESS taking a @i{universal integer} argument is in fact
26605 an extension to Ada 83 not strictly compatible with the reference manual.
26606 In GNAT, we are constrained to be exactly compatible with the standard,
26607 and this means we cannot provide this capability.  In HP Ada 83, the
26608 point of this definition is to deal with a call like:
26609
26610 @smallexample @c ada
26611 TO_ADDRESS (16#12777#);
26612 @end smallexample
26613
26614 @noindent
26615 Normally, according to the Ada 83 standard, one would expect this to be
26616 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
26617 of TO_ADDRESS@.  However, in HP Ada 83, there is no ambiguity, since the
26618 definition using @i{universal_integer} takes precedence.
26619
26620 In GNAT, since the version with @i{universal_integer} cannot be supplied, it
26621 is not possible to be 100% compatible.  Since there are many programs using
26622 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
26623 to change the name of the function in the UNSIGNED_LONGWORD case, so the
26624 declarations provided in the GNAT version of AUX_Dec are:
26625
26626 @smallexample @c ada
26627 function To_Address (X : Integer) return Address;
26628 pragma Pure_Function (To_Address);
26629
26630 function To_Address_Long (X : Unsigned_Longword)
26631  return Address;
26632 pragma Pure_Function (To_Address_Long);
26633 @end smallexample
26634
26635 @noindent
26636 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
26637 change the name to TO_ADDRESS_LONG@.
26638
26639 @item Task_Id values
26640 The Task_Id values assigned will be different in the two systems, and GNAT
26641 does not provide a specified value for the Task_Id of the environment task,
26642 which in GNAT is treated like any other declared task.
26643 @end table
26644
26645 @noindent
26646 For full details on these and other less significant compatibility issues,
26647 see appendix E of the HP publication entitled @cite{HP Ada, Technical
26648 Overview and Comparison on HP Platforms}.
26649
26650 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
26651 attributes are recognized, although only a subset of them can sensibly
26652 be implemented.  The description of pragmas in @ref{Implementation
26653 Defined Pragmas,,, gnat_rm, GNAT Reference Manual}
26654 indicates whether or not they are applicable to non-VMS systems.
26655 @end ifclear
26656
26657 @ifset vms
26658 @node Transitioning to 64-Bit GNAT for OpenVMS
26659 @section Transitioning to 64-Bit @value{EDITION} for OpenVMS
26660
26661 @noindent
26662 This section is meant to assist users of pre-2006 @value{EDITION}
26663 for Alpha OpenVMS who are transitioning to 64-bit @value{EDITION},
26664 the version of the GNAT technology supplied in 2006 and later for
26665 OpenVMS on both Alpha and I64.
26666
26667 @menu
26668 * Introduction to transitioning::
26669 * Migration of 32 bit code::
26670 * Taking advantage of 64 bit addressing::
26671 * Technical details::
26672 @end menu
26673
26674 @node Introduction to transitioning
26675 @subsection Introduction
26676
26677 @noindent
26678 64-bit @value{EDITION} for Open VMS has been designed to meet
26679 three main goals:
26680
26681 @enumerate
26682 @item
26683 Providing a full conforming implementation of Ada 95 and Ada 2005
26684
26685 @item
26686 Allowing maximum backward compatibility, thus easing migration of existing
26687 Ada source code
26688
26689 @item
26690 Supplying a path for exploiting the full 64-bit address range
26691 @end enumerate
26692
26693 @noindent
26694 Ada's strong typing semantics has made it
26695 impractical to have different 32-bit and 64-bit modes. As soon as
26696 one object could possibly be outside the 32-bit address space, this
26697 would make it necessary for the @code{System.Address} type to be 64 bits.
26698 In particular, this would cause inconsistencies if 32-bit code is
26699 called from 64-bit code that raises an exception.
26700
26701 This issue has been resolved by always using 64-bit addressing
26702 at the system level, but allowing for automatic conversions between
26703 32-bit and 64-bit addresses where required. Thus users who
26704 do not currently require 64-bit addressing capabilities, can
26705 recompile their code with only minimal changes (and indeed
26706 if the code is written in portable Ada, with no assumptions about
26707 the size of the @code{Address} type, then no changes at all are necessary).
26708 At the same time,
26709 this approach provides a simple, gradual upgrade path to future
26710 use of larger memories than available for 32-bit systems.
26711 Also, newly written applications or libraries will by default
26712 be fully compatible with future systems exploiting 64-bit
26713 addressing capabilities.
26714
26715 @ref{Migration of 32 bit code}, will focus on porting applications
26716 that do not require more than 2 GB of
26717 addressable memory. This code will be referred to as
26718 @emph{32-bit code}.
26719 For applications intending to exploit the full 64-bit address space,
26720 @ref{Taking advantage of 64 bit addressing},
26721 will consider further changes that may be required.
26722 Such code will be referred to below as @emph{64-bit code}.
26723
26724 @node Migration of 32 bit code
26725 @subsection Migration of 32-bit code
26726
26727 @menu
26728 * Address types::
26729 * Access types and 32/64-bit allocation::
26730 * Unchecked conversions::
26731 * Predefined constants::
26732 * Interfacing with C::
26733 * 32/64-bit descriptors::
26734 * Experience with source compatibility::
26735 @end menu
26736
26737 @node Address types
26738 @subsubsection Address types
26739
26740 @noindent
26741 To solve the problem of mixing 64-bit and 32-bit addressing,
26742 while maintaining maximum backward compatibility, the following
26743 approach has been taken:
26744
26745 @itemize @bullet
26746 @item
26747 @code{System.Address} always has a size of 64 bits
26748 @cindex @code{System.Address} size
26749 @cindex @code{Address} size
26750
26751 @item
26752 @code{System.Short_Address} is a 32-bit subtype of @code{System.Address}
26753 @cindex @code{System.Short_Address} size
26754 @cindex @code{Short_Address} size
26755 @end itemize
26756
26757 @noindent
26758 Since @code{System.Short_Address} is a subtype of @code{System.Address},
26759 a @code{Short_Address}
26760 may be used where an @code{Address} is required, and vice versa, without
26761 needing explicit type conversions.
26762 By virtue of the Open VMS parameter passing conventions,
26763 even imported
26764 and exported subprograms that have 32-bit address parameters are
26765 compatible with those that have 64-bit address parameters.
26766 (See @ref{Making code 64 bit clean} for details.)
26767
26768 The areas that may need attention are those where record types have
26769 been defined that contain components of the type @code{System.Address}, and
26770 where objects of this type are passed to code expecting a record layout with
26771 32-bit addresses.
26772
26773 Different compilers on different platforms cannot be
26774 expected to represent the same type in the same way,
26775 since alignment constraints
26776 and other system-dependent properties affect the compiler's decision.
26777 For that reason, Ada code
26778 generally uses representation clauses to specify the expected
26779 layout where required.
26780
26781 If such a representation clause uses 32 bits for a component having
26782 the type @code{System.Address}, 64-bit @value{EDITION} for OpenVMS
26783 will detect that error and produce a specific diagnostic message.
26784 The developer should then determine whether the representation
26785 should be 64 bits or not and make either of two changes:
26786 change the size to 64 bits and leave the type as @code{System.Address}, or
26787 leave the size as 32 bits and change the type to @code{System.Short_Address}.
26788 Since @code{Short_Address} is a subtype of @code{Address}, no changes are
26789 required in any code setting or accessing the field; the compiler will
26790 automatically perform any needed conversions between address
26791 formats.
26792
26793 @node Access types and 32/64-bit allocation
26794 @subsubsection Access types and 32/64-bit allocation
26795 @cindex 32-bit allocation
26796 @cindex 64-bit allocation
26797
26798 @noindent
26799 By default, objects designated by access values are always allocated in
26800 the 64-bit address space, and access values themselves are represented
26801 in 64 bits.  If these defaults are not appropriate, and 32-bit allocation
26802 is required (for example if the address of an allocated object is assigned
26803 to a @code{Short_Address} variable), then several alternatives are available:
26804
26805 @itemize @bullet
26806 @item
26807 A pool-specific access type (ie, an @w{Ada 83} access type, whose
26808 definition is @code{access T} versus @code{access all T} or
26809 @code{access constant T}), may be declared with a @code{'Size} representation
26810 clause that establishes the size as 32 bits.
26811 In such circumstances allocations for that type will
26812 be from the 32-bit heap.  Such a clause is not permitted
26813 for a general access type (declared with @code{access all} or
26814 @code{access constant}) as values of such types must be able to refer
26815 to any object of the designated type, including objects residing outside
26816 the 32-bit address range.  Existing @w{Ada 83} code will not contain such
26817 type definitions, however, since general access types were introduced
26818 in @w{Ada 95}.
26819
26820 @item
26821 Switches for @command{GNAT BIND} control whether the internal GNAT
26822 allocation routine @code{__gnat_malloc} uses 64-bit or 32-bit allocations.
26823 @cindex @code{__gnat_malloc}
26824 The switches are respectively @option{-H64} (the default) and
26825 @option{-H32}.
26826 @cindex @option{-H32} (@command{gnatbind})
26827 @cindex @option{-H64} (@command{gnatbind})
26828
26829 @item
26830 The environment variable (logical name) @code{GNAT$NO_MALLOC_64}
26831 @cindex @code{GNAT$NO_MALLOC_64} environment variable
26832 may be used to force @code{__gnat_malloc} to use 32-bit allocation.
26833 If this variable is left
26834 undefined, or defined as @code{"DISABLE"}, @code{"FALSE"}, or @code{"0"},
26835 then the default (64-bit) allocation is used.
26836 If defined as @code{"ENABLE"}, @code{"TRUE"}, or @code{"1"},
26837 then 32-bit allocation is used.  The gnatbind qualifiers described above
26838 override this logical name.
26839
26840 @item
26841 A ^gcc switch^gcc switch^ for OpenVMS, @option{-mno-malloc64}, operates
26842 @cindex @option{-mno-malloc64} (^gcc^gcc^)
26843 at a low level to convert explicit calls to @code{malloc} and related
26844 functions from the C run-time library so that they perform allocations
26845 in the 32-bit heap.
26846 Since all internal allocations from GNAT use @code{__gnat_malloc},
26847 this switch is not required unless the program makes explicit calls on
26848 @code{malloc} (or related functions) from interfaced C code.
26849 @end itemize
26850
26851
26852 @node Unchecked conversions
26853 @subsubsection Unchecked conversions
26854
26855 @noindent
26856 In the case of an @code{Unchecked_Conversion} where the source type is a
26857 64-bit access type or the type @code{System.Address}, and the target
26858 type is a 32-bit type, the compiler will generate a warning.
26859 Even though the generated code will still perform the required
26860 conversions, it is highly recommended in these cases to use
26861 respectively a 32-bit access type or @code{System.Short_Address}
26862 as the source type.
26863
26864 @node Predefined constants
26865 @subsubsection Predefined constants
26866
26867 @noindent
26868 The following table shows the correspondence between pre-2006 versions of
26869 @value{EDITION} on Alpha OpenVMS (``Old'') and 64-bit @value{EDITION}
26870 (``New''):
26871
26872 @multitable {@code{System.Short_Memory_Size}} {2**32} {2**64}
26873 @item   @b{Constant}                     @tab @b{Old} @tab @b{New}
26874 @item   @code{System.Word_Size}          @tab 32      @tab 64
26875 @item   @code{System.Memory_Size}        @tab 2**32   @tab 2**64
26876 @item   @code{System.Short_Memory_Size}  @tab 2**32   @tab 2**32
26877 @item   @code{System.Address_Size}       @tab 32      @tab 64
26878 @end multitable
26879
26880 @noindent
26881 If you need to refer to the specific
26882 memory size of a 32-bit implementation, instead of the
26883 actual memory size, use @code{System.Short_Memory_Size}
26884 rather than @code{System.Memory_Size}.
26885 Similarly, references to @code{System.Address_Size} may need
26886 to be replaced by @code{System.Short_Address'Size}.
26887 The program @command{gnatfind} may be useful for locating
26888 references to the above constants, so that you can verify that they
26889 are still correct.
26890
26891 @node Interfacing with C
26892 @subsubsection Interfacing with C
26893
26894 @noindent
26895 In order to minimize the impact of the transition to 64-bit addresses on
26896 legacy programs, some fundamental types in the @code{Interfaces.C}
26897 package hierarchy continue to be represented in 32 bits.
26898 These types are: @code{ptrdiff_t}, @code{size_t}, and @code{chars_ptr}.
26899 This eases integration with the default HP C layout choices, for example
26900 as found in the system routines in @code{DECC$SHR.EXE}.
26901 Because of this implementation choice, the type fully compatible with
26902 @code{chars_ptr} is now @code{Short_Address} and not @code{Address}.
26903 Depending on the context the compiler will issue a
26904 warning or an error when type @code{Address} is used, alerting the user to a
26905 potential problem. Otherwise 32-bit programs that use
26906 @code{Interfaces.C} should normally not require code modifications
26907
26908 The other issue arising with C interfacing concerns pragma @code{Convention}.
26909 For VMS 64-bit systems, there is an issue of the appropriate default size
26910 of C convention pointers in the absence of an explicit size clause. The HP
26911 C compiler can choose either 32 or 64 bits depending on compiler options.
26912 GNAT chooses 32-bits rather than 64-bits in the default case where no size
26913 clause is given. This proves a better choice for porting 32-bit legacy
26914 applications. In order to have a 64-bit representation, it is necessary to
26915 specify a size representation clause. For example:
26916
26917 @smallexample @c ada
26918 type int_star is access Interfaces.C.int;
26919 pragma Convention(C, int_star);
26920 for int_star'Size use 64;  -- Necessary to get 64 and not 32 bits
26921 @end smallexample
26922
26923 @node 32/64-bit descriptors
26924 @subsubsection 32/64-bit descriptors
26925
26926 @noindent
26927 By default, GNAT uses a 64-bit descriptor mechanism.  For an imported
26928 subprogram (i.e., a subprogram identified by pragma @code{Import_Function},
26929 @code{Import_Procedure}, or @code{Import_Valued_Procedure}) that specifies
26930 @code{Short_Descriptor} as its mechanism, a 32-bit descriptor is used.
26931 @cindex @code{Short_Descriptor} mechanism for imported subprograms
26932
26933 If the configuration pragma @code{Short_Descriptors} is supplied, then
26934 all descriptors will be 32 bits.
26935 @cindex pragma @code{Short_Descriptors}
26936
26937 @node Experience with source compatibility
26938 @subsubsection Experience with source compatibility
26939
26940 @noindent
26941 The Security Server and STARLET on I64 provide an interesting ``test case''
26942 for source compatibility issues, since it is in such system code
26943 where assumptions about @code{Address} size might be expected to occur.
26944 Indeed, there were a small number of occasions in the Security Server
26945 file @file{jibdef.ads}
26946 where a representation clause for a record type specified
26947 32 bits for a component of type @code{Address}.
26948 All of these errors were detected by the compiler.
26949 The repair was obvious and immediate; to simply replace @code{Address} by
26950 @code{Short_Address}.
26951
26952 In the case of STARLET, there were several record types that should
26953 have had representation clauses but did not.  In these record types
26954 there was an implicit assumption that an @code{Address} value occupied
26955 32 bits.
26956 These compiled without error, but their usage resulted in run-time error
26957 returns from STARLET system calls.
26958 Future GNAT technology enhancements may include a tool that detects and flags
26959 these sorts of potential source code porting problems.
26960
26961 @c ****************************************
26962 @node Taking advantage of 64 bit addressing
26963 @subsection Taking advantage of 64-bit addressing
26964
26965 @menu
26966 * Making code 64 bit clean::
26967 * Allocating memory from the 64 bit storage pool::
26968 * Restrictions on use of 64 bit objects::
26969 * STARLET and other predefined libraries::
26970 @end menu
26971
26972 @node Making code 64 bit clean
26973 @subsubsection Making code 64-bit clean
26974
26975 @noindent
26976 In order to prevent problems that may occur when (parts of) a
26977 system start using memory outside the 32-bit address range,
26978 we recommend some additional guidelines:
26979
26980 @itemize @bullet
26981 @item
26982 For imported subprograms that take parameters of the
26983 type @code{System.Address}, ensure that these subprograms can
26984 indeed handle 64-bit addresses. If not, or when in doubt,
26985 change the subprogram declaration to specify
26986 @code{System.Short_Address} instead.
26987
26988 @item
26989 Resolve all warnings related to size mismatches in
26990 unchecked conversions. Failing to do so causes
26991 erroneous execution if the source object is outside
26992 the 32-bit address space.
26993
26994 @item
26995 (optional) Explicitly use the 32-bit storage pool
26996 for access types used in a 32-bit context, or use
26997 generic access types where possible
26998 (@pxref{Restrictions on use of 64 bit objects}).
26999 @end itemize
27000
27001 @noindent
27002 If these rules are followed, the compiler will automatically insert
27003 any necessary checks to ensure that no addresses or access values
27004 passed to 32-bit code ever refer to objects outside the 32-bit
27005 address range.
27006 Any attempt to do this will raise @code{Constraint_Error}.
27007
27008 @node Allocating memory from the 64 bit storage pool
27009 @subsubsection Allocating memory from the 64-bit storage pool
27010
27011 @noindent
27012 By default, all allocations -- for both pool-specific and general
27013 access types -- use the 64-bit storage pool.  To override
27014 this default, for an individual access type or globally, see
27015 @ref{Access types and 32/64-bit allocation}.
27016
27017 @node Restrictions on use of 64 bit objects
27018 @subsubsection Restrictions on use of 64-bit objects
27019
27020 @noindent
27021 Taking the address of an object allocated from a 64-bit storage pool,
27022 and then passing this address to a subprogram expecting
27023 @code{System.Short_Address},
27024 or assigning it to a variable of type @code{Short_Address}, will cause
27025 @code{Constraint_Error} to be raised. In case the code is not 64-bit clean
27026 (@pxref{Making code 64 bit clean}), or checks are suppressed,
27027 no exception is raised and execution
27028 will become erroneous.
27029
27030 @node STARLET and other predefined libraries
27031 @subsubsection STARLET and other predefined libraries
27032
27033 @noindent
27034 All code that comes as part of GNAT is 64-bit clean, but the
27035 restrictions given in @ref{Restrictions on use of 64 bit objects},
27036 still apply. Look at the package
27037 specs to see in which contexts objects allocated
27038 in 64-bit address space are acceptable.
27039
27040 @node Technical details
27041 @subsection Technical details
27042
27043 @noindent
27044 64-bit @value{EDITION} for Open VMS takes advantage of the freedom given in the
27045 Ada standard with respect to the type of @code{System.Address}. Previous
27046 versions of @value{EDITION} have defined this type as private and implemented it as a
27047 modular type.
27048
27049 In order to allow defining @code{System.Short_Address} as a proper subtype,
27050 and to match the implicit sign extension in parameter passing,
27051 in 64-bit @value{EDITION} for Open VMS, @code{System.Address} is defined as a
27052 visible (i.e., non-private) integer type.
27053 Standard operations on the type, such as the binary operators ``+'', ``-'',
27054 etc., that take @code{Address} operands and return an @code{Address} result,
27055 have been hidden by declaring these
27056 @code{abstract}, a feature introduced in Ada 95 that helps avoid the potential
27057 ambiguities that would otherwise result from overloading.
27058 (Note that, although @code{Address} is a visible integer type,
27059 good programming practice dictates against exploiting the type's
27060 integer properties such as literals, since this will compromise
27061 code portability.)
27062
27063 Defining @code{Address} as a visible integer type helps achieve
27064 maximum compatibility for existing Ada code,
27065 without sacrificing the capabilities of the 64-bit architecture.
27066 @end ifset
27067
27068 @c ************************************************
27069 @ifset unw
27070 @node Microsoft Windows Topics
27071 @appendix Microsoft Windows Topics
27072 @cindex Windows NT
27073 @cindex Windows 95
27074 @cindex Windows 98
27075
27076 @noindent
27077 This chapter describes topics that are specific to the Microsoft Windows
27078 platforms (NT, 2000, and XP Professional).
27079
27080 @menu
27081 * Using GNAT on Windows::
27082 * Using a network installation of GNAT::
27083 * CONSOLE and WINDOWS subsystems::
27084 * Temporary Files::
27085 * Mixed-Language Programming on Windows::
27086 * Windows Calling Conventions::
27087 * Introduction to Dynamic Link Libraries (DLLs)::
27088 * Using DLLs with GNAT::
27089 * Building DLLs with GNAT Project files::
27090 * Building DLLs with GNAT::
27091 * Building DLLs with gnatdll::
27092 * GNAT and Windows Resources::
27093 * Debugging a DLL::
27094 * Setting Stack Size from gnatlink::
27095 * Setting Heap Size from gnatlink::
27096 @end menu
27097
27098 @node Using GNAT on Windows
27099 @section Using GNAT on Windows
27100
27101 @noindent
27102 One of the strengths of the GNAT technology is that its tool set
27103 (@command{gcc}, @command{gnatbind}, @command{gnatlink}, @command{gnatmake}, the
27104 @code{gdb} debugger, etc.) is used in the same way regardless of the
27105 platform.
27106
27107 On Windows this tool set is complemented by a number of Microsoft-specific
27108 tools that have been provided to facilitate interoperability with Windows
27109 when this is required. With these tools:
27110
27111 @itemize @bullet
27112
27113 @item
27114 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
27115 subsystems.
27116
27117 @item
27118 You can use any Dynamically Linked Library (DLL) in your Ada code (both
27119 relocatable and non-relocatable DLLs are supported).
27120
27121 @item
27122 You can build Ada DLLs for use in other applications. These applications
27123 can be written in a language other than Ada (e.g., C, C++, etc). Again both
27124 relocatable and non-relocatable Ada DLLs are supported.
27125
27126 @item
27127 You can include Windows resources in your Ada application.
27128
27129 @item
27130 You can use or create COM/DCOM objects.
27131 @end itemize
27132
27133 @noindent
27134 Immediately below are listed all known general GNAT-for-Windows restrictions.
27135 Other restrictions about specific features like Windows Resources and DLLs
27136 are listed in separate sections below.
27137
27138 @itemize @bullet
27139
27140 @item
27141 It is not possible to use @code{GetLastError} and @code{SetLastError}
27142 when tasking, protected records, or exceptions are used. In these
27143 cases, in order to implement Ada semantics, the GNAT run-time system
27144 calls certain Win32 routines that set the last error variable to 0 upon
27145 success. It should be possible to use @code{GetLastError} and
27146 @code{SetLastError} when tasking, protected record, and exception
27147 features are not used, but it is not guaranteed to work.
27148
27149 @item
27150 It is not possible to link against Microsoft libraries except for
27151 import libraries. Interfacing must be done by the mean of DLLs.
27152
27153 @item
27154 When the compilation environment is located on FAT32 drives, users may
27155 experience recompilations of the source files that have not changed if
27156 Daylight Saving Time (DST) state has changed since the last time files
27157 were compiled. NTFS drives do not have this problem.
27158
27159 @item
27160 No components of the GNAT toolset use any entries in the Windows
27161 registry. The only entries that can be created are file associations and
27162 PATH settings, provided the user has chosen to create them at installation
27163 time, as well as some minimal book-keeping information needed to correctly
27164 uninstall or integrate different GNAT products.
27165 @end itemize
27166
27167 @node Using a network installation of GNAT
27168 @section Using a network installation of GNAT
27169
27170 @noindent
27171 Make sure the system on which GNAT is installed is accessible from the
27172 current machine, i.e., the install location is shared over the network.
27173 Shared resources are accessed on Windows by means of UNC paths, which
27174 have the format @code{\\server\sharename\path}
27175
27176 In order to use such a network installation, simply add the UNC path of the
27177 @file{bin} directory of your GNAT installation in front of your PATH. For
27178 example, if GNAT is installed in @file{\GNAT} directory of a share location
27179 called @file{c-drive} on a machine @file{LOKI}, the following command will
27180 make it available:
27181
27182 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
27183
27184 Be aware that every compilation using the network installation results in the
27185 transfer of large amounts of data across the network and will likely cause
27186 serious performance penalty.
27187
27188 @node CONSOLE and WINDOWS subsystems
27189 @section CONSOLE and WINDOWS subsystems
27190 @cindex CONSOLE Subsystem
27191 @cindex WINDOWS Subsystem
27192 @cindex -mwindows
27193
27194 @noindent
27195 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
27196 (which is the default subsystem) will always create a console when
27197 launching the application. This is not something desirable when the
27198 application has a Windows GUI. To get rid of this console the
27199 application must be using the @code{WINDOWS} subsystem. To do so
27200 the @option{-mwindows} linker option must be specified.
27201
27202 @smallexample
27203 $ gnatmake winprog -largs -mwindows
27204 @end smallexample
27205
27206 @node Temporary Files
27207 @section Temporary Files
27208 @cindex Temporary files
27209
27210 @noindent
27211 It is possible to control where temporary files gets created by setting
27212 the @env{TMP} environment variable. The file will be created:
27213
27214 @itemize
27215 @item Under the directory pointed to by the @env{TMP} environment variable if
27216 this directory exists.
27217
27218 @item Under @file{c:\temp}, if the @env{TMP} environment variable is not
27219 set (or not pointing to a directory) and if this directory exists.
27220
27221 @item Under the current working directory otherwise.
27222 @end itemize
27223
27224 @noindent
27225 This allows you to determine exactly where the temporary
27226 file will be created. This is particularly useful in networked
27227 environments where you may not have write access to some
27228 directories.
27229
27230 @node Mixed-Language Programming on Windows
27231 @section Mixed-Language Programming on Windows
27232
27233 @noindent
27234 Developing pure Ada applications on Windows is no different than on
27235 other GNAT-supported platforms. However, when developing or porting an
27236 application that contains a mix of Ada and C/C++, the choice of your
27237 Windows C/C++ development environment conditions your overall
27238 interoperability strategy.
27239
27240 If you use @command{gcc} to compile the non-Ada part of your application,
27241 there are no Windows-specific restrictions that affect the overall
27242 interoperability with your Ada code. If you do want to use the
27243 Microsoft tools for your non-Ada code, you have two choices:
27244
27245 @enumerate
27246 @item
27247 Encapsulate your non-Ada code in a DLL to be linked with your Ada
27248 application. In this case, use the Microsoft or whatever environment to
27249 build the DLL and use GNAT to build your executable
27250 (@pxref{Using DLLs with GNAT}).
27251
27252 @item
27253 Or you can encapsulate your Ada code in a DLL to be linked with the
27254 other part of your application. In this case, use GNAT to build the DLL
27255 (@pxref{Building DLLs with GNAT Project files}) and use the Microsoft
27256 or whatever environment to build your executable.
27257 @end enumerate
27258
27259 @node Windows Calling Conventions
27260 @section Windows Calling Conventions
27261 @findex Stdcall
27262 @findex APIENTRY
27263
27264 This section pertain only to Win32. On Win64 there is a single native
27265 calling convention. All convention specifiers are ignored on this
27266 platform.
27267
27268 @menu
27269 * C Calling Convention::
27270 * Stdcall Calling Convention::
27271 * Win32 Calling Convention::
27272 * DLL Calling Convention::
27273 @end menu
27274
27275 @noindent
27276 When a subprogram @code{F} (caller) calls a subprogram @code{G}
27277 (callee), there are several ways to push @code{G}'s parameters on the
27278 stack and there are several possible scenarios to clean up the stack
27279 upon @code{G}'s return. A calling convention is an agreed upon software
27280 protocol whereby the responsibilities between the caller (@code{F}) and
27281 the callee (@code{G}) are clearly defined. Several calling conventions
27282 are available for Windows:
27283
27284 @itemize @bullet
27285 @item
27286 @code{C} (Microsoft defined)
27287
27288 @item
27289 @code{Stdcall} (Microsoft defined)
27290
27291 @item
27292 @code{Win32} (GNAT specific)
27293
27294 @item
27295 @code{DLL} (GNAT specific)
27296 @end itemize
27297
27298 @node C Calling Convention
27299 @subsection @code{C} Calling Convention
27300
27301 @noindent
27302 This is the default calling convention used when interfacing to C/C++
27303 routines compiled with either @command{gcc} or Microsoft Visual C++.
27304
27305 In the @code{C} calling convention subprogram parameters are pushed on the
27306 stack by the caller from right to left. The caller itself is in charge of
27307 cleaning up the stack after the call. In addition, the name of a routine
27308 with @code{C} calling convention is mangled by adding a leading underscore.
27309
27310 The name to use on the Ada side when importing (or exporting) a routine
27311 with @code{C} calling convention is the name of the routine. For
27312 instance the C function:
27313
27314 @smallexample
27315 int get_val (long);
27316 @end smallexample
27317
27318 @noindent
27319 should be imported from Ada as follows:
27320
27321 @smallexample @c ada
27322 @group
27323 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
27324 pragma Import (C, Get_Val, External_Name => "get_val");
27325 @end group
27326 @end smallexample
27327
27328 @noindent
27329 Note that in this particular case the @code{External_Name} parameter could
27330 have been omitted since, when missing, this parameter is taken to be the
27331 name of the Ada entity in lower case. When the @code{Link_Name} parameter
27332 is missing, as in the above example, this parameter is set to be the
27333 @code{External_Name} with a leading underscore.
27334
27335 When importing a variable defined in C, you should always use the @code{C}
27336 calling convention unless the object containing the variable is part of a
27337 DLL (in which case you should use the @code{Stdcall} calling
27338 convention, @pxref{Stdcall Calling Convention}).
27339
27340 @node Stdcall Calling Convention
27341 @subsection @code{Stdcall} Calling Convention
27342
27343 @noindent
27344 This convention, which was the calling convention used for Pascal
27345 programs, is used by Microsoft for all the routines in the Win32 API for
27346 efficiency reasons. It must be used to import any routine for which this
27347 convention was specified.
27348
27349 In the @code{Stdcall} calling convention subprogram parameters are pushed
27350 on the stack by the caller from right to left. The callee (and not the
27351 caller) is in charge of cleaning the stack on routine exit. In addition,
27352 the name of a routine with @code{Stdcall} calling convention is mangled by
27353 adding a leading underscore (as for the @code{C} calling convention) and a
27354 trailing @code{@@}@code{@var{nn}}, where @var{nn} is the overall size (in
27355 bytes) of the parameters passed to the routine.
27356
27357 The name to use on the Ada side when importing a C routine with a
27358 @code{Stdcall} calling convention is the name of the C routine. The leading
27359 underscore and trailing @code{@@}@code{@var{nn}} are added automatically by
27360 the compiler. For instance the Win32 function:
27361
27362 @smallexample
27363 @b{APIENTRY} int get_val (long);
27364 @end smallexample
27365
27366 @noindent
27367 should be imported from Ada as follows:
27368
27369 @smallexample @c ada
27370 @group
27371 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
27372 pragma Import (Stdcall, Get_Val);
27373 --  On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
27374 @end group
27375 @end smallexample
27376
27377 @noindent
27378 As for the @code{C} calling convention, when the @code{External_Name}
27379 parameter is missing, it is taken to be the name of the Ada entity in lower
27380 case. If instead of writing the above import pragma you write:
27381
27382 @smallexample @c ada
27383 @group
27384 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
27385 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
27386 @end group
27387 @end smallexample
27388
27389 @noindent
27390 then the imported routine is @code{_retrieve_val@@4}. However, if instead
27391 of specifying the @code{External_Name} parameter you specify the
27392 @code{Link_Name} as in the following example:
27393
27394 @smallexample @c ada
27395 @group
27396 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
27397 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
27398 @end group
27399 @end smallexample
27400
27401 @noindent
27402 then the imported routine is @code{retrieve_val}, that is, there is no
27403 decoration at all. No leading underscore and no Stdcall suffix
27404 @code{@@}@code{@var{nn}}.
27405
27406 @noindent
27407 This is especially important as in some special cases a DLL's entry
27408 point name lacks a trailing @code{@@}@code{@var{nn}} while the exported
27409 name generated for a call has it.
27410
27411 @noindent
27412 It is also possible to import variables defined in a DLL by using an
27413 import pragma for a variable. As an example, if a DLL contains a
27414 variable defined as:
27415
27416 @smallexample
27417 int my_var;
27418 @end smallexample
27419
27420 @noindent
27421 then, to access this variable from Ada you should write:
27422
27423 @smallexample @c ada
27424 @group
27425 My_Var : Interfaces.C.int;
27426 pragma Import (Stdcall, My_Var);
27427 @end group
27428 @end smallexample
27429
27430 @noindent
27431 Note that to ease building cross-platform bindings this convention
27432 will be handled as a @code{C} calling convention on non-Windows platforms.
27433
27434 @node Win32 Calling Convention
27435 @subsection @code{Win32} Calling Convention
27436
27437 @noindent
27438 This convention, which is GNAT-specific is fully equivalent to the
27439 @code{Stdcall} calling convention described above.
27440
27441 @node DLL Calling Convention
27442 @subsection @code{DLL} Calling Convention
27443
27444 @noindent
27445 This convention, which is GNAT-specific is fully equivalent to the
27446 @code{Stdcall} calling convention described above.
27447
27448 @node Introduction to Dynamic Link Libraries (DLLs)
27449 @section Introduction to Dynamic Link Libraries (DLLs)
27450 @findex DLL
27451
27452 @noindent
27453 A Dynamically Linked Library (DLL) is a library that can be shared by
27454 several applications running under Windows. A DLL can contain any number of
27455 routines and variables.
27456
27457 One advantage of DLLs is that you can change and enhance them without
27458 forcing all the applications that depend on them to be relinked or
27459 recompiled. However, you should be aware than all calls to DLL routines are
27460 slower since, as you will understand below, such calls are indirect.
27461
27462 To illustrate the remainder of this section, suppose that an application
27463 wants to use the services of a DLL @file{API.dll}. To use the services
27464 provided by @file{API.dll} you must statically link against the DLL or
27465 an import library which contains a jump table with an entry for each
27466 routine and variable exported by the DLL. In the Microsoft world this
27467 import library is called @file{API.lib}. When using GNAT this import
27468 library is called either @file{libAPI.dll.a}, @file{libapi.dll.a},
27469 @file{libAPI.a} or @file{libapi.a} (names are case insensitive).
27470
27471 After you have linked your application with the DLL or the import library
27472 and you run your application, here is what happens:
27473
27474 @enumerate
27475 @item
27476 Your application is loaded into memory.
27477
27478 @item
27479 The DLL @file{API.dll} is mapped into the address space of your
27480 application. This means that:
27481
27482 @itemize @bullet
27483 @item
27484 The DLL will use the stack of the calling thread.
27485
27486 @item
27487 The DLL will use the virtual address space of the calling process.
27488
27489 @item
27490 The DLL will allocate memory from the virtual address space of the calling
27491 process.
27492
27493 @item
27494 Handles (pointers) can be safely exchanged between routines in the DLL
27495 routines and routines in the application using the DLL.
27496 @end itemize
27497
27498 @item
27499 The entries in the jump table (from the import library @file{libAPI.dll.a}
27500 or @file{API.lib} or automatically created when linking against a DLL)
27501 which is part of your application are initialized with the addresses
27502 of the routines and variables in @file{API.dll}.
27503
27504 @item
27505 If present in @file{API.dll}, routines @code{DllMain} or
27506 @code{DllMainCRTStartup} are invoked. These routines typically contain
27507 the initialization code needed for the well-being of the routines and
27508 variables exported by the DLL.
27509 @end enumerate
27510
27511 @noindent
27512 There is an additional point which is worth mentioning. In the Windows
27513 world there are two kind of DLLs: relocatable and non-relocatable
27514 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
27515 in the target application address space. If the addresses of two
27516 non-relocatable DLLs overlap and these happen to be used by the same
27517 application, a conflict will occur and the application will run
27518 incorrectly. Hence, when possible, it is always preferable to use and
27519 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
27520 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
27521 User's Guide) removes the debugging symbols from the DLL but the DLL can
27522 still be relocated.
27523
27524 As a side note, an interesting difference between Microsoft DLLs and
27525 Unix shared libraries, is the fact that on most Unix systems all public
27526 routines are exported by default in a Unix shared library, while under
27527 Windows it is possible (but not required) to list exported routines in
27528 a definition file (@pxref{The Definition File}).
27529
27530 @node Using DLLs with GNAT
27531 @section Using DLLs with GNAT
27532
27533 @menu
27534 * Creating an Ada Spec for the DLL Services::
27535 * Creating an Import Library::
27536 @end menu
27537
27538 @noindent
27539 To use the services of a DLL, say @file{API.dll}, in your Ada application
27540 you must have:
27541
27542 @enumerate
27543 @item
27544 The Ada spec for the routines and/or variables you want to access in
27545 @file{API.dll}. If not available this Ada spec must be built from the C/C++
27546 header files provided with the DLL.
27547
27548 @item
27549 The import library (@file{libAPI.dll.a} or @file{API.lib}). As previously
27550 mentioned an import library is a statically linked library containing the
27551 import table which will be filled at load time to point to the actual
27552 @file{API.dll} routines. Sometimes you don't have an import library for the
27553 DLL you want to use. The following sections will explain how to build
27554 one. Note that this is optional.
27555
27556 @item
27557 The actual DLL, @file{API.dll}.
27558 @end enumerate
27559
27560 @noindent
27561 Once you have all the above, to compile an Ada application that uses the
27562 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
27563 you simply issue the command
27564
27565 @smallexample
27566 $ gnatmake my_ada_app -largs -lAPI
27567 @end smallexample
27568
27569 @noindent
27570 The argument @option{-largs -lAPI} at the end of the @command{gnatmake} command
27571 tells the GNAT linker to look for an import library. The linker will
27572 look for a library name in this specific order:
27573
27574 @enumerate
27575 @item @file{libAPI.dll.a}
27576 @item @file{API.dll.a}
27577 @item @file{libAPI.a}
27578 @item @file{API.lib}
27579 @item @file{libAPI.dll}
27580 @item @file{API.dll}
27581 @end enumerate
27582
27583 The first three are the GNU style import libraries. The third is the
27584 Microsoft style import libraries. The last two are the actual DLL names.
27585
27586 Note that if the Ada package spec for @file{API.dll} contains the
27587 following pragma
27588
27589 @smallexample @c ada
27590 pragma Linker_Options ("-lAPI");
27591 @end smallexample
27592
27593 @noindent
27594 you do not have to add @option{-largs -lAPI} at the end of the
27595 @command{gnatmake} command.
27596
27597 If any one of the items above is missing you will have to create it
27598 yourself. The following sections explain how to do so using as an
27599 example a fictitious DLL called @file{API.dll}.
27600
27601 @node Creating an Ada Spec for the DLL Services
27602 @subsection Creating an Ada Spec for the DLL Services
27603
27604 @noindent
27605 A DLL typically comes with a C/C++ header file which provides the
27606 definitions of the routines and variables exported by the DLL. The Ada
27607 equivalent of this header file is a package spec that contains definitions
27608 for the imported entities. If the DLL you intend to use does not come with
27609 an Ada spec you have to generate one such spec yourself. For example if
27610 the header file of @file{API.dll} is a file @file{api.h} containing the
27611 following two definitions:
27612
27613 @smallexample
27614 @group
27615 @cartouche
27616 int some_var;
27617 int get (char *);
27618 @end cartouche
27619 @end group
27620 @end smallexample
27621
27622 @noindent
27623 then the equivalent Ada spec could be:
27624
27625 @smallexample @c ada
27626 @group
27627 @cartouche
27628 with Interfaces.C.Strings;
27629 package API is
27630    use Interfaces;
27631
27632    Some_Var : C.int;
27633    function Get (Str : C.Strings.Chars_Ptr) return C.int;
27634
27635 private
27636    pragma Import (C, Get);
27637    pragma Import (DLL, Some_Var);
27638 end API;
27639 @end cartouche
27640 @end group
27641 @end smallexample
27642
27643 @noindent
27644 Note that a variable is
27645 @strong{always imported with a DLL convention}. A function
27646 can have @code{C} or @code{Stdcall} convention.
27647 (@pxref{Windows Calling Conventions}).
27648
27649 @node Creating an Import Library
27650 @subsection Creating an Import Library
27651 @cindex Import library
27652
27653 @menu
27654 * The Definition File::
27655 * GNAT-Style Import Library::
27656 * Microsoft-Style Import Library::
27657 @end menu
27658
27659 @noindent
27660 If a Microsoft-style import library @file{API.lib} or a GNAT-style
27661 import library @file{libAPI.dll.a} or @file{libAPI.a} is available
27662 with @file{API.dll} you can skip this section. You can also skip this
27663 section if @file{API.dll} or @file{libAPI.dll} is built with GNU tools
27664 as in this case it is possible to link directly against the
27665 DLL. Otherwise read on.
27666
27667 @node The Definition File
27668 @subsubsection The Definition File
27669 @cindex Definition file
27670 @findex .def
27671
27672 @noindent
27673 As previously mentioned, and unlike Unix systems, the list of symbols
27674 that are exported from a DLL must be provided explicitly in Windows.
27675 The main goal of a definition file is precisely that: list the symbols
27676 exported by a DLL. A definition file (usually a file with a @code{.def}
27677 suffix) has the following structure:
27678
27679 @smallexample
27680 @group
27681 @cartouche
27682 @r{[}LIBRARY @var{name}@r{]}
27683 @r{[}DESCRIPTION @var{string}@r{]}
27684 EXPORTS
27685    @var{symbol1}
27686    @var{symbol2}
27687    @dots{}
27688 @end cartouche
27689 @end group
27690 @end smallexample
27691
27692 @table @code
27693 @item LIBRARY @var{name}
27694 This section, which is optional, gives the name of the DLL.
27695
27696 @item DESCRIPTION @var{string}
27697 This section, which is optional, gives a description string that will be
27698 embedded in the import library.
27699
27700 @item EXPORTS
27701 This section gives the list of exported symbols (procedures, functions or
27702 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
27703 section of @file{API.def} looks like:
27704
27705 @smallexample
27706 @group
27707 @cartouche
27708 EXPORTS
27709    some_var
27710    get
27711 @end cartouche
27712 @end group
27713 @end smallexample
27714 @end table
27715
27716 @noindent
27717 Note that you must specify the correct suffix (@code{@@}@code{@var{nn}})
27718 (@pxref{Windows Calling Conventions}) for a Stdcall
27719 calling convention function in the exported symbols list.
27720
27721 @noindent
27722 There can actually be other sections in a definition file, but these
27723 sections are not relevant to the discussion at hand.
27724
27725 @node GNAT-Style Import Library
27726 @subsubsection GNAT-Style Import Library
27727
27728 @noindent
27729 To create a static import library from @file{API.dll} with the GNAT tools
27730 you should proceed as follows:
27731
27732 @enumerate
27733 @item
27734 Create the definition file @file{API.def} (@pxref{The Definition File}).
27735 For that use the @code{dll2def} tool as follows:
27736
27737 @smallexample
27738 $ dll2def API.dll > API.def
27739 @end smallexample
27740
27741 @noindent
27742 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
27743 to standard output the list of entry points in the DLL. Note that if
27744 some routines in the DLL have the @code{Stdcall} convention
27745 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@var{nn}
27746 suffix then you'll have to edit @file{api.def} to add it, and specify
27747 @option{-k} to @command{gnatdll} when creating the import library.
27748
27749 @noindent
27750 Here are some hints to find the right @code{@@}@var{nn} suffix.
27751
27752 @enumerate
27753 @item
27754 If you have the Microsoft import library (.lib), it is possible to get
27755 the right symbols by using Microsoft @code{dumpbin} tool (see the
27756 corresponding Microsoft documentation for further details).
27757
27758 @smallexample
27759 $ dumpbin /exports api.lib
27760 @end smallexample
27761
27762 @item
27763 If you have a message about a missing symbol at link time the compiler
27764 tells you what symbol is expected. You just have to go back to the
27765 definition file and add the right suffix.
27766 @end enumerate
27767
27768 @item
27769 Build the import library @code{libAPI.dll.a}, using @code{gnatdll}
27770 (@pxref{Using gnatdll}) as follows:
27771
27772 @smallexample
27773 $ gnatdll -e API.def -d API.dll
27774 @end smallexample
27775
27776 @noindent
27777 @code{gnatdll} takes as input a definition file @file{API.def} and the
27778 name of the DLL containing the services listed in the definition file
27779 @file{API.dll}. The name of the static import library generated is
27780 computed from the name of the definition file as follows: if the
27781 definition file name is @var{xyz}@code{.def}, the import library name will
27782 be @code{lib}@var{xyz}@code{.a}. Note that in the previous example option
27783 @option{-e} could have been removed because the name of the definition
27784 file (before the ``@code{.def}'' suffix) is the same as the name of the
27785 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
27786 @end enumerate
27787
27788 @node Microsoft-Style Import Library
27789 @subsubsection Microsoft-Style Import Library
27790
27791 @noindent
27792 With GNAT you can either use a GNAT-style or Microsoft-style import
27793 library. A Microsoft import library is needed only if you plan to make an
27794 Ada DLL available to applications developed with Microsoft
27795 tools (@pxref{Mixed-Language Programming on Windows}).
27796
27797 To create a Microsoft-style import library for @file{API.dll} you
27798 should proceed as follows:
27799
27800 @enumerate
27801 @item
27802 Create the definition file @file{API.def} from the DLL. For this use either
27803 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
27804 tool (see the corresponding Microsoft documentation for further details).
27805
27806 @item
27807 Build the actual import library using Microsoft's @code{lib} utility:
27808
27809 @smallexample
27810 $ lib -machine:IX86 -def:API.def -out:API.lib
27811 @end smallexample
27812
27813 @noindent
27814 If you use the above command the definition file @file{API.def} must
27815 contain a line giving the name of the DLL:
27816
27817 @smallexample
27818 LIBRARY      "API"
27819 @end smallexample
27820
27821 @noindent
27822 See the Microsoft documentation for further details about the usage of
27823 @code{lib}.
27824 @end enumerate
27825
27826 @node Building DLLs with GNAT Project files
27827 @section Building DLLs with GNAT Project files
27828 @cindex DLLs, building
27829
27830 @noindent
27831 There is nothing specific to Windows in the build process.
27832 @pxref{Library Projects}.
27833
27834 @noindent
27835 Due to a system limitation, it is not possible under Windows to create threads
27836 when inside the @code{DllMain} routine which is used for auto-initialization
27837 of shared libraries, so it is not possible to have library level tasks in SALs.
27838
27839 @node Building DLLs with GNAT
27840 @section Building DLLs with GNAT
27841 @cindex DLLs, building
27842
27843 @noindent
27844 This section explain how to build DLLs using the GNAT built-in DLL
27845 support. With the following procedure it is straight forward to build
27846 and use DLLs with GNAT.
27847
27848 @enumerate
27849
27850 @item building object files
27851
27852 The first step is to build all objects files that are to be included
27853 into the DLL. This is done by using the standard @command{gnatmake} tool.
27854
27855 @item building the DLL
27856
27857 To build the DLL you must use @command{gcc}'s @option{-shared} and
27858 @option{-shared-libgcc} options. It is quite simple to use this method:
27859
27860 @smallexample
27861 $ gcc -shared -shared-libgcc -o api.dll obj1.o obj2.o @dots{}
27862 @end smallexample
27863
27864 It is important to note that in this case all symbols found in the
27865 object files are automatically exported. It is possible to restrict
27866 the set of symbols to export by passing to @command{gcc} a definition
27867 file, @pxref{The Definition File}. For example:
27868
27869 @smallexample
27870 $ gcc -shared -shared-libgcc -o api.dll api.def obj1.o obj2.o @dots{}
27871 @end smallexample
27872
27873 If you use a definition file you must export the elaboration procedures
27874 for every package that required one. Elaboration procedures are named
27875 using the package name followed by "_E".
27876
27877 @item preparing DLL to be used
27878
27879 For the DLL to be used by client programs the bodies must be hidden
27880 from it and the .ali set with read-only attribute. This is very important
27881 otherwise GNAT will recompile all packages and will not actually use
27882 the code in the DLL. For example:
27883
27884 @smallexample
27885 $ mkdir apilib
27886 $ copy *.ads *.ali api.dll apilib
27887 $ attrib +R apilib\*.ali
27888 @end smallexample
27889
27890 @end enumerate
27891
27892 At this point it is possible to use the DLL by directly linking
27893 against it. Note that you must use the GNAT shared runtime when using
27894 GNAT shared libraries. This is achieved by using @option{-shared} binder's
27895 option.
27896
27897 @smallexample
27898 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
27899 @end smallexample
27900
27901 @node Building DLLs with gnatdll
27902 @section Building DLLs with gnatdll
27903 @cindex DLLs, building
27904
27905 @menu
27906 * Limitations When Using Ada DLLs from Ada::
27907 * Exporting Ada Entities::
27908 * Ada DLLs and Elaboration::
27909 * Ada DLLs and Finalization::
27910 * Creating a Spec for Ada DLLs::
27911 * Creating the Definition File::
27912 * Using gnatdll::
27913 @end menu
27914
27915 @noindent
27916 Note that it is preferred to use GNAT Project files
27917 (@pxref{Building DLLs with GNAT Project files}) or the built-in GNAT
27918 DLL support (@pxref{Building DLLs with GNAT}) or to build DLLs.
27919
27920 This section explains how to build DLLs containing Ada code using
27921 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
27922 remainder of this section.
27923
27924 The steps required to build an Ada DLL that is to be used by Ada as well as
27925 non-Ada applications are as follows:
27926
27927 @enumerate
27928 @item
27929 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
27930 @code{Stdcall} calling convention to avoid any Ada name mangling for the
27931 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
27932 skip this step if you plan to use the Ada DLL only from Ada applications.
27933
27934 @item
27935 Your Ada code must export an initialization routine which calls the routine
27936 @code{adainit} generated by @command{gnatbind} to perform the elaboration of
27937 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
27938 routine exported by the Ada DLL must be invoked by the clients of the DLL
27939 to initialize the DLL.
27940
27941 @item
27942 When useful, the DLL should also export a finalization routine which calls
27943 routine @code{adafinal} generated by @command{gnatbind} to perform the
27944 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
27945 The finalization routine exported by the Ada DLL must be invoked by the
27946 clients of the DLL when the DLL services are no further needed.
27947
27948 @item
27949 You must provide a spec for the services exported by the Ada DLL in each
27950 of the programming languages to which you plan to make the DLL available.
27951
27952 @item
27953 You must provide a definition file listing the exported entities
27954 (@pxref{The Definition File}).
27955
27956 @item
27957 Finally you must use @code{gnatdll} to produce the DLL and the import
27958 library (@pxref{Using gnatdll}).
27959 @end enumerate
27960
27961 @noindent
27962 Note that a relocatable DLL stripped using the @code{strip}
27963 binutils tool will not be relocatable anymore. To build a DLL without
27964 debug information pass @code{-largs -s} to @code{gnatdll}. This
27965 restriction does not apply to a DLL built using a Library Project.
27966 @pxref{Library Projects}.
27967
27968 @node Limitations When Using Ada DLLs from Ada
27969 @subsection Limitations When Using Ada DLLs from Ada
27970
27971 @noindent
27972 When using Ada DLLs from Ada applications there is a limitation users
27973 should be aware of. Because on Windows the GNAT run time is not in a DLL of
27974 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
27975 each Ada DLL includes the services of the GNAT run time that are necessary
27976 to the Ada code inside the DLL. As a result, when an Ada program uses an
27977 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
27978 one in the main program.
27979
27980 It is therefore not possible to exchange GNAT run-time objects between the
27981 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
27982 handles (e.g.@: @code{Text_IO.File_Type}), tasks types, protected objects
27983 types, etc.
27984
27985 It is completely safe to exchange plain elementary, array or record types,
27986 Windows object handles, etc.
27987
27988 @node Exporting Ada Entities
27989 @subsection Exporting Ada Entities
27990 @cindex Export table
27991
27992 @noindent
27993 Building a DLL is a way to encapsulate a set of services usable from any
27994 application. As a result, the Ada entities exported by a DLL should be
27995 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
27996 any Ada name mangling. As an example here is an Ada package
27997 @code{API}, spec and body, exporting two procedures, a function, and a
27998 variable:
27999
28000 @smallexample @c ada
28001 @group
28002 @cartouche
28003 with Interfaces.C; use Interfaces;
28004 package API is
28005    Count : C.int := 0;
28006    function Factorial (Val : C.int) return C.int;
28007
28008    procedure Initialize_API;
28009    procedure Finalize_API;
28010    --  Initialization & Finalization routines. More in the next section.
28011 private
28012    pragma Export (C, Initialize_API);
28013    pragma Export (C, Finalize_API);
28014    pragma Export (C, Count);
28015    pragma Export (C, Factorial);
28016 end API;
28017 @end cartouche
28018 @end group
28019 @end smallexample
28020
28021 @smallexample @c ada
28022 @group
28023 @cartouche
28024 package body API is
28025    function Factorial (Val : C.int) return C.int is
28026       Fact : C.int := 1;
28027    begin
28028       Count := Count + 1;
28029       for K in 1 .. Val loop
28030          Fact := Fact * K;
28031       end loop;
28032       return Fact;
28033    end Factorial;
28034
28035    procedure Initialize_API is
28036       procedure Adainit;
28037       pragma Import (C, Adainit);
28038    begin
28039       Adainit;
28040    end Initialize_API;
28041
28042    procedure Finalize_API is
28043       procedure Adafinal;
28044       pragma Import (C, Adafinal);
28045    begin
28046       Adafinal;
28047    end Finalize_API;
28048 end API;
28049 @end cartouche
28050 @end group
28051 @end smallexample
28052
28053 @noindent
28054 If the Ada DLL you are building will only be used by Ada applications
28055 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
28056 convention. As an example, the previous package could be written as
28057 follows:
28058
28059 @smallexample @c ada
28060 @group
28061 @cartouche
28062 package API is
28063    Count : Integer := 0;
28064    function Factorial (Val : Integer) return Integer;
28065
28066    procedure Initialize_API;
28067    procedure Finalize_API;
28068    --  Initialization and Finalization routines.
28069 end API;
28070 @end cartouche
28071 @end group
28072 @end smallexample
28073
28074 @smallexample @c ada
28075 @group
28076 @cartouche
28077 package body API is
28078    function Factorial (Val : Integer) return Integer is
28079       Fact : Integer := 1;
28080    begin
28081       Count := Count + 1;
28082       for K in 1 .. Val loop
28083          Fact := Fact * K;
28084       end loop;
28085       return Fact;
28086    end Factorial;
28087
28088    @dots{}
28089    --  The remainder of this package body is unchanged.
28090 end API;
28091 @end cartouche
28092 @end group
28093 @end smallexample
28094
28095 @noindent
28096 Note that if you do not export the Ada entities with a @code{C} or
28097 @code{Stdcall} convention you will have to provide the mangled Ada names
28098 in the definition file of the Ada DLL
28099 (@pxref{Creating the Definition File}).
28100
28101 @node Ada DLLs and Elaboration
28102 @subsection Ada DLLs and Elaboration
28103 @cindex DLLs and elaboration
28104
28105 @noindent
28106 The DLL that you are building contains your Ada code as well as all the
28107 routines in the Ada library that are needed by it. The first thing a
28108 user of your DLL must do is elaborate the Ada code
28109 (@pxref{Elaboration Order Handling in GNAT}).
28110
28111 To achieve this you must export an initialization routine
28112 (@code{Initialize_API} in the previous example), which must be invoked
28113 before using any of the DLL services. This elaboration routine must call
28114 the Ada elaboration routine @code{adainit} generated by the GNAT binder
28115 (@pxref{Binding with Non-Ada Main Programs}). See the body of
28116 @code{Initialize_Api} for an example. Note that the GNAT binder is
28117 automatically invoked during the DLL build process by the @code{gnatdll}
28118 tool (@pxref{Using gnatdll}).
28119
28120 When a DLL is loaded, Windows systematically invokes a routine called
28121 @code{DllMain}. It would therefore be possible to call @code{adainit}
28122 directly from @code{DllMain} without having to provide an explicit
28123 initialization routine. Unfortunately, it is not possible to call
28124 @code{adainit} from the @code{DllMain} if your program has library level
28125 tasks because access to the @code{DllMain} entry point is serialized by
28126 the system (that is, only a single thread can execute ``through'' it at a
28127 time), which means that the GNAT run time will deadlock waiting for the
28128 newly created task to complete its initialization.
28129
28130 @node Ada DLLs and Finalization
28131 @subsection Ada DLLs and Finalization
28132 @cindex DLLs and finalization
28133
28134 @noindent
28135 When the services of an Ada DLL are no longer needed, the client code should
28136 invoke the DLL finalization routine, if available. The DLL finalization
28137 routine is in charge of releasing all resources acquired by the DLL. In the
28138 case of the Ada code contained in the DLL, this is achieved by calling
28139 routine @code{adafinal} generated by the GNAT binder
28140 (@pxref{Binding with Non-Ada Main Programs}).
28141 See the body of @code{Finalize_Api} for an
28142 example. As already pointed out the GNAT binder is automatically invoked
28143 during the DLL build process by the @code{gnatdll} tool
28144 (@pxref{Using gnatdll}).
28145
28146 @node Creating a Spec for Ada DLLs
28147 @subsection Creating a Spec for Ada DLLs
28148
28149 @noindent
28150 To use the services exported by the Ada DLL from another programming
28151 language (e.g.@: C), you have to translate the specs of the exported Ada
28152 entities in that language. For instance in the case of @code{API.dll},
28153 the corresponding C header file could look like:
28154
28155 @smallexample
28156 @group
28157 @cartouche
28158 extern int *_imp__count;
28159 #define count (*_imp__count)
28160 int factorial (int);
28161 @end cartouche
28162 @end group
28163 @end smallexample
28164
28165 @noindent
28166 It is important to understand that when building an Ada DLL to be used by
28167 other Ada applications, you need two different specs for the packages
28168 contained in the DLL: one for building the DLL and the other for using
28169 the DLL. This is because the @code{DLL} calling convention is needed to
28170 use a variable defined in a DLL, but when building the DLL, the variable
28171 must have either the @code{Ada} or @code{C} calling convention. As an
28172 example consider a DLL comprising the following package @code{API}:
28173
28174 @smallexample @c ada
28175 @group
28176 @cartouche
28177 package API is
28178    Count : Integer := 0;
28179    @dots{}
28180    --  Remainder of the package omitted.
28181 end API;
28182 @end cartouche
28183 @end group
28184 @end smallexample
28185
28186 @noindent
28187 After producing a DLL containing package @code{API}, the spec that
28188 must be used to import @code{API.Count} from Ada code outside of the
28189 DLL is:
28190
28191 @smallexample @c ada
28192 @group
28193 @cartouche
28194 package API is
28195    Count : Integer;
28196    pragma Import (DLL, Count);
28197 end API;
28198 @end cartouche
28199 @end group
28200 @end smallexample
28201
28202 @node Creating the Definition File
28203 @subsection Creating the Definition File
28204
28205 @noindent
28206 The definition file is the last file needed to build the DLL. It lists
28207 the exported symbols. As an example, the definition file for a DLL
28208 containing only package @code{API} (where all the entities are exported
28209 with a @code{C} calling convention) is:
28210
28211 @smallexample
28212 @group
28213 @cartouche
28214 EXPORTS
28215     count
28216     factorial
28217     finalize_api
28218     initialize_api
28219 @end cartouche
28220 @end group
28221 @end smallexample
28222
28223 @noindent
28224 If the @code{C} calling convention is missing from package @code{API},
28225 then the definition file contains the mangled Ada names of the above
28226 entities, which in this case are:
28227
28228 @smallexample
28229 @group
28230 @cartouche
28231 EXPORTS
28232     api__count
28233     api__factorial
28234     api__finalize_api
28235     api__initialize_api
28236 @end cartouche
28237 @end group
28238 @end smallexample
28239
28240 @node Using gnatdll
28241 @subsection Using @code{gnatdll}
28242 @findex gnatdll
28243
28244 @menu
28245 * gnatdll Example::
28246 * gnatdll behind the Scenes::
28247 * Using dlltool::
28248 @end menu
28249
28250 @noindent
28251 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
28252 and non-Ada sources that make up your DLL have been compiled.
28253 @code{gnatdll} is actually in charge of two distinct tasks: build the
28254 static import library for the DLL and the actual DLL. The form of the
28255 @code{gnatdll} command is
28256
28257 @smallexample
28258 @cartouche
28259 @c $ gnatdll @ovar{switches} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
28260 @c Expanding @ovar macro inline (explanation in macro def comments)
28261 $ gnatdll @r{[}@var{switches}@r{]} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
28262 @end cartouche
28263 @end smallexample
28264
28265 @noindent
28266 where @var{list-of-files} is a list of ALI and object files. The object
28267 file list must be the exact list of objects corresponding to the non-Ada
28268 sources whose services are to be included in the DLL. The ALI file list
28269 must be the exact list of ALI files for the corresponding Ada sources
28270 whose services are to be included in the DLL. If @var{list-of-files} is
28271 missing, only the static import library is generated.
28272
28273 @noindent
28274 You may specify any of the following switches to @code{gnatdll}:
28275
28276 @table @code
28277 @c @item -a@ovar{address}
28278 @c Expanding @ovar macro inline (explanation in macro def comments)
28279 @item -a@r{[}@var{address}@r{]}
28280 @cindex @option{-a} (@code{gnatdll})
28281 Build a non-relocatable DLL at @var{address}. If @var{address} is not
28282 specified the default address @var{0x11000000} will be used. By default,
28283 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
28284 advise the reader to build relocatable DLL.
28285
28286 @item -b @var{address}
28287 @cindex @option{-b} (@code{gnatdll})
28288 Set the relocatable DLL base address. By default the address is
28289 @code{0x11000000}.
28290
28291 @item -bargs @var{opts}
28292 @cindex @option{-bargs} (@code{gnatdll})
28293 Binder options. Pass @var{opts} to the binder.
28294
28295 @item -d @var{dllfile}
28296 @cindex @option{-d} (@code{gnatdll})
28297 @var{dllfile} is the name of the DLL. This switch must be present for
28298 @code{gnatdll} to do anything. The name of the generated import library is
28299 obtained algorithmically from @var{dllfile} as shown in the following
28300 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
28301 @code{libxyz.dll.a}. The name of the definition file to use (if not specified
28302 by option @option{-e}) is obtained algorithmically from @var{dllfile}
28303 as shown in the following example:
28304 if @var{dllfile} is @code{xyz.dll}, the definition
28305 file used is @code{xyz.def}.
28306
28307 @item -e @var{deffile}
28308 @cindex @option{-e} (@code{gnatdll})
28309 @var{deffile} is the name of the definition file.
28310
28311 @item -g
28312 @cindex @option{-g} (@code{gnatdll})
28313 Generate debugging information. This information is stored in the object
28314 file and copied from there to the final DLL file by the linker,
28315 where it can be read by the debugger. You must use the
28316 @option{-g} switch if you plan on using the debugger or the symbolic
28317 stack traceback.
28318
28319 @item -h
28320 @cindex @option{-h} (@code{gnatdll})
28321 Help mode. Displays @code{gnatdll} switch usage information.
28322
28323 @item -Idir
28324 @cindex @option{-I} (@code{gnatdll})
28325 Direct @code{gnatdll} to search the @var{dir} directory for source and
28326 object files needed to build the DLL.
28327 (@pxref{Search Paths and the Run-Time Library (RTL)}).
28328
28329 @item -k
28330 @cindex @option{-k} (@code{gnatdll})
28331 Removes the @code{@@}@var{nn} suffix from the import library's exported
28332 names, but keeps them for the link names. You must specify this
28333 option if you want to use a @code{Stdcall} function in a DLL for which
28334 the @code{@@}@var{nn} suffix has been removed. This is the case for most
28335 of the Windows NT DLL for example. This option has no effect when
28336 @option{-n} option is specified.
28337
28338 @item -l @var{file}
28339 @cindex @option{-l} (@code{gnatdll})
28340 The list of ALI and object files used to build the DLL are listed in
28341 @var{file}, instead of being given in the command line. Each line in
28342 @var{file} contains the name of an ALI or object file.
28343
28344 @item -n
28345 @cindex @option{-n} (@code{gnatdll})
28346 No Import. Do not create the import library.
28347
28348 @item -q
28349 @cindex @option{-q} (@code{gnatdll})
28350 Quiet mode. Do not display unnecessary messages.
28351
28352 @item -v
28353 @cindex @option{-v} (@code{gnatdll})
28354 Verbose mode. Display extra information.
28355
28356 @item -largs @var{opts}
28357 @cindex @option{-largs} (@code{gnatdll})
28358 Linker options. Pass @var{opts} to the linker.
28359 @end table
28360
28361 @node gnatdll Example
28362 @subsubsection @code{gnatdll} Example
28363
28364 @noindent
28365 As an example the command to build a relocatable DLL from @file{api.adb}
28366 once @file{api.adb} has been compiled and @file{api.def} created is
28367
28368 @smallexample
28369 $ gnatdll -d api.dll api.ali
28370 @end smallexample
28371
28372 @noindent
28373 The above command creates two files: @file{libapi.dll.a} (the import
28374 library) and @file{api.dll} (the actual DLL). If you want to create
28375 only the DLL, just type:
28376
28377 @smallexample
28378 $ gnatdll -d api.dll -n api.ali
28379 @end smallexample
28380
28381 @noindent
28382 Alternatively if you want to create just the import library, type:
28383
28384 @smallexample
28385 $ gnatdll -d api.dll
28386 @end smallexample
28387
28388 @node gnatdll behind the Scenes
28389 @subsubsection @code{gnatdll} behind the Scenes
28390
28391 @noindent
28392 This section details the steps involved in creating a DLL. @code{gnatdll}
28393 does these steps for you. Unless you are interested in understanding what
28394 goes on behind the scenes, you should skip this section.
28395
28396 We use the previous example of a DLL containing the Ada package @code{API},
28397 to illustrate the steps necessary to build a DLL. The starting point is a
28398 set of objects that will make up the DLL and the corresponding ALI
28399 files. In the case of this example this means that @file{api.o} and
28400 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
28401 the following:
28402
28403 @enumerate
28404 @item
28405 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
28406 the information necessary to generate relocation information for the
28407 DLL.
28408
28409 @smallexample
28410 @group
28411 $ gnatbind -n api
28412 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
28413 @end group
28414 @end smallexample
28415
28416 @noindent
28417 In addition to the base file, the @command{gnatlink} command generates an
28418 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
28419 asks @command{gnatlink} to generate the routines @code{DllMain} and
28420 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
28421 is loaded into memory.
28422
28423 @item
28424 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
28425 export table (@file{api.exp}). The export table contains the relocation
28426 information in a form which can be used during the final link to ensure
28427 that the Windows loader is able to place the DLL anywhere in memory.
28428
28429 @smallexample
28430 @group
28431 $ dlltool --dllname api.dll --def api.def --base-file api.base \
28432           --output-exp api.exp
28433 @end group
28434 @end smallexample
28435
28436 @item
28437 @code{gnatdll} builds the base file using the new export table. Note that
28438 @command{gnatbind} must be called once again since the binder generated file
28439 has been deleted during the previous call to @command{gnatlink}.
28440
28441 @smallexample
28442 @group
28443 $ gnatbind -n api
28444 $ gnatlink api -o api.jnk api.exp -mdll
28445       -Wl,--base-file,api.base
28446 @end group
28447 @end smallexample
28448
28449 @item
28450 @code{gnatdll} builds the new export table using the new base file and
28451 generates the DLL import library @file{libAPI.dll.a}.
28452
28453 @smallexample
28454 @group
28455 $ dlltool --dllname api.dll --def api.def --base-file api.base \
28456           --output-exp api.exp --output-lib libAPI.a
28457 @end group
28458 @end smallexample
28459
28460 @item
28461 Finally @code{gnatdll} builds the relocatable DLL using the final export
28462 table.
28463
28464 @smallexample
28465 @group
28466 $ gnatbind -n api
28467 $ gnatlink api api.exp -o api.dll -mdll
28468 @end group
28469 @end smallexample
28470 @end enumerate
28471
28472 @node Using dlltool
28473 @subsubsection Using @code{dlltool}
28474
28475 @noindent
28476 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
28477 DLLs and static import libraries. This section summarizes the most
28478 common @code{dlltool} switches. The form of the @code{dlltool} command
28479 is
28480
28481 @smallexample
28482 @c $ dlltool @ovar{switches}
28483 @c Expanding @ovar macro inline (explanation in macro def comments)
28484 $ dlltool @r{[}@var{switches}@r{]}
28485 @end smallexample
28486
28487 @noindent
28488 @code{dlltool} switches include:
28489
28490 @table @option
28491 @item --base-file @var{basefile}
28492 @cindex @option{--base-file} (@command{dlltool})
28493 Read the base file @var{basefile} generated by the linker. This switch
28494 is used to create a relocatable DLL.
28495
28496 @item --def @var{deffile}
28497 @cindex @option{--def} (@command{dlltool})
28498 Read the definition file.
28499
28500 @item --dllname @var{name}
28501 @cindex @option{--dllname} (@command{dlltool})
28502 Gives the name of the DLL. This switch is used to embed the name of the
28503 DLL in the static import library generated by @code{dlltool} with switch
28504 @option{--output-lib}.
28505
28506 @item -k
28507 @cindex @option{-k} (@command{dlltool})
28508 Kill @code{@@}@var{nn} from exported names
28509 (@pxref{Windows Calling Conventions}
28510 for a discussion about @code{Stdcall}-style symbols.
28511
28512 @item --help
28513 @cindex @option{--help} (@command{dlltool})
28514 Prints the @code{dlltool} switches with a concise description.
28515
28516 @item --output-exp @var{exportfile}
28517 @cindex @option{--output-exp} (@command{dlltool})
28518 Generate an export file @var{exportfile}. The export file contains the
28519 export table (list of symbols in the DLL) and is used to create the DLL.
28520
28521 @item --output-lib @var{libfile}
28522 @cindex @option{--output-lib} (@command{dlltool})
28523 Generate a static import library @var{libfile}.
28524
28525 @item -v
28526 @cindex @option{-v} (@command{dlltool})
28527 Verbose mode.
28528
28529 @item --as @var{assembler-name}
28530 @cindex @option{--as} (@command{dlltool})
28531 Use @var{assembler-name} as the assembler. The default is @code{as}.
28532 @end table
28533
28534 @node GNAT and Windows Resources
28535 @section GNAT and Windows Resources
28536 @cindex Resources, windows
28537
28538 @menu
28539 * Building Resources::
28540 * Compiling Resources::
28541 * Using Resources::
28542 @end menu
28543
28544 @noindent
28545 Resources are an easy way to add Windows specific objects to your
28546 application. The objects that can be added as resources include:
28547
28548 @itemize @bullet
28549 @item menus
28550
28551 @item accelerators
28552
28553 @item dialog boxes
28554
28555 @item string tables
28556
28557 @item bitmaps
28558
28559 @item cursors
28560
28561 @item icons
28562
28563 @item fonts
28564
28565 @item version information
28566 @end itemize
28567
28568 For example, a version information resource can be defined as follow and
28569 embedded into an executable or DLL:
28570
28571 A version information resource can be used to embed information into an
28572 executable or a DLL. These information can be viewed using the file properties
28573 from the Windows Explorer. Here is an example of a version information
28574 resource:
28575
28576 @smallexample
28577 @group
28578 1 VERSIONINFO
28579 FILEVERSION     1,0,0,0
28580 PRODUCTVERSION  1,0,0,0
28581 BEGIN
28582   BLOCK "StringFileInfo"
28583   BEGIN
28584     BLOCK "080904E4"
28585     BEGIN
28586       VALUE "CompanyName", "My Company Name"
28587       VALUE "FileDescription", "My application"
28588       VALUE "FileVersion", "1.0"
28589       VALUE "InternalName", "my_app"
28590       VALUE "LegalCopyright", "My Name"
28591       VALUE "OriginalFilename", "my_app.exe"
28592       VALUE "ProductName", "My App"
28593       VALUE "ProductVersion", "1.0"
28594     END
28595   END
28596
28597   BLOCK "VarFileInfo"
28598   BEGIN
28599     VALUE "Translation", 0x809, 1252
28600   END
28601 END
28602 @end group
28603 @end smallexample
28604
28605 The value @code{0809} (langID) is for the U.K English language and
28606 @code{04E4} (charsetID), which is equal to @code{1252} decimal, for
28607 multilingual.
28608
28609 @noindent
28610 This section explains how to build, compile and use resources. Note that this
28611 section does not cover all resource objects, for a complete description see
28612 the corresponding Microsoft documentation.
28613
28614 @node Building Resources
28615 @subsection Building Resources
28616 @cindex Resources, building
28617
28618 @noindent
28619 A resource file is an ASCII file. By convention resource files have an
28620 @file{.rc} extension.
28621 The easiest way to build a resource file is to use Microsoft tools
28622 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
28623 @code{dlgedit.exe} to build dialogs.
28624 It is always possible to build an @file{.rc} file yourself by writing a
28625 resource script.
28626
28627 It is not our objective to explain how to write a resource file. A
28628 complete description of the resource script language can be found in the
28629 Microsoft documentation.
28630
28631 @node Compiling Resources
28632 @subsection Compiling Resources
28633 @findex rc
28634 @findex windres
28635 @cindex Resources, compiling
28636
28637 @noindent
28638 This section describes how to build a GNAT-compatible (COFF) object file
28639 containing the resources. This is done using the Resource Compiler
28640 @code{windres} as follows:
28641
28642 @smallexample
28643 $ windres -i myres.rc -o myres.o
28644 @end smallexample
28645
28646 @noindent
28647 By default @code{windres} will run @command{gcc} to preprocess the @file{.rc}
28648 file. You can specify an alternate preprocessor (usually named
28649 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
28650 parameter. A list of all possible options may be obtained by entering
28651 the command @code{windres} @option{--help}.
28652
28653 It is also possible to use the Microsoft resource compiler @code{rc.exe}
28654 to produce a @file{.res} file (binary resource file). See the
28655 corresponding Microsoft documentation for further details. In this case
28656 you need to use @code{windres} to translate the @file{.res} file to a
28657 GNAT-compatible object file as follows:
28658
28659 @smallexample
28660 $ windres -i myres.res -o myres.o
28661 @end smallexample
28662
28663 @node Using Resources
28664 @subsection Using Resources
28665 @cindex Resources, using
28666
28667 @noindent
28668 To include the resource file in your program just add the
28669 GNAT-compatible object file for the resource(s) to the linker
28670 arguments. With @command{gnatmake} this is done by using the @option{-largs}
28671 option:
28672
28673 @smallexample
28674 $ gnatmake myprog -largs myres.o
28675 @end smallexample
28676
28677 @node Debugging a DLL
28678 @section Debugging a DLL
28679 @cindex DLL debugging
28680
28681 @menu
28682 * Program and DLL Both Built with GCC/GNAT::
28683 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
28684 @end menu
28685
28686 @noindent
28687 Debugging a DLL is similar to debugging a standard program. But
28688 we have to deal with two different executable parts: the DLL and the
28689 program that uses it. We have the following four possibilities:
28690
28691 @enumerate 1
28692 @item
28693 The program and the DLL are built with @code{GCC/GNAT}.
28694 @item
28695 The program is built with foreign tools and the DLL is built with
28696 @code{GCC/GNAT}.
28697 @item
28698 The program is built with @code{GCC/GNAT} and the DLL is built with
28699 foreign tools.
28700 @end enumerate
28701
28702 @noindent
28703 In this section we address only cases one and two above.
28704 There is no point in trying to debug
28705 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
28706 information in it. To do so you must use a debugger compatible with the
28707 tools suite used to build the DLL.
28708
28709 @node Program and DLL Both Built with GCC/GNAT
28710 @subsection Program and DLL Both Built with GCC/GNAT
28711
28712 @noindent
28713 This is the simplest case. Both the DLL and the program have @code{GDB}
28714 compatible debugging information. It is then possible to break anywhere in
28715 the process. Let's suppose here that the main procedure is named
28716 @code{ada_main} and that in the DLL there is an entry point named
28717 @code{ada_dll}.
28718
28719 @noindent
28720 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
28721 program must have been built with the debugging information (see GNAT -g
28722 switch). Here are the step-by-step instructions for debugging it:
28723
28724 @enumerate 1
28725 @item Launch @code{GDB} on the main program.
28726
28727 @smallexample
28728 $ gdb -nw ada_main
28729 @end smallexample
28730
28731 @item Start the program and stop at the beginning of the main procedure
28732
28733 @smallexample
28734 (gdb) start
28735 @end smallexample
28736
28737 @noindent
28738 This step is required to be able to set a breakpoint inside the DLL. As long
28739 as the program is not run, the DLL is not loaded. This has the
28740 consequence that the DLL debugging information is also not loaded, so it is not
28741 possible to set a breakpoint in the DLL.
28742
28743 @item Set a breakpoint inside the DLL
28744
28745 @smallexample
28746 (gdb) break ada_dll
28747 (gdb) cont
28748 @end smallexample
28749
28750 @end enumerate
28751
28752 @noindent
28753 At this stage a breakpoint is set inside the DLL. From there on
28754 you can use the standard approach to debug the whole program
28755 (@pxref{Running and Debugging Ada Programs}).
28756
28757 @ignore
28758 @c This used to work, probably because the DLLs were non-relocatable
28759 @c keep this section around until the problem is sorted out.
28760
28761 To break on the @code{DllMain} routine it is not possible to follow
28762 the procedure above. At the time the program stop on @code{ada_main}
28763 the @code{DllMain} routine as already been called. Either you can use
28764 the procedure below @pxref{Debugging the DLL Directly} or this procedure:
28765
28766 @enumerate 1
28767 @item Launch @code{GDB} on the main program.
28768
28769 @smallexample
28770 $ gdb ada_main
28771 @end smallexample
28772
28773 @item Load DLL symbols
28774
28775 @smallexample
28776 (gdb) add-sym api.dll
28777 @end smallexample
28778
28779 @item Set a breakpoint inside the DLL
28780
28781 @smallexample
28782 (gdb) break ada_dll.adb:45
28783 @end smallexample
28784
28785 Note that at this point it is not possible to break using the routine symbol
28786 directly as the program is not yet running. The solution is to break
28787 on the proper line (break in @file{ada_dll.adb} line 45).
28788
28789 @item Start the program
28790
28791 @smallexample
28792 (gdb) run
28793 @end smallexample
28794
28795 @end enumerate
28796 @end ignore
28797
28798 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
28799 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
28800
28801 @menu
28802 * Debugging the DLL Directly::
28803 * Attaching to a Running Process::
28804 @end menu
28805
28806 @noindent
28807 In this case things are slightly more complex because it is not possible to
28808 start the main program and then break at the beginning to load the DLL and the
28809 associated DLL debugging information. It is not possible to break at the
28810 beginning of the program because there is no @code{GDB} debugging information,
28811 and therefore there is no direct way of getting initial control. This
28812 section addresses this issue by describing some methods that can be used
28813 to break somewhere in the DLL to debug it.
28814
28815 @noindent
28816 First suppose that the main procedure is named @code{main} (this is for
28817 example some C code built with Microsoft Visual C) and that there is a
28818 DLL named @code{test.dll} containing an Ada entry point named
28819 @code{ada_dll}.
28820
28821 @noindent
28822 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
28823 been built with debugging information (see GNAT -g option).
28824
28825 @node Debugging the DLL Directly
28826 @subsubsection Debugging the DLL Directly
28827
28828 @enumerate 1
28829 @item
28830 Find out the executable starting address
28831
28832 @smallexample
28833 $ objdump --file-header main.exe
28834 @end smallexample
28835
28836 The starting address is reported on the last line. For example:
28837
28838 @smallexample
28839 main.exe:     file format pei-i386
28840 architecture: i386, flags 0x0000010a:
28841 EXEC_P, HAS_DEBUG, D_PAGED
28842 start address 0x00401010
28843 @end smallexample
28844
28845 @item
28846 Launch the debugger on the executable.
28847
28848 @smallexample
28849 $ gdb main.exe
28850 @end smallexample
28851
28852 @item
28853 Set a breakpoint at the starting address, and launch the program.
28854
28855 @smallexample
28856 $ (gdb) break *0x00401010
28857 $ (gdb) run
28858 @end smallexample
28859
28860 The program will stop at the given address.
28861
28862 @item
28863 Set a breakpoint on a DLL subroutine.
28864
28865 @smallexample
28866 (gdb) break ada_dll.adb:45
28867 @end smallexample
28868
28869 Or if you want to break using a symbol on the DLL, you need first to
28870 select the Ada language (language used by the DLL).
28871
28872 @smallexample
28873 (gdb) set language ada
28874 (gdb) break ada_dll
28875 @end smallexample
28876
28877 @item
28878 Continue the program.
28879
28880 @smallexample
28881 (gdb) cont
28882 @end smallexample
28883
28884 @noindent
28885 This will run the program until it reaches the breakpoint that has been
28886 set. From that point you can use the standard way to debug a program
28887 as described in (@pxref{Running and Debugging Ada Programs}).
28888
28889 @end enumerate
28890
28891 @noindent
28892 It is also possible to debug the DLL by attaching to a running process.
28893
28894 @node Attaching to a Running Process
28895 @subsubsection Attaching to a Running Process
28896 @cindex DLL debugging, attach to process
28897
28898 @noindent
28899 With @code{GDB} it is always possible to debug a running process by
28900 attaching to it. It is possible to debug a DLL this way. The limitation
28901 of this approach is that the DLL must run long enough to perform the
28902 attach operation. It may be useful for instance to insert a time wasting
28903 loop in the code of the DLL to meet this criterion.
28904
28905 @enumerate 1
28906
28907 @item Launch the main program @file{main.exe}.
28908
28909 @smallexample
28910 $ main
28911 @end smallexample
28912
28913 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
28914 that the process PID for @file{main.exe} is 208.
28915
28916 @item Launch gdb.
28917
28918 @smallexample
28919 $ gdb
28920 @end smallexample
28921
28922 @item Attach to the running process to be debugged.
28923
28924 @smallexample
28925 (gdb) attach 208
28926 @end smallexample
28927
28928 @item Load the process debugging information.
28929
28930 @smallexample
28931 (gdb) symbol-file main.exe
28932 @end smallexample
28933
28934 @item Break somewhere in the DLL.
28935
28936 @smallexample
28937 (gdb) break ada_dll
28938 @end smallexample
28939
28940 @item Continue process execution.
28941
28942 @smallexample
28943 (gdb) cont
28944 @end smallexample
28945
28946 @end enumerate
28947
28948 @noindent
28949 This last step will resume the process execution, and stop at
28950 the breakpoint we have set. From there you can use the standard
28951 approach to debug a program as described in
28952 (@pxref{Running and Debugging Ada Programs}).
28953
28954 @node Setting Stack Size from gnatlink
28955 @section Setting Stack Size from @command{gnatlink}
28956
28957 @noindent
28958 It is possible to specify the program stack size at link time. On modern
28959 versions of Windows, starting with XP, this is mostly useful to set the size of
28960 the main stack (environment task). The other task stacks are set with pragma
28961 Storage_Size or with the @command{gnatbind -d} command.
28962
28963 Since older versions of Windows (2000, NT4, etc.) do not allow setting the
28964 reserve size of individual tasks, the link-time stack size applies to all
28965 tasks, and pragma Storage_Size has no effect.
28966 In particular, Stack Overflow checks are made against this
28967 link-time specified size.
28968
28969 This setting can be done with
28970 @command{gnatlink} using either:
28971
28972 @itemize @bullet
28973
28974 @item using @option{-Xlinker} linker option
28975
28976 @smallexample
28977 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
28978 @end smallexample
28979
28980 This sets the stack reserve size to 0x10000 bytes and the stack commit
28981 size to 0x1000 bytes.
28982
28983 @item using @option{-Wl} linker option
28984
28985 @smallexample
28986 $ gnatlink hello -Wl,--stack=0x1000000
28987 @end smallexample
28988
28989 This sets the stack reserve size to 0x1000000 bytes. Note that with
28990 @option{-Wl} option it is not possible to set the stack commit size
28991 because the coma is a separator for this option.
28992
28993 @end itemize
28994
28995 @node Setting Heap Size from gnatlink
28996 @section Setting Heap Size from @command{gnatlink}
28997
28998 @noindent
28999 Under Windows systems, it is possible to specify the program heap size from
29000 @command{gnatlink} using either:
29001
29002 @itemize @bullet
29003
29004 @item using @option{-Xlinker} linker option
29005
29006 @smallexample
29007 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
29008 @end smallexample
29009
29010 This sets the heap reserve size to 0x10000 bytes and the heap commit
29011 size to 0x1000 bytes.
29012
29013 @item using @option{-Wl} linker option
29014
29015 @smallexample
29016 $ gnatlink hello -Wl,--heap=0x1000000
29017 @end smallexample
29018
29019 This sets the heap reserve size to 0x1000000 bytes. Note that with
29020 @option{-Wl} option it is not possible to set the heap commit size
29021 because the coma is a separator for this option.
29022
29023 @end itemize
29024
29025 @end ifset
29026
29027 @c **********************************
29028 @c * GNU Free Documentation License *
29029 @c **********************************
29030 @include fdl.texi
29031 @c GNU Free Documentation License
29032
29033 @node Index,,GNU Free Documentation License, Top
29034 @unnumbered Index
29035
29036 @printindex cp
29037
29038 @contents
29039 @c Put table of contents at end, otherwise it precedes the "title page" in
29040 @c the .txt version
29041 @c Edit the pdf file to move the contents to the beginning, after the title
29042 @c page
29043
29044 @bye