OSDN Git Service

* gcc-interface/misc.c (gnat_expand_expr): Remove.
[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   GNAT is maintained by Ada Core Technologies Inc (http://www.gnat.com).   o
11 @c                                                                            o
12 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
13
14 @setfilename gnat_ugn.info
15
16 @copying
17 Copyright @copyright{} 1995-2005, 2006, 2007, 2008 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.2 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
111 @settitle @value{EDITION} User's Guide @value{PLATFORM}
112 @dircategory GNU Ada tools
113 @direntry
114 * @value{EDITION} User's Guide: (gnat_ugn). @value{PLATFORM}
115 @end direntry
116
117 @include gcc-common.texi
118
119 @setchapternewpage odd
120 @syncodeindex fn cp
121 @c %**end of header
122
123 @titlepage
124 @title @value{EDITION} User's Guide
125 @ifset vms
126 @sp 1
127 @flushright
128 @titlefont{@i{@value{PLATFORM}}}
129 @end flushright
130 @end ifset
131
132 @sp 2
133
134 @subtitle GNAT, The GNU Ada Compiler
135 @versionsubtitle
136 @author AdaCore
137
138 @page
139 @vskip 0pt plus 1filll
140
141 @insertcopying
142
143 @end titlepage
144
145 @ifnottex
146 @node Top, About This Guide, (dir), (dir)
147 @top @value{EDITION} User's Guide
148
149 @noindent
150 @value{EDITION} User's Guide @value{PLATFORM}
151
152 @noindent
153 GNAT, The GNU Ada Compiler@*
154 GCC version @value{version-GCC}@*
155
156 @noindent
157 AdaCore@*
158
159 @menu
160 * About This Guide::
161 * Getting Started with GNAT::
162 * The GNAT Compilation Model::
163 * Compiling Using gcc::
164 * Binding Using gnatbind::
165 * Linking Using gnatlink::
166 * The GNAT Make Program gnatmake::
167 * Improving Performance::
168 * Renaming Files Using gnatchop::
169 * Configuration Pragmas::
170 * Handling Arbitrary File Naming Conventions Using gnatname::
171 * GNAT Project Manager::
172 * The Cross-Referencing Tools gnatxref and gnatfind::
173 * The GNAT Pretty-Printer gnatpp::
174 * The GNAT Metric Tool gnatmetric::
175 * File Name Krunching Using gnatkr::
176 * Preprocessing Using gnatprep::
177 @ifset vms
178 * The GNAT Run-Time Library Builder gnatlbr::
179 @end ifset
180 * The GNAT Library Browser gnatls::
181 * Cleaning Up Using gnatclean::
182 @ifclear vms
183 * GNAT and Libraries::
184 * Using the GNU make Utility::
185 @end ifclear
186 * Memory Management Issues::
187 * Stack Related Facilities::
188 * Verifying Properties Using gnatcheck::
189 * Creating Sample Bodies Using gnatstub::
190 * Generating Ada Bindings for C and C++ headers::
191 * Other Utility Programs::
192 * Running and Debugging Ada Programs::
193 @ifclear vms
194 * Code Coverage and Profiling::
195 @end ifclear
196 @ifset vms
197 * Compatibility with HP Ada::
198 @end ifset
199 * Platform-Specific Information for the Run-Time Libraries::
200 * Example of Binder Output File::
201 * Elaboration Order Handling in GNAT::
202 * Conditional Compilation::
203 * Inline Assembler::
204 * Compatibility and Porting Guide::
205 @ifset unw
206 * Microsoft Windows Topics::
207 @end ifset
208 * GNU Free Documentation License::
209 * Index::
210
211  --- The Detailed Node Listing ---
212
213 About This Guide
214
215 * What This Guide Contains::
216 * What You Should Know before Reading This Guide::
217 * Related Information::
218 * Conventions::
219
220 Getting Started with GNAT
221
222 * Running GNAT::
223 * Running a Simple Ada Program::
224 * Running a Program with Multiple Units::
225 * Using the gnatmake Utility::
226 @ifset vms
227 * Editing with Emacs::
228 @end ifset
229 @ifclear vms
230 * Introduction to GPS::
231 @end ifclear
232
233 The GNAT Compilation Model
234
235 * Source Representation::
236 * Foreign Language Representation::
237 * File Naming Rules::
238 * Using Other File Names::
239 * Alternative File Naming Schemes::
240 * Generating Object Files::
241 * Source Dependencies::
242 * The Ada Library Information Files::
243 * Binding an Ada Program::
244 * Mixed Language Programming::
245 @ifclear vms
246 * Building Mixed Ada & C++ Programs::
247 * Comparison between GNAT and C/C++ Compilation Models::
248 @end ifclear
249 * Comparison between GNAT and Conventional Ada Library Models::
250 @ifset vms
251 * Placement of temporary files::
252 @end ifset
253
254 Foreign Language Representation
255
256 * Latin-1::
257 * Other 8-Bit Codes::
258 * Wide Character Encodings::
259
260 Compiling Ada Programs With gcc
261
262 * Compiling Programs::
263 * Switches for gcc::
264 * Search Paths and the Run-Time Library (RTL)::
265 * Order of Compilation Issues::
266 * Examples::
267
268 Switches for gcc
269
270 * Output and Error Message Control::
271 * Warning Message Control::
272 * Debugging and Assertion Control::
273 * Validity Checking::
274 * Style Checking::
275 * Run-Time Checks::
276 * Using gcc for Syntax Checking::
277 * Using gcc for Semantic Checking::
278 * Compiling Different Versions of Ada::
279 * Character Set Control::
280 * File Naming Control::
281 * Subprogram Inlining Control::
282 * Auxiliary Output Control::
283 * Debugging Control::
284 * Exception Handling Control::
285 * Units to Sources Mapping Files::
286 * Integrated Preprocessing::
287 @ifset vms
288 * Return Codes::
289 @end ifset
290
291 Binding Ada Programs With gnatbind
292
293 * Running gnatbind::
294 * Switches for gnatbind::
295 * Command-Line Access::
296 * Search Paths for gnatbind::
297 * Examples of gnatbind Usage::
298
299 Switches for gnatbind
300
301 * Consistency-Checking Modes::
302 * Binder Error Message Control::
303 * Elaboration Control::
304 * Output Control::
305 * Binding with Non-Ada Main Programs::
306 * Binding Programs with No Main Subprogram::
307
308 Linking Using gnatlink
309
310 * Running gnatlink::
311 * Switches for gnatlink::
312
313 The GNAT Make Program gnatmake
314
315 * Running gnatmake::
316 * Switches for gnatmake::
317 * Mode Switches for gnatmake::
318 * Notes on the Command Line::
319 * How gnatmake Works::
320 * Examples of gnatmake Usage::
321
322 Improving Performance
323 * Performance Considerations::
324 * Text_IO Suggestions::
325 * Reducing Size of Ada Executables with gnatelim::
326 * Reducing Size of Executables with unused subprogram/data elimination::
327
328 Performance Considerations
329 * Controlling Run-Time Checks::
330 * Use of Restrictions::
331 * Optimization Levels::
332 * Debugging Optimized Code::
333 * Inlining of Subprograms::
334 * Other Optimization Switches::
335 * Optimization and Strict Aliasing::
336 @ifset vms
337 * Coverage Analysis::
338 @end ifset
339
340 Reducing Size of Ada Executables with gnatelim
341 * About gnatelim::
342 * Running gnatelim::
343 * Correcting the List of Eliminate Pragmas::
344 * Making Your Executables Smaller::
345 * Summary of the gnatelim Usage Cycle::
346
347 Reducing Size of Executables with unused subprogram/data elimination
348 * About unused subprogram/data elimination::
349 * Compilation options::
350
351 Renaming Files Using gnatchop
352
353 * Handling Files with Multiple Units::
354 * Operating gnatchop in Compilation Mode::
355 * Command Line for gnatchop::
356 * Switches for gnatchop::
357 * Examples of gnatchop Usage::
358
359 Configuration Pragmas
360
361 * Handling of Configuration Pragmas::
362 * The Configuration Pragmas Files::
363
364 Handling Arbitrary File Naming Conventions Using gnatname
365
366 * Arbitrary File Naming Conventions::
367 * Running gnatname::
368 * Switches for gnatname::
369 * Examples of gnatname Usage::
370
371 GNAT Project Manager
372
373 * Introduction::
374 * Examples of Project Files::
375 * Project File Syntax::
376 * Objects and Sources in Project Files::
377 * Importing Projects::
378 * Project Extension::
379 * Project Hierarchy Extension::
380 * External References in Project Files::
381 * Packages in Project Files::
382 * Variables from Imported Projects::
383 * Naming Schemes::
384 * Library Projects::
385 * Stand-alone Library Projects::
386 * Switches Related to Project Files::
387 * Tools Supporting Project Files::
388 * An Extended Example::
389 * Project File Complete Syntax::
390
391 The Cross-Referencing Tools gnatxref and gnatfind
392
393 * gnatxref Switches::
394 * gnatfind Switches::
395 * Project Files for gnatxref and gnatfind::
396 * Regular Expressions in gnatfind and gnatxref::
397 * Examples of gnatxref Usage::
398 * Examples of gnatfind Usage::
399
400 The GNAT Pretty-Printer gnatpp
401
402 * Switches for gnatpp::
403 * Formatting Rules::
404
405 The GNAT Metrics Tool gnatmetric
406
407 * Switches for gnatmetric::
408
409 File Name Krunching Using gnatkr
410
411 * About gnatkr::
412 * Using gnatkr::
413 * Krunching Method::
414 * Examples of gnatkr Usage::
415
416 Preprocessing Using gnatprep
417 * Preprocessing Symbols::
418 * Using gnatprep::
419 * Switches for gnatprep::
420 * Form of Definitions File::
421 * Form of Input Text for gnatprep::
422
423 @ifset vms
424 The GNAT Run-Time Library Builder gnatlbr
425
426 * Running gnatlbr::
427 * Switches for gnatlbr::
428 * Examples of gnatlbr Usage::
429 @end ifset
430
431 The GNAT Library Browser gnatls
432
433 * Running gnatls::
434 * Switches for gnatls::
435 * Examples of gnatls Usage::
436
437 Cleaning Up Using gnatclean
438
439 * Running gnatclean::
440 * Switches for gnatclean::
441 @c * Examples of gnatclean Usage::
442
443 @ifclear vms
444
445 GNAT and Libraries
446
447 * Introduction to Libraries in GNAT::
448 * General Ada Libraries::
449 * Stand-alone Ada Libraries::
450 * Rebuilding the GNAT Run-Time Library::
451
452 Using the GNU make Utility
453
454 * Using gnatmake in a Makefile::
455 * Automatically Creating a List of Directories::
456 * Generating the Command Line Switches::
457 * Overcoming Command Line Length Limits::
458 @end ifclear
459
460 Memory Management Issues
461
462 * Some Useful Memory Pools::
463 * The GNAT Debug Pool Facility::
464 @ifclear vms
465 * The gnatmem Tool::
466 @end ifclear
467
468 Stack Related Facilities
469
470 * Stack Overflow Checking::
471 * Static Stack Usage Analysis::
472 * Dynamic Stack Usage Analysis::
473
474 Some Useful Memory Pools
475
476 The GNAT Debug Pool Facility
477
478 @ifclear vms
479 The gnatmem Tool
480
481 * Running gnatmem::
482 * Switches for gnatmem::
483 * Example of gnatmem Usage::
484 @end ifclear
485
486 Verifying Properties Using gnatcheck
487
488 * Format of the Report File::
489 * General gnatcheck Switches::
490 * gnatcheck Rule Options::
491 * Adding the Results of Compiler Checks to gnatcheck Output::
492 * Project-Wide Checks::
493 * Predefined Rules::
494
495 Sample Bodies Using gnatstub
496
497 * Running gnatstub::
498 * Switches for gnatstub::
499
500 Other Utility Programs
501
502 * Using Other Utility Programs with GNAT::
503 * The External Symbol Naming Scheme of GNAT::
504 * Converting Ada Files to html with gnathtml::
505
506 @ifclear vms
507 Code Coverage and Profiling
508
509 * Code Coverage of Ada Programs using gcov::
510 * Profiling an Ada Program using gprof::
511 @end ifclear
512
513 Running and Debugging Ada Programs
514
515 * The GNAT Debugger GDB::
516 * Running GDB::
517 * Introduction to GDB Commands::
518 * Using Ada Expressions::
519 * Calling User-Defined Subprograms::
520 * Using the Next Command in a Function::
521 * Ada Exceptions::
522 * Ada Tasks::
523 * Debugging Generic Units::
524 * GNAT Abnormal Termination or Failure to Terminate::
525 * Naming Conventions for GNAT Source Files::
526 * Getting Internal Debugging Information::
527 * Stack Traceback::
528
529 @ifset vms
530 * LSE::
531 @end ifset
532
533 @ifset vms
534 Compatibility with HP Ada
535
536 * Ada Language Compatibility::
537 * Differences in the Definition of Package System::
538 * Language-Related Features::
539 * The Package STANDARD::
540 * The Package SYSTEM::
541 * Tasking and Task-Related Features::
542 * Pragmas and Pragma-Related Features::
543 * Library of Predefined Units::
544 * Bindings::
545 * Main Program Definition::
546 * Implementation-Defined Attributes::
547 * Compiler and Run-Time Interfacing::
548 * Program Compilation and Library Management::
549 * Input-Output::
550 * Implementation Limits::
551 * Tools and Utilities::
552
553 Language-Related Features
554
555 * Integer Types and Representations::
556 * Floating-Point Types and Representations::
557 * Pragmas Float_Representation and Long_Float::
558 * Fixed-Point Types and Representations::
559 * Record and Array Component Alignment::
560 * Address Clauses::
561 * Other Representation Clauses::
562
563 Tasking and Task-Related Features
564
565 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
566 * Assigning Task IDs::
567 * Task IDs and Delays::
568 * Task-Related Pragmas::
569 * Scheduling and Task Priority::
570 * The Task Stack::
571 * External Interrupts::
572
573 Pragmas and Pragma-Related Features
574
575 * Restrictions on the Pragma INLINE::
576 * Restrictions on the Pragma INTERFACE::
577 * Restrictions on the Pragma SYSTEM_NAME::
578
579 Library of Predefined Units
580
581 * Changes to DECLIB::
582
583 Bindings
584
585 * Shared Libraries and Options Files::
586 * Interfaces to C::
587 @end ifset
588
589 Platform-Specific Information for the Run-Time Libraries
590
591 * Summary of Run-Time Configurations::
592 * Specifying a Run-Time Library::
593 * Choosing the Scheduling Policy::
594 * Solaris-Specific Considerations::
595 * Linux-Specific Considerations::
596 * AIX-Specific Considerations::
597 * Irix-Specific Considerations::
598
599 Example of Binder Output File
600
601 Elaboration Order Handling in GNAT
602
603 * Elaboration Code::
604 * Checking the Elaboration Order::
605 * Controlling the Elaboration Order::
606 * Controlling Elaboration in GNAT - Internal Calls::
607 * Controlling Elaboration in GNAT - External Calls::
608 * Default Behavior in GNAT - Ensuring Safety::
609 * Treatment of Pragma Elaborate::
610 * Elaboration Issues for Library Tasks::
611 * Mixing Elaboration Models::
612 * What to Do If the Default Elaboration Behavior Fails::
613 * Elaboration for Access-to-Subprogram Values::
614 * Summary of Procedures for Elaboration Control::
615 * Other Elaboration Order Considerations::
616
617 Conditional Compilation
618 * Use of Boolean Constants::
619 * Debugging - A Special Case::
620 * Conditionalizing Declarations::
621 * Use of Alternative Implementations::
622 * Preprocessing::
623
624 Inline Assembler
625
626 * Basic Assembler Syntax::
627 * A Simple Example of Inline Assembler::
628 * Output Variables in Inline Assembler::
629 * Input Variables in Inline Assembler::
630 * Inlining Inline Assembler Code::
631 * Other Asm Functionality::
632
633 Compatibility and Porting Guide
634
635 * Compatibility with Ada 83::
636 * Compatibility between Ada 95 and Ada 2005::
637 * Implementation-dependent characteristics::
638 @ifclear vms
639 @c This brief section is only in the non-VMS version
640 @c The complete chapter on HP Ada issues is in the VMS version
641 * Compatibility with HP Ada 83::
642 @end ifclear
643 * Compatibility with Other Ada Systems::
644 * Representation Clauses::
645 @ifset vms
646 * Transitioning to 64-Bit GNAT for OpenVMS::
647 @end ifset
648
649 @ifset unw
650 Microsoft Windows Topics
651
652 * Using GNAT on Windows::
653 * CONSOLE and WINDOWS subsystems::
654 * Temporary Files::
655 * Mixed-Language Programming on Windows::
656 * Windows Calling Conventions::
657 * Introduction to Dynamic Link Libraries (DLLs)::
658 * Using DLLs with GNAT::
659 * Building DLLs with GNAT::
660 * GNAT and Windows Resources::
661 * Debugging a DLL::
662 * Setting Stack Size from gnatlink::
663 * Setting Heap Size from gnatlink::
664 @end ifset
665
666 * Index::
667 @end menu
668 @end ifnottex
669
670 @node About This Guide
671 @unnumbered About This Guide
672
673 @noindent
674 @ifset vms
675 This guide describes the use of @value{EDITION},
676 a compiler and software development toolset for the full Ada
677 programming language, implemented on OpenVMS for HP's Alpha and
678 Integrity server (I64) platforms.
679 @end ifset
680 @ifclear vms
681 This guide describes the use of @value{EDITION},
682 a compiler and software development
683 toolset for the full Ada programming language.
684 @end ifclear
685 It documents the features of the compiler and tools, and explains
686 how to use them to build Ada applications.
687
688 @value{EDITION} implements Ada 95 and Ada 2005, and it may also be invoked in
689 Ada 83 compatibility mode.
690 By default, @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION},
691 but you can override with a compiler switch
692 (@pxref{Compiling Different Versions of Ada})
693 to explicitly specify the language version.
694 Throughout this manual, references to ``Ada'' without a year suffix
695 apply to both the Ada 95 and Ada 2005 versions of the language.
696
697
698 @ifclear FSFEDITION
699 For ease of exposition, ``@value{EDITION}'' will be referred to simply as
700 ``GNAT'' in the remainder of this document.
701 @end ifclear
702
703
704
705
706 @menu
707 * What This Guide Contains::
708 * What You Should Know before Reading This Guide::
709 * Related Information::
710 * Conventions::
711 @end menu
712
713 @node What This Guide Contains
714 @unnumberedsec What This Guide Contains
715
716 @noindent
717 This guide contains the following chapters:
718 @itemize @bullet
719
720 @item
721 @ref{Getting Started with GNAT}, describes how to get started compiling
722 and running Ada programs with the GNAT Ada programming environment.
723 @item
724 @ref{The GNAT Compilation Model}, describes the compilation model used
725 by GNAT.
726
727 @item
728 @ref{Compiling Using gcc}, describes how to compile
729 Ada programs with @command{gcc}, the Ada compiler.
730
731 @item
732 @ref{Binding Using gnatbind}, describes how to
733 perform binding of Ada programs with @code{gnatbind}, the GNAT binding
734 utility.
735
736 @item
737 @ref{Linking Using gnatlink},
738 describes @command{gnatlink}, a
739 program that provides for linking using the GNAT run-time library to
740 construct a program. @command{gnatlink} can also incorporate foreign language
741 object units into the executable.
742
743 @item
744 @ref{The GNAT Make Program gnatmake}, describes @command{gnatmake}, a
745 utility that automatically determines the set of sources
746 needed by an Ada compilation unit, and executes the necessary compilations
747 binding and link.
748
749 @item
750 @ref{Improving Performance}, shows various techniques for making your
751 Ada program run faster or take less space.
752 It discusses the effect of the compiler's optimization switch and
753 also describes the @command{gnatelim} tool and unused subprogram/data
754 elimination.
755
756 @item
757 @ref{Renaming Files Using gnatchop}, describes
758 @code{gnatchop}, a utility that allows you to preprocess a file that
759 contains Ada source code, and split it into one or more new files, one
760 for each compilation unit.
761
762 @item
763 @ref{Configuration Pragmas}, describes the configuration pragmas
764 handled by GNAT.
765
766 @item
767 @ref{Handling Arbitrary File Naming Conventions Using gnatname},
768 shows how to override the default GNAT file naming conventions,
769 either for an individual unit or globally.
770
771 @item
772 @ref{GNAT Project Manager}, describes how to use project files
773 to organize large projects.
774
775 @item
776 @ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses
777 @code{gnatxref} and @code{gnatfind}, two tools that provide an easy
778 way to navigate through sources.
779
780 @item
781 @ref{The GNAT Pretty-Printer gnatpp}, shows how to produce a reformatted
782 version of an Ada source file with control over casing, indentation,
783 comment placement, and other elements of program presentation style.
784
785 @item
786 @ref{The GNAT Metric Tool gnatmetric}, shows how to compute various
787 metrics for an Ada source file, such as the number of types and subprograms,
788 and assorted complexity measures.
789
790 @item
791 @ref{File Name Krunching Using gnatkr}, describes the @code{gnatkr}
792 file name krunching utility, used to handle shortened
793 file names on operating systems with a limit on the length of names.
794
795 @item
796 @ref{Preprocessing Using gnatprep}, describes @code{gnatprep}, a
797 preprocessor utility that allows a single source file to be used to
798 generate multiple or parameterized source files by means of macro
799 substitution.
800
801 @ifset vms
802 @item
803 @ref{The GNAT Run-Time Library Builder gnatlbr}, describes @command{gnatlbr},
804 a tool for rebuilding the GNAT run time with user-supplied
805 configuration pragmas.
806 @end ifset
807
808 @item
809 @ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a
810 utility that displays information about compiled units, including dependences
811 on the corresponding sources files, and consistency of compilations.
812
813 @item
814 @ref{Cleaning Up Using gnatclean}, describes @code{gnatclean}, a utility
815 to delete files that are produced by the compiler, binder and linker.
816
817 @ifclear vms
818 @item
819 @ref{GNAT and Libraries}, describes the process of creating and using
820 Libraries with GNAT. It also describes how to recompile the GNAT run-time
821 library.
822
823 @item
824 @ref{Using the GNU make Utility}, describes some techniques for using
825 the GNAT toolset in Makefiles.
826 @end ifclear
827
828 @item
829 @ref{Memory Management Issues}, describes some useful predefined storage pools
830 and in particular the GNAT Debug Pool facility, which helps detect incorrect
831 memory references.
832 @ifclear vms
833 It also describes @command{gnatmem}, a utility that monitors dynamic
834 allocation and deallocation and helps detect ``memory leaks''.
835 @end ifclear
836
837 @item
838 @ref{Stack Related Facilities}, describes some useful tools associated with
839 stack checking and analysis.
840
841 @item
842 @ref{Verifying Properties Using gnatcheck}, discusses @code{gnatcheck},
843 a utility that checks Ada code against a set of rules.
844
845 @item
846 @ref{Creating Sample Bodies Using gnatstub}, discusses @code{gnatstub},
847 a utility that generates empty but compilable bodies for library units.
848
849 @item
850 @ref{Generating Ada Bindings for C and C++ headers}, describes how to
851 generate automatically Ada bindings from C and C++ headers.
852
853 @item
854 @ref{Other Utility Programs}, discusses several other GNAT utilities,
855 including @code{gnathtml}.
856
857 @ifclear vms
858 @item
859 @ref{Code Coverage and Profiling}, describes how to perform a structural
860 coverage and profile the execution of Ada programs.
861 @end ifclear
862
863 @item
864 @ref{Running and Debugging Ada Programs}, describes how to run and debug
865 Ada programs.
866
867 @ifset vms
868 @item
869 @ref{Compatibility with HP Ada}, details the compatibility of GNAT with
870 HP Ada 83 @footnote{``HP Ada'' refers to the legacy product originally
871 developed by Digital Equipment Corporation and currently supported by HP.}
872 for OpenVMS Alpha. This product was formerly known as DEC Ada,
873 @cindex DEC Ada
874 and for
875 historical compatibility reasons, the relevant libraries still use the
876 DEC prefix.
877 @end ifset
878
879 @item
880 @ref{Platform-Specific Information for the Run-Time Libraries},
881 describes the various run-time
882 libraries supported by GNAT on various platforms and explains how to
883 choose a particular library.
884
885 @item
886 @ref{Example of Binder Output File}, shows the source code for the binder
887 output file for a sample program.
888
889 @item
890 @ref{Elaboration Order Handling in GNAT}, describes how GNAT helps
891 you deal with elaboration order issues.
892
893 @item
894 @ref{Conditional Compilation}, describes how to model conditional compilation,
895 both with Ada in general and with GNAT facilities in particular.
896
897 @item
898 @ref{Inline Assembler}, shows how to use the inline assembly facility
899 in an Ada program.
900
901 @item
902 @ref{Compatibility and Porting Guide}, contains sections on compatibility
903 of GNAT with other Ada development environments (including Ada 83 systems),
904 to assist in porting code from those environments.
905
906 @ifset unw
907 @item
908 @ref{Microsoft Windows Topics}, presents information relevant to the
909 Microsoft Windows platform.
910 @end ifset
911 @end itemize
912
913 @c *************************************************
914 @node What You Should Know before Reading This Guide
915 @c *************************************************
916 @unnumberedsec What You Should Know before Reading This Guide
917
918 @cindex Ada 95 Language Reference Manual
919 @cindex Ada 2005 Language Reference Manual
920 @noindent
921 This guide assumes a basic familiarity with the Ada 95 language, as
922 described in the International Standard ANSI/ISO/IEC-8652:1995, January
923 1995.
924 It does not require knowledge of the new features introduced by Ada 2005,
925 (officially known as ISO/IEC 8652:1995 with Technical Corrigendum 1
926 and Amendment 1).
927 Both reference manuals are included in the GNAT documentation
928 package.
929
930 @node Related Information
931 @unnumberedsec Related Information
932
933 @noindent
934 For further information about related tools, refer to the following
935 documents:
936
937 @itemize @bullet
938 @item
939 @xref{Top, GNAT Reference Manual, About This Guide, gnat_rm, GNAT
940 Reference Manual}, which contains all reference material for the GNAT
941 implementation of Ada.
942
943 @ifset unw
944 @item
945 @cite{Using the GNAT Programming Studio}, which describes the GPS
946 Integrated Development Environment.
947
948 @item
949 @cite{GNAT Programming Studio Tutorial}, which introduces the
950 main GPS features through examples.
951 @end ifset
952
953 @item
954 @cite{Ada 95 Reference Manual}, which contains reference
955 material for the Ada 95 programming language.
956
957 @item
958 @cite{Ada 2005 Reference Manual}, which contains reference
959 material for the Ada 2005 programming language.
960
961 @item
962 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
963 @ifset vms
964 in the GNU:[DOCS] directory,
965 @end ifset
966 for all details on the use of the GNU source-level debugger.
967
968 @item
969 @xref{Top,, The extensible self-documenting text editor, emacs,
970 GNU Emacs Manual},
971 @ifset vms
972 located in the GNU:[DOCS] directory if the EMACS kit is installed,
973 @end ifset
974 for full information on the extensible editor and programming
975 environment Emacs.
976
977 @end itemize
978
979 @c **************
980 @node Conventions
981 @unnumberedsec Conventions
982 @cindex Conventions
983 @cindex Typographical conventions
984
985 @noindent
986 Following are examples of the typographical and graphic conventions used
987 in this guide:
988
989 @itemize @bullet
990 @item
991 @code{Functions}, @command{utility program names}, @code{standard names},
992 and @code{classes}.
993
994 @item
995 @option{Option flags}
996
997 @item
998 @file{File names}, @samp{button names}, and @samp{field names}.
999
1000 @item
1001 @code{Variables}, @env{environment variables}, and @var{metasyntactic
1002 variables}.
1003
1004 @item
1005 @emph{Emphasis}.
1006
1007 @item
1008 @r{[}optional information or parameters@r{]}
1009
1010 @item
1011 Examples are described by text
1012 @smallexample
1013 and then shown this way.
1014 @end smallexample
1015 @end itemize
1016
1017 @noindent
1018 Commands that are entered by the user are preceded in this manual by the
1019 characters @w{``@code{$ }''} (dollar sign followed by space). If your system
1020 uses this sequence as a prompt, then the commands will appear exactly as
1021 you see them in the manual. If your system uses some other prompt, then
1022 the command will appear with the @code{$} replaced by whatever prompt
1023 character you are using.
1024
1025 @ifset unw
1026 Full file names are shown with the ``@code{/}'' character
1027 as the directory separator; e.g., @file{parent-dir/subdir/myfile.adb}.
1028 If you are using GNAT on a Windows platform, please note that
1029 the ``@code{\}'' character should be used instead.
1030 @end ifset
1031
1032 @c ****************************
1033 @node Getting Started with GNAT
1034 @chapter Getting Started with GNAT
1035
1036 @noindent
1037 This chapter describes some simple ways of using GNAT to build
1038 executable Ada programs.
1039 @ifset unw
1040 @ref{Running GNAT}, through @ref{Using the gnatmake Utility},
1041 show how to use the command line environment.
1042 @ref{Introduction to GPS}, provides a brief
1043 introduction to the GNAT Programming Studio, a visually-oriented
1044 Integrated Development Environment for GNAT.
1045 GPS offers a graphical ``look and feel'', support for development in
1046 other programming languages, comprehensive browsing features, and
1047 many other capabilities.
1048 For information on GPS please refer to
1049 @cite{Using the GNAT Programming Studio}.
1050 @end ifset
1051
1052 @menu
1053 * Running GNAT::
1054 * Running a Simple Ada Program::
1055 * Running a Program with Multiple Units::
1056 * Using the gnatmake Utility::
1057 @ifset vms
1058 * Editing with Emacs::
1059 @end ifset
1060 @ifclear vms
1061 * Introduction to GPS::
1062 @end ifclear
1063 @end menu
1064
1065 @node Running GNAT
1066 @section Running GNAT
1067
1068 @noindent
1069 Three steps are needed to create an executable file from an Ada source
1070 file:
1071
1072 @enumerate
1073 @item
1074 The source file(s) must be compiled.
1075 @item
1076 The file(s) must be bound using the GNAT binder.
1077 @item
1078 All appropriate object files must be linked to produce an executable.
1079 @end enumerate
1080
1081 @noindent
1082 All three steps are most commonly handled by using the @command{gnatmake}
1083 utility program that, given the name of the main program, automatically
1084 performs the necessary compilation, binding and linking steps.
1085
1086 @node Running a Simple Ada Program
1087 @section Running a Simple Ada Program
1088
1089 @noindent
1090 Any text editor may be used to prepare an Ada program.
1091 (If @code{Emacs} is
1092 used, the optional Ada mode may be helpful in laying out the program.)
1093 The
1094 program text is a normal text file. We will assume in our initial
1095 example that you have used your editor to prepare the following
1096 standard format text file:
1097
1098 @smallexample @c ada
1099 @cartouche
1100 with Ada.Text_IO; use Ada.Text_IO;
1101 procedure Hello is
1102 begin
1103    Put_Line ("Hello WORLD!");
1104 end Hello;
1105 @end cartouche
1106 @end smallexample
1107
1108 @noindent
1109 This file should be named @file{hello.adb}.
1110 With the normal default file naming conventions, GNAT requires
1111 that each file
1112 contain a single compilation unit whose file name is the
1113 unit name,
1114 with periods replaced by hyphens; the
1115 extension is @file{ads} for a
1116 spec and @file{adb} for a body.
1117 You can override this default file naming convention by use of the
1118 special pragma @code{Source_File_Name} (@pxref{Using Other File Names}).
1119 Alternatively, if you want to rename your files according to this default
1120 convention, which is probably more convenient if you will be using GNAT
1121 for all your compilations, then the @code{gnatchop} utility
1122 can be used to generate correctly-named source files
1123 (@pxref{Renaming Files Using gnatchop}).
1124
1125 You can compile the program using the following command (@code{$} is used
1126 as the command prompt in the examples in this document):
1127
1128 @smallexample
1129 $ gcc -c hello.adb
1130 @end smallexample
1131
1132 @noindent
1133 @command{gcc} is the command used to run the compiler. This compiler is
1134 capable of compiling programs in several languages, including Ada and
1135 C. It assumes that you have given it an Ada program if the file extension is
1136 either @file{.ads} or @file{.adb}, and it will then call
1137 the GNAT compiler to compile the specified file.
1138
1139 @ifclear vms
1140 The @option{-c} switch is required. It tells @command{gcc} to only do a
1141 compilation. (For C programs, @command{gcc} can also do linking, but this
1142 capability is not used directly for Ada programs, so the @option{-c}
1143 switch must always be present.)
1144 @end ifclear
1145
1146 This compile command generates a file
1147 @file{hello.o}, which is the object
1148 file corresponding to your Ada program. It also generates
1149 an ``Ada Library Information'' file @file{hello.ali},
1150 which contains additional information used to check
1151 that an Ada program is consistent.
1152 To build an executable file,
1153 use @code{gnatbind} to bind the program
1154 and @command{gnatlink} to link it. The
1155 argument to both @code{gnatbind} and @command{gnatlink} is the name of the
1156 @file{ALI} file, but the default extension of @file{.ali} can
1157 be omitted. This means that in the most common case, the argument
1158 is simply the name of the main program:
1159
1160 @smallexample
1161 $ gnatbind hello
1162 $ gnatlink hello
1163 @end smallexample
1164
1165 @noindent
1166 A simpler method of carrying out these steps is to use
1167 @command{gnatmake},
1168 a master program that invokes all the required
1169 compilation, binding and linking tools in the correct order. In particular,
1170 @command{gnatmake} automatically recompiles any sources that have been
1171 modified since they were last compiled, or sources that depend
1172 on such modified sources, so that ``version skew'' is avoided.
1173 @cindex Version skew (avoided by @command{gnatmake})
1174
1175 @smallexample
1176 $ gnatmake hello.adb
1177 @end smallexample
1178
1179 @noindent
1180 The result is an executable program called @file{hello}, which can be
1181 run by entering:
1182
1183 @smallexample
1184 $ ^hello^RUN HELLO^
1185 @end smallexample
1186
1187 @noindent
1188 assuming that the current directory is on the search path
1189 for executable programs.
1190
1191 @noindent
1192 and, if all has gone well, you will see
1193
1194 @smallexample
1195 Hello WORLD!
1196 @end smallexample
1197
1198 @noindent
1199 appear in response to this command.
1200
1201 @c ****************************************
1202 @node Running a Program with Multiple Units
1203 @section Running a Program with Multiple Units
1204
1205 @noindent
1206 Consider a slightly more complicated example that has three files: a
1207 main program, and the spec and body of a package:
1208
1209 @smallexample @c ada
1210 @cartouche
1211 @group
1212 package Greetings is
1213    procedure Hello;
1214    procedure Goodbye;
1215 end Greetings;
1216
1217 with Ada.Text_IO; use Ada.Text_IO;
1218 package body Greetings is
1219    procedure Hello is
1220    begin
1221       Put_Line ("Hello WORLD!");
1222    end Hello;
1223
1224    procedure Goodbye is
1225    begin
1226       Put_Line ("Goodbye WORLD!");
1227    end Goodbye;
1228 end Greetings;
1229 @end group
1230
1231 @group
1232 with Greetings;
1233 procedure Gmain is
1234 begin
1235    Greetings.Hello;
1236    Greetings.Goodbye;
1237 end Gmain;
1238 @end group
1239 @end cartouche
1240 @end smallexample
1241
1242 @noindent
1243 Following the one-unit-per-file rule, place this program in the
1244 following three separate files:
1245
1246 @table @file
1247 @item greetings.ads
1248 spec of package @code{Greetings}
1249
1250 @item greetings.adb
1251 body of package @code{Greetings}
1252
1253 @item gmain.adb
1254 body of main program
1255 @end table
1256
1257 @noindent
1258 To build an executable version of
1259 this program, we could use four separate steps to compile, bind, and link
1260 the program, as follows:
1261
1262 @smallexample
1263 $ gcc -c gmain.adb
1264 $ gcc -c greetings.adb
1265 $ gnatbind gmain
1266 $ gnatlink gmain
1267 @end smallexample
1268
1269 @noindent
1270 Note that there is no required order of compilation when using GNAT.
1271 In particular it is perfectly fine to compile the main program first.
1272 Also, it is not necessary to compile package specs in the case where
1273 there is an accompanying body; you only need to compile the body. If you want
1274 to submit these files to the compiler for semantic checking and not code
1275 generation, then use the
1276 @option{-gnatc} switch:
1277
1278 @smallexample
1279 $ gcc -c greetings.ads -gnatc
1280 @end smallexample
1281
1282 @noindent
1283 Although the compilation can be done in separate steps as in the
1284 above example, in practice it is almost always more convenient
1285 to use the @command{gnatmake} tool. All you need to know in this case
1286 is the name of the main program's source file. The effect of the above four
1287 commands can be achieved with a single one:
1288
1289 @smallexample
1290 $ gnatmake gmain.adb
1291 @end smallexample
1292
1293 @noindent
1294 In the next section we discuss the advantages of using @command{gnatmake} in
1295 more detail.
1296
1297 @c *****************************
1298 @node Using the gnatmake Utility
1299 @section Using the @command{gnatmake} Utility
1300
1301 @noindent
1302 If you work on a program by compiling single components at a time using
1303 @command{gcc}, you typically keep track of the units you modify. In order to
1304 build a consistent system, you compile not only these units, but also any
1305 units that depend on the units you have modified.
1306 For example, in the preceding case,
1307 if you edit @file{gmain.adb}, you only need to recompile that file. But if
1308 you edit @file{greetings.ads}, you must recompile both
1309 @file{greetings.adb} and @file{gmain.adb}, because both files contain
1310 units that depend on @file{greetings.ads}.
1311
1312 @code{gnatbind} will warn you if you forget one of these compilation
1313 steps, so that it is impossible to generate an inconsistent program as a
1314 result of forgetting to do a compilation. Nevertheless it is tedious and
1315 error-prone to keep track of dependencies among units.
1316 One approach to handle the dependency-bookkeeping is to use a
1317 makefile. However, makefiles present maintenance problems of their own:
1318 if the dependencies change as you change the program, you must make
1319 sure that the makefile is kept up-to-date manually, which is also an
1320 error-prone process.
1321
1322 The @command{gnatmake} utility takes care of these details automatically.
1323 Invoke it using either one of the following forms:
1324
1325 @smallexample
1326 $ gnatmake gmain.adb
1327 $ gnatmake ^gmain^GMAIN^
1328 @end smallexample
1329
1330 @noindent
1331 The argument is the name of the file containing the main program;
1332 you may omit the extension. @command{gnatmake}
1333 examines the environment, automatically recompiles any files that need
1334 recompiling, and binds and links the resulting set of object files,
1335 generating the executable file, @file{^gmain^GMAIN.EXE^}.
1336 In a large program, it
1337 can be extremely helpful to use @command{gnatmake}, because working out by hand
1338 what needs to be recompiled can be difficult.
1339
1340 Note that @command{gnatmake}
1341 takes into account all the Ada rules that
1342 establish dependencies among units. These include dependencies that result
1343 from inlining subprogram bodies, and from
1344 generic instantiation. Unlike some other
1345 Ada make tools, @command{gnatmake} does not rely on the dependencies that were
1346 found by the compiler on a previous compilation, which may possibly
1347 be wrong when sources change. @command{gnatmake} determines the exact set of
1348 dependencies from scratch each time it is run.
1349
1350 @ifset vms
1351 @node Editing with Emacs
1352 @section Editing with Emacs
1353 @cindex Emacs
1354
1355 @noindent
1356 Emacs is an extensible self-documenting text editor that is available in a
1357 separate VMSINSTAL kit.
1358
1359 Invoke Emacs by typing @kbd{Emacs} at the command prompt. To get started,
1360 click on the Emacs Help menu and run the Emacs Tutorial.
1361 In a character cell terminal, Emacs help is invoked with @kbd{Ctrl-h} (also
1362 written as @kbd{C-h}), and the tutorial by @kbd{C-h t}.
1363
1364 Documentation on Emacs and other tools is available in Emacs under the
1365 pull-down menu button: @code{Help - Info}. After selecting @code{Info},
1366 use the middle mouse button to select a topic (e.g.@: Emacs).
1367
1368 In a character cell terminal, do @kbd{C-h i} to invoke info, and then @kbd{m}
1369 (stands for menu) followed by the menu item desired, as in @kbd{m Emacs}, to
1370 get to the Emacs manual.
1371 Help on Emacs is also available by typing @kbd{HELP EMACS} at the DCL command
1372 prompt.
1373
1374 The tutorial is highly recommended in order to learn the intricacies of Emacs,
1375 which is sufficiently extensible to provide for a complete programming
1376 environment and shell for the sophisticated user.
1377 @end ifset
1378
1379 @ifclear vms
1380 @node Introduction to GPS
1381 @section Introduction to GPS
1382 @cindex GPS (GNAT Programming Studio)
1383 @cindex GNAT Programming Studio (GPS)
1384 @noindent
1385 Although the command line interface (@command{gnatmake}, etc.) alone
1386 is sufficient, a graphical Interactive Development
1387 Environment can make it easier for you to compose, navigate, and debug
1388 programs.  This section describes the main features of GPS
1389 (``GNAT Programming Studio''), the GNAT graphical IDE.
1390 You will see how to use GPS to build and debug an executable, and
1391 you will also learn some of the basics of the GNAT ``project'' facility.
1392
1393 GPS enables you to do much more than is presented here;
1394 e.g., you can produce a call graph, interface to a third-party
1395 Version Control System, and inspect the generated assembly language
1396 for a program.
1397 Indeed, GPS also supports languages other than Ada.
1398 Such additional information, and an explanation of all of the GPS menu
1399 items. may be found in the on-line help, which includes
1400 a user's guide and a tutorial (these are also accessible from the GNAT
1401 startup menu).
1402
1403 @menu
1404 * Building a New Program with GPS::
1405 * Simple Debugging with GPS::
1406 @end menu
1407
1408 @node Building a New Program with GPS
1409 @subsection Building a New Program with GPS
1410 @noindent
1411 GPS invokes the GNAT compilation tools using information
1412 contained in a @emph{project} (also known as a @emph{project file}):
1413 a collection of properties such
1414 as source directories, identities of main subprograms, tool switches, etc.,
1415 and their associated values.
1416 See @ref{GNAT Project Manager} for details.
1417 In order to run GPS, you will need to either create a new project
1418 or else open an existing one.
1419
1420 This section will explain how you can use GPS to create a project,
1421 to associate Ada source files with a project, and to build and run
1422 programs.
1423
1424 @enumerate
1425 @item @emph{Creating a project}
1426
1427 Invoke GPS, either from the command line or the platform's IDE.
1428 After it starts, GPS will display a ``Welcome'' screen with three
1429 radio buttons:
1430
1431 @itemize @bullet
1432 @item
1433 @code{Start with default project in directory}
1434
1435 @item
1436 @code{Create new project with wizard}
1437
1438 @item
1439 @code{Open existing project}
1440 @end itemize
1441
1442 @noindent
1443 Select @code{Create new project with wizard} and press @code{OK}.
1444 A new window will appear.  In the text box labeled with
1445 @code{Enter the name of the project to create}, type @file{sample}
1446 as the project name.
1447 In the next box, browse to choose the directory in which you
1448 would like to create the project file.
1449 After selecting an appropriate directory, press @code{Forward}.
1450
1451 A window will appear with the title
1452 @code{Version Control System Configuration}.
1453 Simply press @code{Forward}.
1454
1455 A window will appear with the title
1456 @code{Please select the source directories for this project}.
1457 The directory that you specified for the project file will be selected
1458 by default as the one to use for sources; simply press @code{Forward}.
1459
1460 A window will appear with the title
1461 @code{Please select the build directory for this project}.
1462 The directory that you specified for the project file will be selected
1463 by default for object files and executables;
1464 simply press @code{Forward}.
1465
1466 A window will appear with the title
1467 @code{Please select the main units for this project}.
1468 You will supply this information later, after creating the source file.
1469 Simply press @code{Forward} for now.
1470
1471 A window will appear with the title
1472 @code{Please select the switches to build the project}.
1473 Press @code{Apply}.  This will create a project file named
1474 @file{sample.prj} in the directory that you had specified.
1475
1476 @item @emph{Creating and saving the source file}
1477
1478 After you create the new project, a GPS window will appear, which is
1479 partitioned into two main sections:
1480
1481 @itemize @bullet
1482 @item
1483 A @emph{Workspace area}, initially greyed out, which you will use for
1484 creating and editing source files
1485
1486 @item
1487 Directly below, a @emph{Messages area}, which initially displays a
1488 ``Welcome'' message.
1489 (If the Messages area is not visible, drag its border upward to expand it.)
1490 @end itemize
1491
1492 @noindent
1493 Select @code{File} on the menu bar, and then the @code{New} command.
1494 The Workspace area will become white, and you can now
1495 enter the source program explicitly.
1496 Type the following text
1497
1498 @smallexample @c ada
1499 @group
1500 with Ada.Text_IO; use Ada.Text_IO;
1501 procedure Hello is
1502 begin
1503   Put_Line("Hello from GPS!");
1504 end Hello;
1505 @end group
1506 @end smallexample
1507
1508 @noindent
1509 Select @code{File}, then @code{Save As}, and enter the source file name
1510 @file{hello.adb}.
1511 The file will be saved in the same directory you specified as the
1512 location of the default project file.
1513
1514 @item @emph{Updating the project file}
1515
1516 You need to add the new source file to the project.
1517 To do this, select
1518 the @code{Project} menu and then @code{Edit project properties}.
1519 Click the @code{Main files} tab on the left, and then the
1520 @code{Add} button.
1521 Choose @file{hello.adb} from the list, and press @code{Open}.
1522 The project settings window will reflect this action.
1523 Click @code{OK}.
1524
1525 @item @emph{Building and running the program}
1526
1527 In the main GPS window, now choose the @code{Build} menu, then @code{Make},
1528 and select @file{hello.adb}.
1529 The Messages window will display the resulting invocations of @command{gcc},
1530 @command{gnatbind}, and @command{gnatlink}
1531 (reflecting the default switch settings from the
1532 project file that you created) and then a ``successful compilation/build''
1533 message.
1534
1535 To run the program, choose the @code{Build} menu, then @code{Run}, and
1536 select @command{hello}.
1537 An @emph{Arguments Selection} window will appear.
1538 There are no command line arguments, so just click @code{OK}.
1539
1540 The Messages window will now display the program's output (the string
1541 @code{Hello from GPS}), and at the bottom of the GPS window a status
1542 update is displayed (@code{Run: hello}).
1543 Close the GPS window (or select @code{File}, then @code{Exit}) to
1544 terminate this GPS session.
1545 @end enumerate
1546
1547 @node Simple Debugging with GPS
1548 @subsection Simple Debugging with GPS
1549 @noindent
1550 This section illustrates basic debugging techniques (setting breakpoints,
1551 examining/modifying variables, single stepping).
1552
1553 @enumerate
1554 @item @emph{Opening a project}
1555
1556 Start GPS and select @code{Open existing project}; browse to
1557 specify the project file @file{sample.prj} that you had created in the
1558 earlier example.
1559
1560 @item @emph{Creating a source file}
1561
1562 Select @code{File}, then @code{New}, and type in the following program:
1563
1564 @smallexample @c ada
1565 @group
1566 with Ada.Text_IO; use Ada.Text_IO;
1567 procedure Example is
1568    Line : String (1..80);
1569    N    : Natural;
1570 begin
1571    Put_Line("Type a line of text at each prompt; an empty line to exit");
1572    loop
1573       Put(": ");
1574       Get_Line (Line, N);
1575       Put_Line (Line (1..N) );
1576       exit when N=0;
1577    end loop;
1578 end Example;
1579 @end group
1580 @end smallexample
1581
1582 @noindent
1583 Select @code{File}, then @code{Save as}, and enter the file name
1584 @file{example.adb}.
1585
1586 @item @emph{Updating the project file}
1587
1588 Add @code{Example} as a new main unit for the project:
1589 @enumerate a
1590 @item
1591 Select @code{Project}, then @code{Edit Project Properties}.
1592
1593 @item
1594 Select the @code{Main files} tab, click @code{Add}, then
1595 select the file @file{example.adb} from the list, and
1596 click @code{Open}.
1597 You will see the file name appear in the list of main units
1598
1599 @item
1600 Click @code{OK}
1601 @end enumerate
1602
1603 @item @emph{Building/running the executable}
1604
1605 To build the executable
1606 select @code{Build}, then @code{Make}, and then choose @file{example.adb}.
1607
1608 Run the program to see its effect (in the Messages area).
1609 Each line that you enter is displayed; an empty line will
1610 cause the loop to exit and the program to terminate.
1611
1612 @item @emph{Debugging the program}
1613
1614 Note that the @option{-g} switches to @command{gcc} and @command{gnatlink},
1615 which are required for debugging, are on by default when you create
1616 a new project.
1617 Thus unless you intentionally remove these settings, you will be able
1618 to debug any program that you develop using GPS.
1619
1620 @enumerate a
1621 @item @emph{Initializing}
1622
1623 Select @code{Debug}, then @code{Initialize}, then @file{example}
1624
1625 @item @emph{Setting a breakpoint}
1626
1627 After performing the initialization step, you will observe a small
1628 icon to the right of each line number.
1629 This serves as a toggle for breakpoints; clicking the icon will
1630 set a breakpoint at the corresponding line (the icon will change to
1631 a red circle with an ``x''), and clicking it again
1632 will remove the breakpoint / reset the icon.
1633
1634 For purposes of this example, set a breakpoint at line 10 (the
1635 statement @code{Put_Line@ (Line@ (1..N));}
1636
1637 @item @emph{Starting program execution}
1638
1639 Select @code{Debug}, then @code{Run}.  When the
1640 @code{Program Arguments} window appears, click @code{OK}.
1641 A console window will appear; enter some line of text,
1642 e.g.@: @code{abcde}, at the prompt.
1643 The program will pause execution when it gets to the
1644 breakpoint, and the corresponding line is highlighted.
1645
1646 @item @emph{Examining a variable}
1647
1648 Move the mouse over one of the occurrences of the variable @code{N}.
1649 You will see the value (5) displayed, in ``tool tip'' fashion.
1650 Right click on @code{N}, select @code{Debug}, then select @code{Display N}.
1651 You will see information about @code{N} appear in the @code{Debugger Data}
1652 pane, showing the value as 5.
1653
1654 @item @emph{Assigning a new value to a variable}
1655
1656 Right click on the @code{N} in the @code{Debugger Data} pane, and
1657 select @code{Set value of N}.
1658 When the input window appears, enter the value @code{4} and click
1659 @code{OK}.
1660 This value does not automatically appear in the @code{Debugger Data}
1661 pane; to see it, right click again on the @code{N} in the
1662 @code{Debugger Data} pane and select @code{Update value}.
1663 The new value, 4, will appear in red.
1664
1665 @item @emph{Single stepping}
1666
1667 Select @code{Debug}, then @code{Next}.
1668 This will cause the next statement to be executed, in this case the
1669 call of @code{Put_Line} with the string slice.
1670 Notice in the console window that the displayed string is simply
1671 @code{abcd} and not @code{abcde} which you had entered.
1672 This is because the upper bound of the slice is now 4 rather than 5.
1673
1674 @item @emph{Removing a breakpoint}
1675
1676 Toggle the breakpoint icon at line 10.
1677
1678 @item @emph{Resuming execution from a breakpoint}
1679
1680 Select @code{Debug}, then @code{Continue}.
1681 The program will reach the next iteration of the loop, and
1682 wait for input after displaying the prompt.
1683 This time, just hit the @kbd{Enter} key.
1684 The value of @code{N} will be 0, and the program will terminate.
1685 The console window will disappear.
1686 @end enumerate
1687 @end enumerate
1688 @end ifclear
1689
1690 @node The GNAT Compilation Model
1691 @chapter The GNAT Compilation Model
1692 @cindex GNAT compilation model
1693 @cindex Compilation model
1694
1695 @menu
1696 * Source Representation::
1697 * Foreign Language Representation::
1698 * File Naming Rules::
1699 * Using Other File Names::
1700 * Alternative File Naming Schemes::
1701 * Generating Object Files::
1702 * Source Dependencies::
1703 * The Ada Library Information Files::
1704 * Binding an Ada Program::
1705 * Mixed Language Programming::
1706 @ifclear vms
1707 * Building Mixed Ada & C++ Programs::
1708 * Comparison between GNAT and C/C++ Compilation Models::
1709 @end ifclear
1710 * Comparison between GNAT and Conventional Ada Library Models::
1711 @ifset vms
1712 * Placement of temporary files::
1713 @end ifset
1714 @end menu
1715
1716 @noindent
1717 This chapter describes the compilation model used by GNAT. Although
1718 similar to that used by other languages, such as C and C++, this model
1719 is substantially different from the traditional Ada compilation models,
1720 which are based on a library. The model is initially described without
1721 reference to the library-based model. If you have not previously used an
1722 Ada compiler, you need only read the first part of this chapter. The
1723 last section describes and discusses the differences between the GNAT
1724 model and the traditional Ada compiler models. If you have used other
1725 Ada compilers, this section will help you to understand those
1726 differences, and the advantages of the GNAT model.
1727
1728 @node Source Representation
1729 @section Source Representation
1730 @cindex Latin-1
1731
1732 @noindent
1733 Ada source programs are represented in standard text files, using
1734 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1735 7-bit ASCII set, plus additional characters used for
1736 representing foreign languages (@pxref{Foreign Language Representation}
1737 for support of non-USA character sets). The format effector characters
1738 are represented using their standard ASCII encodings, as follows:
1739
1740 @table @code
1741 @item VT
1742 @findex VT
1743 Vertical tab, @code{16#0B#}
1744
1745 @item HT
1746 @findex HT
1747 Horizontal tab, @code{16#09#}
1748
1749 @item CR
1750 @findex CR
1751 Carriage return, @code{16#0D#}
1752
1753 @item LF
1754 @findex LF
1755 Line feed, @code{16#0A#}
1756
1757 @item FF
1758 @findex FF
1759 Form feed, @code{16#0C#}
1760 @end table
1761
1762 @noindent
1763 Source files are in standard text file format. In addition, GNAT will
1764 recognize a wide variety of stream formats, in which the end of
1765 physical lines is marked by any of the following sequences:
1766 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1767 in accommodating files that are imported from other operating systems.
1768
1769 @cindex End of source file
1770 @cindex Source file, end
1771 @findex SUB
1772 The end of a source file is normally represented by the physical end of
1773 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1774 recognized as signalling the end of the source file. Again, this is
1775 provided for compatibility with other operating systems where this
1776 code is used to represent the end of file.
1777
1778 Each file contains a single Ada compilation unit, including any pragmas
1779 associated with the unit. For example, this means you must place a
1780 package declaration (a package @dfn{spec}) and the corresponding body in
1781 separate files. An Ada @dfn{compilation} (which is a sequence of
1782 compilation units) is represented using a sequence of files. Similarly,
1783 you will place each subunit or child unit in a separate file.
1784
1785 @node Foreign Language Representation
1786 @section Foreign Language Representation
1787
1788 @noindent
1789 GNAT supports the standard character sets defined in Ada as well as
1790 several other non-standard character sets for use in localized versions
1791 of the compiler (@pxref{Character Set Control}).
1792 @menu
1793 * Latin-1::
1794 * Other 8-Bit Codes::
1795 * Wide Character Encodings::
1796 @end menu
1797
1798 @node Latin-1
1799 @subsection Latin-1
1800 @cindex Latin-1
1801
1802 @noindent
1803 The basic character set is Latin-1. This character set is defined by ISO
1804 standard 8859, part 1. The lower half (character codes @code{16#00#}
1805 @dots{} @code{16#7F#)} is identical to standard ASCII coding, but the upper half
1806 is used to represent additional characters. These include extended letters
1807 used by European languages, such as French accents, the vowels with umlauts
1808 used in German, and the extra letter A-ring used in Swedish.
1809
1810 @findex Ada.Characters.Latin_1
1811 For a complete list of Latin-1 codes and their encodings, see the source
1812 file of library unit @code{Ada.Characters.Latin_1} in file
1813 @file{a-chlat1.ads}.
1814 You may use any of these extended characters freely in character or
1815 string literals. In addition, the extended characters that represent
1816 letters can be used in identifiers.
1817
1818 @node Other 8-Bit Codes
1819 @subsection Other 8-Bit Codes
1820
1821 @noindent
1822 GNAT also supports several other 8-bit coding schemes:
1823
1824 @table @asis
1825 @item ISO 8859-2 (Latin-2)
1826 @cindex Latin-2
1827 @cindex ISO 8859-2
1828 Latin-2 letters allowed in identifiers, with uppercase and lowercase
1829 equivalence.
1830
1831 @item ISO 8859-3 (Latin-3)
1832 @cindex Latin-3
1833 @cindex ISO 8859-3
1834 Latin-3 letters allowed in identifiers, with uppercase and lowercase
1835 equivalence.
1836
1837 @item ISO 8859-4 (Latin-4)
1838 @cindex Latin-4
1839 @cindex ISO 8859-4
1840 Latin-4 letters allowed in identifiers, with uppercase and lowercase
1841 equivalence.
1842
1843 @item ISO 8859-5 (Cyrillic)
1844 @cindex ISO 8859-5
1845 @cindex Cyrillic
1846 ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
1847 lowercase equivalence.
1848
1849 @item ISO 8859-15 (Latin-9)
1850 @cindex ISO 8859-15
1851 @cindex Latin-9
1852 ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
1853 lowercase equivalence
1854
1855 @item IBM PC (code page 437)
1856 @cindex code page 437
1857 This code page is the normal default for PCs in the U.S. It corresponds
1858 to the original IBM PC character set. This set has some, but not all, of
1859 the extended Latin-1 letters, but these letters do not have the same
1860 encoding as Latin-1. In this mode, these letters are allowed in
1861 identifiers with uppercase and lowercase equivalence.
1862
1863 @item IBM PC (code page 850)
1864 @cindex code page 850
1865 This code page is a modification of 437 extended to include all the
1866 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
1867 mode, all these letters are allowed in identifiers with uppercase and
1868 lowercase equivalence.
1869
1870 @item Full Upper 8-bit
1871 Any character in the range 80-FF allowed in identifiers, and all are
1872 considered distinct. In other words, there are no uppercase and lowercase
1873 equivalences in this range. This is useful in conjunction with
1874 certain encoding schemes used for some foreign character sets (e.g.,
1875 the typical method of representing Chinese characters on the PC).
1876
1877 @item No Upper-Half
1878 No upper-half characters in the range 80-FF are allowed in identifiers.
1879 This gives Ada 83 compatibility for identifier names.
1880 @end table
1881
1882 @noindent
1883 For precise data on the encodings permitted, and the uppercase and lowercase
1884 equivalences that are recognized, see the file @file{csets.adb} in
1885 the GNAT compiler sources. You will need to obtain a full source release
1886 of GNAT to obtain this file.
1887
1888 @node Wide Character Encodings
1889 @subsection Wide Character Encodings
1890
1891 @noindent
1892 GNAT allows wide character codes to appear in character and string
1893 literals, and also optionally in identifiers, by means of the following
1894 possible encoding schemes:
1895
1896 @table @asis
1897
1898 @item Hex Coding
1899 In this encoding, a wide character is represented by the following five
1900 character sequence:
1901
1902 @smallexample
1903 ESC a b c d
1904 @end smallexample
1905
1906 @noindent
1907 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1908 characters (using uppercase letters) of the wide character code. For
1909 example, ESC A345 is used to represent the wide character with code
1910 @code{16#A345#}.
1911 This scheme is compatible with use of the full Wide_Character set.
1912
1913 @item Upper-Half Coding
1914 @cindex Upper-Half Coding
1915 The wide character with encoding @code{16#abcd#} where the upper bit is on
1916 (in other words, ``a'' is in the range 8-F) is represented as two bytes,
1917 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
1918 character, but is not required to be in the upper half. This method can
1919 be also used for shift-JIS or EUC, where the internal coding matches the
1920 external coding.
1921
1922 @item Shift JIS Coding
1923 @cindex Shift JIS Coding
1924 A wide character is represented by a two-character sequence,
1925 @code{16#ab#} and
1926 @code{16#cd#}, with the restrictions described for upper-half encoding as
1927 described above. The internal character code is the corresponding JIS
1928 character according to the standard algorithm for Shift-JIS
1929 conversion. Only characters defined in the JIS code set table can be
1930 used with this encoding method.
1931
1932 @item EUC Coding
1933 @cindex EUC Coding
1934 A wide character is represented by a two-character sequence
1935 @code{16#ab#} and
1936 @code{16#cd#}, with both characters being in the upper half. The internal
1937 character code is the corresponding JIS character according to the EUC
1938 encoding algorithm. Only characters defined in the JIS code set table
1939 can be used with this encoding method.
1940
1941 @item UTF-8 Coding
1942 A wide character is represented using
1943 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1944 10646-1/Am.2. Depending on the character value, the representation
1945 is a one, two, or three byte sequence:
1946 @smallexample
1947 @iftex
1948 @leftskip=.7cm
1949 @end iftex
1950 16#0000#-16#007f#: 2#0@var{xxxxxxx}#
1951 16#0080#-16#07ff#: 2#110@var{xxxxx}# 2#10@var{xxxxxx}#
1952 16#0800#-16#ffff#: 2#1110@var{xxxx}# 2#10@var{xxxxxx}# 2#10@var{xxxxxx}#
1953
1954 @end smallexample
1955
1956 @noindent
1957 where the @var{xxx} bits correspond to the left-padded bits of the
1958 16-bit character value. Note that all lower half ASCII characters
1959 are represented as ASCII bytes and all upper half characters and
1960 other wide characters are represented as sequences of upper-half
1961 (The full UTF-8 scheme allows for encoding 31-bit characters as
1962 6-byte sequences, but in this implementation, all UTF-8 sequences
1963 of four or more bytes length will be treated as illegal).
1964 @item Brackets Coding
1965 In this encoding, a wide character is represented by the following eight
1966 character sequence:
1967
1968 @smallexample
1969 [ " a b c d " ]
1970 @end smallexample
1971
1972 @noindent
1973 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1974 characters (using uppercase letters) of the wide character code. For
1975 example, [``A345''] is used to represent the wide character with code
1976 @code{16#A345#}. It is also possible (though not required) to use the
1977 Brackets coding for upper half characters. For example, the code
1978 @code{16#A3#} can be represented as @code{[``A3'']}.
1979
1980 This scheme is compatible with use of the full Wide_Character set,
1981 and is also the method used for wide character encoding in the standard
1982 ACVC (Ada Compiler Validation Capability) test suite distributions.
1983
1984 @end table
1985
1986 @noindent
1987 Note: Some of these coding schemes do not permit the full use of the
1988 Ada character set. For example, neither Shift JIS, nor EUC allow the
1989 use of the upper half of the Latin-1 set.
1990
1991 @node File Naming Rules
1992 @section File Naming Rules
1993
1994 @noindent
1995 The default file name is determined by the name of the unit that the
1996 file contains. The name is formed by taking the full expanded name of
1997 the unit and replacing the separating dots with hyphens and using
1998 ^lowercase^uppercase^ for all letters.
1999
2000 An exception arises if the file name generated by the above rules starts
2001 with one of the characters
2002 @ifset vms
2003 @samp{A}, @samp{G}, @samp{I}, or @samp{S},
2004 @end ifset
2005 @ifclear vms
2006 @samp{a}, @samp{g}, @samp{i}, or @samp{s},
2007 @end ifclear
2008 and the second character is a
2009 minus. In this case, the character ^tilde^dollar sign^ is used in place
2010 of the minus. The reason for this special rule is to avoid clashes with
2011 the standard names for child units of the packages System, Ada,
2012 Interfaces, and GNAT, which use the prefixes
2013 @ifset vms
2014 @samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},
2015 @end ifset
2016 @ifclear vms
2017 @samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},
2018 @end ifclear
2019 respectively.
2020
2021 The file extension is @file{.ads} for a spec and
2022 @file{.adb} for a body. The following list shows some
2023 examples of these rules.
2024
2025 @table @file
2026 @item main.ads
2027 Main (spec)
2028 @item main.adb
2029 Main (body)
2030 @item arith_functions.ads
2031 Arith_Functions (package spec)
2032 @item arith_functions.adb
2033 Arith_Functions (package body)
2034 @item func-spec.ads
2035 Func.Spec (child package spec)
2036 @item func-spec.adb
2037 Func.Spec (child package body)
2038 @item main-sub.adb
2039 Sub (subunit of Main)
2040 @item ^a~bad.adb^A$BAD.ADB^
2041 A.Bad (child package body)
2042 @end table
2043
2044 @noindent
2045 Following these rules can result in excessively long
2046 file names if corresponding
2047 unit names are long (for example, if child units or subunits are
2048 heavily nested). An option is available to shorten such long file names
2049 (called file name ``krunching''). This may be particularly useful when
2050 programs being developed with GNAT are to be used on operating systems
2051 with limited file name lengths. @xref{Using gnatkr}.
2052
2053 Of course, no file shortening algorithm can guarantee uniqueness over
2054 all possible unit names; if file name krunching is used, it is your
2055 responsibility to ensure no name clashes occur. Alternatively you
2056 can specify the exact file names that you want used, as described
2057 in the next section. Finally, if your Ada programs are migrating from a
2058 compiler with a different naming convention, you can use the gnatchop
2059 utility to produce source files that follow the GNAT naming conventions.
2060 (For details @pxref{Renaming Files Using gnatchop}.)
2061
2062 Note: in the case of @code{Windows NT/XP} or @code{OpenVMS} operating
2063 systems, case is not significant. So for example on @code{Windows XP}
2064 if the canonical name is @code{main-sub.adb}, you can use the file name
2065 @code{Main-Sub.adb} instead. However, case is significant for other
2066 operating systems, so for example, if you want to use other than
2067 canonically cased file names on a Unix system, you need to follow
2068 the procedures described in the next section.
2069
2070 @node Using Other File Names
2071 @section Using Other File Names
2072 @cindex File names
2073
2074 @noindent
2075 In the previous section, we have described the default rules used by
2076 GNAT to determine the file name in which a given unit resides. It is
2077 often convenient to follow these default rules, and if you follow them,
2078 the compiler knows without being explicitly told where to find all
2079 the files it needs.
2080
2081 However, in some cases, particularly when a program is imported from
2082 another Ada compiler environment, it may be more convenient for the
2083 programmer to specify which file names contain which units. GNAT allows
2084 arbitrary file names to be used by means of the Source_File_Name pragma.
2085 The form of this pragma is as shown in the following examples:
2086 @cindex Source_File_Name pragma
2087
2088 @smallexample @c ada
2089 @cartouche
2090 pragma Source_File_Name (My_Utilities.Stacks,
2091   Spec_File_Name => "myutilst_a.ada");
2092 pragma Source_File_name (My_Utilities.Stacks,
2093   Body_File_Name => "myutilst.ada");
2094 @end cartouche
2095 @end smallexample
2096
2097 @noindent
2098 As shown in this example, the first argument for the pragma is the unit
2099 name (in this example a child unit). The second argument has the form
2100 of a named association. The identifier
2101 indicates whether the file name is for a spec or a body;
2102 the file name itself is given by a string literal.
2103
2104 The source file name pragma is a configuration pragma, which means that
2105 normally it will be placed in the @file{gnat.adc}
2106 file used to hold configuration
2107 pragmas that apply to a complete compilation environment.
2108 For more details on how the @file{gnat.adc} file is created and used
2109 see @ref{Handling of Configuration Pragmas}.
2110 @cindex @file{gnat.adc}
2111
2112 @ifclear vms
2113 GNAT allows completely arbitrary file names to be specified using the
2114 source file name pragma. However, if the file name specified has an
2115 extension other than @file{.ads} or @file{.adb} it is necessary to use
2116 a special syntax when compiling the file. The name in this case must be
2117 preceded by the special sequence @option{-x} followed by a space and the name
2118 of the language, here @code{ada}, as in:
2119
2120 @smallexample
2121 $ gcc -c -x ada peculiar_file_name.sim
2122 @end smallexample
2123 @end ifclear
2124
2125 @noindent
2126 @command{gnatmake} handles non-standard file names in the usual manner (the
2127 non-standard file name for the main program is simply used as the
2128 argument to gnatmake). Note that if the extension is also non-standard,
2129 then it must be included in the @command{gnatmake} command, it may not
2130 be omitted.
2131
2132 @node Alternative File Naming Schemes
2133 @section Alternative File Naming Schemes
2134 @cindex File naming schemes, alternative
2135 @cindex File names
2136
2137 In the previous section, we described the use of the @code{Source_File_Name}
2138 pragma to allow arbitrary names to be assigned to individual source files.
2139 However, this approach requires one pragma for each file, and especially in
2140 large systems can result in very long @file{gnat.adc} files, and also create
2141 a maintenance problem.
2142
2143 GNAT also provides a facility for specifying systematic file naming schemes
2144 other than the standard default naming scheme previously described. An
2145 alternative scheme for naming is specified by the use of
2146 @code{Source_File_Name} pragmas having the following format:
2147 @cindex Source_File_Name pragma
2148
2149 @smallexample @c ada
2150 pragma Source_File_Name (
2151    Spec_File_Name  => FILE_NAME_PATTERN
2152  @r{[},Casing          => CASING_SPEC@r{]}
2153  @r{[},Dot_Replacement => STRING_LITERAL@r{]});
2154
2155 pragma Source_File_Name (
2156    Body_File_Name  => FILE_NAME_PATTERN
2157  @r{[},Casing          => CASING_SPEC@r{]}
2158  @r{[},Dot_Replacement => STRING_LITERAL@r{]});
2159
2160 pragma Source_File_Name (
2161    Subunit_File_Name  => FILE_NAME_PATTERN
2162  @r{[},Casing             => CASING_SPEC@r{]}
2163  @r{[},Dot_Replacement    => STRING_LITERAL@r{]});
2164
2165 FILE_NAME_PATTERN ::= STRING_LITERAL
2166 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
2167 @end smallexample
2168
2169 @noindent
2170 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
2171 It contains a single asterisk character, and the unit name is substituted
2172 systematically for this asterisk. The optional parameter
2173 @code{Casing} indicates
2174 whether the unit name is to be all upper-case letters, all lower-case letters,
2175 or mixed-case. If no
2176 @code{Casing} parameter is used, then the default is all
2177 ^lower-case^upper-case^.
2178
2179 The optional @code{Dot_Replacement} string is used to replace any periods
2180 that occur in subunit or child unit names. If no @code{Dot_Replacement}
2181 argument is used then separating dots appear unchanged in the resulting
2182 file name.
2183 Although the above syntax indicates that the
2184 @code{Casing} argument must appear
2185 before the @code{Dot_Replacement} argument, but it
2186 is also permissible to write these arguments in the opposite order.
2187
2188 As indicated, it is possible to specify different naming schemes for
2189 bodies, specs, and subunits. Quite often the rule for subunits is the
2190 same as the rule for bodies, in which case, there is no need to give
2191 a separate @code{Subunit_File_Name} rule, and in this case the
2192 @code{Body_File_name} rule is used for subunits as well.
2193
2194 The separate rule for subunits can also be used to implement the rather
2195 unusual case of a compilation environment (e.g.@: a single directory) which
2196 contains a subunit and a child unit with the same unit name. Although
2197 both units cannot appear in the same partition, the Ada Reference Manual
2198 allows (but does not require) the possibility of the two units coexisting
2199 in the same environment.
2200
2201 The file name translation works in the following steps:
2202
2203 @itemize @bullet
2204
2205 @item
2206 If there is a specific @code{Source_File_Name} pragma for the given unit,
2207 then this is always used, and any general pattern rules are ignored.
2208
2209 @item
2210 If there is a pattern type @code{Source_File_Name} pragma that applies to
2211 the unit, then the resulting file name will be used if the file exists. If
2212 more than one pattern matches, the latest one will be tried first, and the
2213 first attempt resulting in a reference to a file that exists will be used.
2214
2215 @item
2216 If no pattern type @code{Source_File_Name} pragma that applies to the unit
2217 for which the corresponding file exists, then the standard GNAT default
2218 naming rules are used.
2219
2220 @end itemize
2221
2222 @noindent
2223 As an example of the use of this mechanism, consider a commonly used scheme
2224 in which file names are all lower case, with separating periods copied
2225 unchanged to the resulting file name, and specs end with @file{.1.ada}, and
2226 bodies end with @file{.2.ada}. GNAT will follow this scheme if the following
2227 two pragmas appear:
2228
2229 @smallexample @c ada
2230 pragma Source_File_Name
2231   (Spec_File_Name => "*.1.ada");
2232 pragma Source_File_Name
2233   (Body_File_Name => "*.2.ada");
2234 @end smallexample
2235
2236 @noindent
2237 The default GNAT scheme is actually implemented by providing the following
2238 default pragmas internally:
2239
2240 @smallexample @c ada
2241 pragma Source_File_Name
2242   (Spec_File_Name => "*.ads", Dot_Replacement => "-");
2243 pragma Source_File_Name
2244   (Body_File_Name => "*.adb", Dot_Replacement => "-");
2245 @end smallexample
2246
2247 @noindent
2248 Our final example implements a scheme typically used with one of the
2249 Ada 83 compilers, where the separator character for subunits was ``__''
2250 (two underscores), specs were identified by adding @file{_.ADA}, bodies
2251 by adding @file{.ADA}, and subunits by
2252 adding @file{.SEP}. All file names were
2253 upper case. Child units were not present of course since this was an
2254 Ada 83 compiler, but it seems reasonable to extend this scheme to use
2255 the same double underscore separator for child units.
2256
2257 @smallexample @c ada
2258 pragma Source_File_Name
2259   (Spec_File_Name => "*_.ADA",
2260    Dot_Replacement => "__",
2261    Casing = Uppercase);
2262 pragma Source_File_Name
2263   (Body_File_Name => "*.ADA",
2264    Dot_Replacement => "__",
2265    Casing = Uppercase);
2266 pragma Source_File_Name
2267   (Subunit_File_Name => "*.SEP",
2268    Dot_Replacement => "__",
2269    Casing = Uppercase);
2270 @end smallexample
2271
2272 @node Generating Object Files
2273 @section Generating Object Files
2274
2275 @noindent
2276 An Ada program consists of a set of source files, and the first step in
2277 compiling the program is to generate the corresponding object files.
2278 These are generated by compiling a subset of these source files.
2279 The files you need to compile are the following:
2280
2281 @itemize @bullet
2282 @item
2283 If a package spec has no body, compile the package spec to produce the
2284 object file for the package.
2285
2286 @item
2287 If a package has both a spec and a body, compile the body to produce the
2288 object file for the package. The source file for the package spec need
2289 not be compiled in this case because there is only one object file, which
2290 contains the code for both the spec and body of the package.
2291
2292 @item
2293 For a subprogram, compile the subprogram body to produce the object file
2294 for the subprogram. The spec, if one is present, is as usual in a
2295 separate file, and need not be compiled.
2296
2297 @item
2298 @cindex Subunits
2299 In the case of subunits, only compile the parent unit. A single object
2300 file is generated for the entire subunit tree, which includes all the
2301 subunits.
2302
2303 @item
2304 Compile child units independently of their parent units
2305 (though, of course, the spec of all the ancestor unit must be present in order
2306 to compile a child unit).
2307
2308 @item
2309 @cindex Generics
2310 Compile generic units in the same manner as any other units. The object
2311 files in this case are small dummy files that contain at most the
2312 flag used for elaboration checking. This is because GNAT always handles generic
2313 instantiation by means of macro expansion. However, it is still necessary to
2314 compile generic units, for dependency checking and elaboration purposes.
2315 @end itemize
2316
2317 @noindent
2318 The preceding rules describe the set of files that must be compiled to
2319 generate the object files for a program. Each object file has the same
2320 name as the corresponding source file, except that the extension is
2321 @file{.o} as usual.
2322
2323 You may wish to compile other files for the purpose of checking their
2324 syntactic and semantic correctness. For example, in the case where a
2325 package has a separate spec and body, you would not normally compile the
2326 spec. However, it is convenient in practice to compile the spec to make
2327 sure it is error-free before compiling clients of this spec, because such
2328 compilations will fail if there is an error in the spec.
2329
2330 GNAT provides an option for compiling such files purely for the
2331 purposes of checking correctness; such compilations are not required as
2332 part of the process of building a program. To compile a file in this
2333 checking mode, use the @option{-gnatc} switch.
2334
2335 @node Source Dependencies
2336 @section Source Dependencies
2337
2338 @noindent
2339 A given object file clearly depends on the source file which is compiled
2340 to produce it. Here we are using @dfn{depends} in the sense of a typical
2341 @code{make} utility; in other words, an object file depends on a source
2342 file if changes to the source file require the object file to be
2343 recompiled.
2344 In addition to this basic dependency, a given object may depend on
2345 additional source files as follows:
2346
2347 @itemize @bullet
2348 @item
2349 If a file being compiled @code{with}'s a unit @var{X}, the object file
2350 depends on the file containing the spec of unit @var{X}. This includes
2351 files that are @code{with}'ed implicitly either because they are parents
2352 of @code{with}'ed child units or they are run-time units required by the
2353 language constructs used in a particular unit.
2354
2355 @item
2356 If a file being compiled instantiates a library level generic unit, the
2357 object file depends on both the spec and body files for this generic
2358 unit.
2359
2360 @item
2361 If a file being compiled instantiates a generic unit defined within a
2362 package, the object file depends on the body file for the package as
2363 well as the spec file.
2364
2365 @item
2366 @findex Inline
2367 @cindex @option{-gnatn} switch
2368 If a file being compiled contains a call to a subprogram for which
2369 pragma @code{Inline} applies and inlining is activated with the
2370 @option{-gnatn} switch, the object file depends on the file containing the
2371 body of this subprogram as well as on the file containing the spec. Note
2372 that for inlining to actually occur as a result of the use of this switch,
2373 it is necessary to compile in optimizing mode.
2374
2375 @cindex @option{-gnatN} switch
2376 The use of @option{-gnatN} activates  inlining optimization
2377 that is performed by the front end of the compiler. This inlining does
2378 not require that the code generation be optimized. Like @option{-gnatn},
2379 the use of this switch generates additional dependencies.
2380
2381 When using a gcc-based back end (in practice this means using any version
2382 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
2383 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
2384 Historically front end inlining was more extensive than the gcc back end
2385 inlining, but that is no longer the case.
2386
2387 @item
2388 If an object file @file{O} depends on the proper body of a subunit through
2389 inlining or instantiation, it depends on the parent unit of the subunit.
2390 This means that any modification of the parent unit or one of its subunits
2391 affects the compilation of @file{O}.
2392
2393 @item
2394 The object file for a parent unit depends on all its subunit body files.
2395
2396 @item
2397 The previous two rules meant that for purposes of computing dependencies and
2398 recompilation, a body and all its subunits are treated as an indivisible whole.
2399
2400 @noindent
2401 These rules are applied transitively: if unit @code{A} @code{with}'s
2402 unit @code{B}, whose elaboration calls an inlined procedure in package
2403 @code{C}, the object file for unit @code{A} will depend on the body of
2404 @code{C}, in file @file{c.adb}.
2405
2406 The set of dependent files described by these rules includes all the
2407 files on which the unit is semantically dependent, as dictated by the
2408 Ada language standard. However, it is a superset of what the
2409 standard describes, because it includes generic, inline, and subunit
2410 dependencies.
2411
2412 An object file must be recreated by recompiling the corresponding source
2413 file if any of the source files on which it depends are modified. For
2414 example, if the @code{make} utility is used to control compilation,
2415 the rule for an Ada object file must mention all the source files on
2416 which the object file depends, according to the above definition.
2417 The determination of the necessary
2418 recompilations is done automatically when one uses @command{gnatmake}.
2419 @end itemize
2420
2421 @node The Ada Library Information Files
2422 @section The Ada Library Information Files
2423 @cindex Ada Library Information files
2424 @cindex @file{ALI} files
2425
2426 @noindent
2427 Each compilation actually generates two output files. The first of these
2428 is the normal object file that has a @file{.o} extension. The second is a
2429 text file containing full dependency information. It has the same
2430 name as the source file, but an @file{.ali} extension.
2431 This file is known as the Ada Library Information (@file{ALI}) file.
2432 The following information is contained in the @file{ALI} file.
2433
2434 @itemize @bullet
2435 @item
2436 Version information (indicates which version of GNAT was used to compile
2437 the unit(s) in question)
2438
2439 @item
2440 Main program information (including priority and time slice settings,
2441 as well as the wide character encoding used during compilation).
2442
2443 @item
2444 List of arguments used in the @command{gcc} command for the compilation
2445
2446 @item
2447 Attributes of the unit, including configuration pragmas used, an indication
2448 of whether the compilation was successful, exception model used etc.
2449
2450 @item
2451 A list of relevant restrictions applying to the unit (used for consistency)
2452 checking.
2453
2454 @item
2455 Categorization information (e.g.@: use of pragma @code{Pure}).
2456
2457 @item
2458 Information on all @code{with}'ed units, including presence of
2459 @code{Elaborate} or @code{Elaborate_All} pragmas.
2460
2461 @item
2462 Information from any @code{Linker_Options} pragmas used in the unit
2463
2464 @item
2465 Information on the use of @code{Body_Version} or @code{Version}
2466 attributes in the unit.
2467
2468 @item
2469 Dependency information. This is a list of files, together with
2470 time stamp and checksum information. These are files on which
2471 the unit depends in the sense that recompilation is required
2472 if any of these units are modified.
2473
2474 @item
2475 Cross-reference data. Contains information on all entities referenced
2476 in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
2477 provide cross-reference information.
2478
2479 @end itemize
2480
2481 @noindent
2482 For a full detailed description of the format of the @file{ALI} file,
2483 see the source of the body of unit @code{Lib.Writ}, contained in file
2484 @file{lib-writ.adb} in the GNAT compiler sources.
2485
2486 @node Binding an Ada Program
2487 @section Binding an Ada Program
2488
2489 @noindent
2490 When using languages such as C and C++, once the source files have been
2491 compiled the only remaining step in building an executable program
2492 is linking the object modules together. This means that it is possible to
2493 link an inconsistent version of a program, in which two units have
2494 included different versions of the same header.
2495
2496 The rules of Ada do not permit such an inconsistent program to be built.
2497 For example, if two clients have different versions of the same package,
2498 it is illegal to build a program containing these two clients.
2499 These rules are enforced by the GNAT binder, which also determines an
2500 elaboration order consistent with the Ada rules.
2501
2502 The GNAT binder is run after all the object files for a program have
2503 been created. It is given the name of the main program unit, and from
2504 this it determines the set of units required by the program, by reading the
2505 corresponding ALI files. It generates error messages if the program is
2506 inconsistent or if no valid order of elaboration exists.
2507
2508 If no errors are detected, the binder produces a main program, in Ada by
2509 default, that contains calls to the elaboration procedures of those
2510 compilation unit that require them, followed by
2511 a call to the main program. This Ada program is compiled to generate the
2512 object file for the main program. The name of
2513 the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec
2514 @file{b~@var{xxx}.ads}) where @var{xxx} is the name of the
2515 main program unit.
2516
2517 Finally, the linker is used to build the resulting executable program,
2518 using the object from the main program from the bind step as well as the
2519 object files for the Ada units of the program.
2520
2521 @node Mixed Language Programming
2522 @section Mixed Language Programming
2523 @cindex Mixed Language Programming
2524
2525 @noindent
2526 This section describes how to develop a mixed-language program,
2527 specifically one that comprises units in both Ada and C.
2528
2529 @menu
2530 * Interfacing to C::
2531 * Calling Conventions::
2532 @end menu
2533
2534 @node Interfacing to C
2535 @subsection Interfacing to C
2536 @noindent
2537 Interfacing Ada with a foreign language such as C involves using
2538 compiler directives to import and/or export entity definitions in each
2539 language---using @code{extern} statements in C, for instance, and the
2540 @code{Import}, @code{Export}, and @code{Convention} pragmas in Ada.
2541 A full treatment of these topics is provided in Appendix B, section 1
2542 of the Ada Reference Manual.
2543
2544 There are two ways to build a program using GNAT that contains some Ada
2545 sources and some foreign language sources, depending on whether or not
2546 the main subprogram is written in Ada.  Here is a source example with
2547 the main subprogram in Ada:
2548
2549 @smallexample
2550 /* file1.c */
2551 #include <stdio.h>
2552
2553 void print_num (int num)
2554 @{
2555   printf ("num is %d.\n", num);
2556   return;
2557 @}
2558
2559 /* file2.c */
2560
2561 /* num_from_Ada is declared in my_main.adb */
2562 extern int num_from_Ada;
2563
2564 int get_num (void)
2565 @{
2566   return num_from_Ada;
2567 @}
2568 @end smallexample
2569
2570 @smallexample @c ada
2571 --  my_main.adb
2572 procedure My_Main is
2573
2574    --  Declare then export an Integer entity called num_from_Ada
2575    My_Num : Integer := 10;
2576    pragma Export (C, My_Num, "num_from_Ada");
2577
2578    --  Declare an Ada function spec for Get_Num, then use
2579    --  C function get_num for the implementation.
2580    function Get_Num return Integer;
2581    pragma Import (C, Get_Num, "get_num");
2582
2583    --  Declare an Ada procedure spec for Print_Num, then use
2584    --  C function print_num for the implementation.
2585    procedure Print_Num (Num : Integer);
2586    pragma Import (C, Print_Num, "print_num");
2587
2588 begin
2589    Print_Num (Get_Num);
2590 end My_Main;
2591 @end smallexample
2592
2593 @enumerate
2594 @item
2595 To build this example, first compile the foreign language files to
2596 generate object files:
2597 @smallexample
2598 ^gcc -c file1.c^gcc -c FILE1.C^
2599 ^gcc -c file2.c^gcc -c FILE2.C^
2600 @end smallexample
2601
2602 @item
2603 Then, compile the Ada units to produce a set of object files and ALI
2604 files:
2605 @smallexample
2606 gnatmake ^-c^/ACTIONS=COMPILE^ my_main.adb
2607 @end smallexample
2608
2609 @item
2610 Run the Ada binder on the Ada main program:
2611 @smallexample
2612 gnatbind my_main.ali
2613 @end smallexample
2614
2615 @item
2616 Link the Ada main program, the Ada objects and the other language
2617 objects:
2618 @smallexample
2619 gnatlink my_main.ali file1.o file2.o
2620 @end smallexample
2621 @end enumerate
2622
2623 The last three steps can be grouped in a single command:
2624 @smallexample
2625 gnatmake my_main.adb -largs file1.o file2.o
2626 @end smallexample
2627
2628 @cindex Binder output file
2629 @noindent
2630 If the main program is in a language other than Ada, then you may have
2631 more than one entry point into the Ada subsystem. You must use a special
2632 binder option to generate callable routines that initialize and
2633 finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}).
2634 Calls to the initialization and finalization routines must be inserted
2635 in the main program, or some other appropriate point in the code. The
2636 call to initialize the Ada units must occur before the first Ada
2637 subprogram is called, and the call to finalize the Ada units must occur
2638 after the last Ada subprogram returns. The binder will place the
2639 initialization and finalization subprograms into the
2640 @file{b~@var{xxx}.adb} file where they can be accessed by your C
2641 sources.  To illustrate, we have the following example:
2642
2643 @smallexample
2644 /* main.c */
2645 extern void adainit (void);
2646 extern void adafinal (void);
2647 extern int add (int, int);
2648 extern int sub (int, int);
2649
2650 int main (int argc, char *argv[])
2651 @{
2652   int a = 21, b = 7;
2653
2654   adainit();
2655
2656   /* Should print "21 + 7 = 28" */
2657   printf ("%d + %d = %d\n", a, b, add (a, b));
2658   /* Should print "21 - 7 = 14" */
2659   printf ("%d - %d = %d\n", a, b, sub (a, b));
2660
2661   adafinal();
2662 @}
2663 @end smallexample
2664
2665 @smallexample @c ada
2666 --  unit1.ads
2667 package Unit1 is
2668    function Add (A, B : Integer) return Integer;
2669    pragma Export (C, Add, "add");
2670 end Unit1;
2671
2672 --  unit1.adb
2673 package body Unit1 is
2674    function Add (A, B : Integer) return Integer is
2675    begin
2676       return A + B;
2677    end Add;
2678 end Unit1;
2679
2680 --  unit2.ads
2681 package Unit2 is
2682    function Sub (A, B : Integer) return Integer;
2683    pragma Export (C, Sub, "sub");
2684 end Unit2;
2685
2686 --  unit2.adb
2687 package body Unit2 is
2688    function Sub (A, B : Integer) return Integer is
2689    begin
2690       return A - B;
2691    end Sub;
2692 end Unit2;
2693 @end smallexample
2694
2695 @enumerate
2696 @item
2697 The build procedure for this application is similar to the last
2698 example's.  First, compile the foreign language files to generate object
2699 files:
2700 @smallexample
2701 ^gcc -c main.c^gcc -c main.c^
2702 @end smallexample
2703
2704 @item
2705 Next, compile the Ada units to produce a set of object files and ALI
2706 files:
2707 @smallexample
2708 gnatmake ^-c^/ACTIONS=COMPILE^ unit1.adb
2709 gnatmake ^-c^/ACTIONS=COMPILE^ unit2.adb
2710 @end smallexample
2711
2712 @item
2713 Run the Ada binder on every generated ALI file.  Make sure to use the
2714 @option{-n} option to specify a foreign main program:
2715 @smallexample
2716 gnatbind ^-n^/NOMAIN^ unit1.ali unit2.ali
2717 @end smallexample
2718
2719 @item
2720 Link the Ada main program, the Ada objects and the foreign language
2721 objects. You need only list the last ALI file here:
2722 @smallexample
2723 gnatlink unit2.ali main.o -o exec_file
2724 @end smallexample
2725
2726 This procedure yields a binary executable called @file{exec_file}.
2727 @end enumerate
2728
2729 @noindent
2730 Depending on the circumstances (for example when your non-Ada main object
2731 does not provide symbol @code{main}), you may also need to instruct the
2732 GNAT linker not to include the standard startup objects by passing the
2733 @option{^-nostartfiles^/NOSTART_FILES^} switch to @command{gnatlink}.
2734
2735 @node Calling Conventions
2736 @subsection Calling Conventions
2737 @cindex Foreign Languages
2738 @cindex Calling Conventions
2739 GNAT follows standard calling sequence conventions and will thus interface
2740 to any other language that also follows these conventions. The following
2741 Convention identifiers are recognized by GNAT:
2742
2743 @table @code
2744 @cindex Interfacing to Ada
2745 @cindex Other Ada compilers
2746 @cindex Convention Ada
2747 @item Ada
2748 This indicates that the standard Ada calling sequence will be
2749 used and all Ada data items may be passed without any limitations in the
2750 case where GNAT is used to generate both the caller and callee. It is also
2751 possible to mix GNAT generated code and code generated by another Ada
2752 compiler. In this case, the data types should be restricted to simple
2753 cases, including primitive types. Whether complex data types can be passed
2754 depends on the situation. Probably it is safe to pass simple arrays, such
2755 as arrays of integers or floats. Records may or may not work, depending
2756 on whether both compilers lay them out identically. Complex structures
2757 involving variant records, access parameters, tasks, or protected types,
2758 are unlikely to be able to be passed.
2759
2760 Note that in the case of GNAT running
2761 on a platform that supports HP Ada 83, a higher degree of compatibility
2762 can be guaranteed, and in particular records are layed out in an identical
2763 manner in the two compilers. Note also that if output from two different
2764 compilers is mixed, the program is responsible for dealing with elaboration
2765 issues. Probably the safest approach is to write the main program in the
2766 version of Ada other than GNAT, so that it takes care of its own elaboration
2767 requirements, and then call the GNAT-generated adainit procedure to ensure
2768 elaboration of the GNAT components. Consult the documentation of the other
2769 Ada compiler for further details on elaboration.
2770
2771 However, it is not possible to mix the tasking run time of GNAT and
2772 HP Ada 83, All the tasking operations must either be entirely within
2773 GNAT compiled sections of the program, or entirely within HP Ada 83
2774 compiled sections of the program.
2775
2776 @cindex Interfacing to Assembly
2777 @cindex Convention Assembler
2778 @item Assembler
2779 Specifies assembler as the convention. In practice this has the
2780 same effect as convention Ada (but is not equivalent in the sense of being
2781 considered the same convention).
2782
2783 @cindex Convention Asm
2784 @findex Asm
2785 @item Asm
2786 Equivalent to Assembler.
2787
2788 @cindex Interfacing to COBOL
2789 @cindex Convention COBOL
2790 @findex COBOL
2791 @item COBOL
2792 Data will be passed according to the conventions described
2793 in section B.4 of the Ada Reference Manual.
2794
2795 @findex C
2796 @cindex Interfacing to C
2797 @cindex Convention C
2798 @item C
2799 Data will be passed according to the conventions described
2800 in section B.3 of the Ada Reference Manual.
2801
2802 A note on interfacing to a C ``varargs'' function:
2803 @findex C varargs function
2804 @cindex Interfacing to C varargs function
2805 @cindex varargs function interfaces
2806
2807 @itemize @bullet
2808 @item
2809 In C, @code{varargs} allows a function to take a variable number of
2810 arguments. There is no direct equivalent in this to Ada. One
2811 approach that can be used is to create a C wrapper for each
2812 different profile and then interface to this C wrapper. For
2813 example, to print an @code{int} value using @code{printf},
2814 create a C function @code{printfi} that takes two arguments, a
2815 pointer to a string and an int, and calls @code{printf}.
2816 Then in the Ada program, use pragma @code{Import} to
2817 interface to @code{printfi}.
2818
2819 @item
2820 It may work on some platforms to directly interface to
2821 a @code{varargs} function by providing a specific Ada profile
2822 for a particular call. However, this does not work on
2823 all platforms, since there is no guarantee that the
2824 calling sequence for a two argument normal C function
2825 is the same as for calling a @code{varargs} C function with
2826 the same two arguments.
2827 @end itemize
2828
2829 @cindex Convention Default
2830 @findex Default
2831 @item Default
2832 Equivalent to C.
2833
2834 @cindex Convention External
2835 @findex External
2836 @item External
2837 Equivalent to C.
2838
2839 @ifclear vms
2840 @findex C++
2841 @cindex Interfacing to C++
2842 @cindex Convention C++
2843 @item C_Plus_Plus (or CPP)
2844 This stands for C++. For most purposes this is identical to C.
2845 See the separate description of the specialized GNAT pragmas relating to
2846 C++ interfacing for further details.
2847 @end ifclear
2848
2849 @findex Fortran
2850 @cindex Interfacing to Fortran
2851 @cindex Convention Fortran
2852 @item Fortran
2853 Data will be passed according to the conventions described
2854 in section B.5 of the Ada Reference Manual.
2855
2856 @item Intrinsic
2857 This applies to an intrinsic operation, as defined in the Ada
2858 Reference Manual. If a pragma Import (Intrinsic) applies to a subprogram,
2859 this means that the body of the subprogram is provided by the compiler itself,
2860 usually by means of an efficient code sequence, and that the user does not
2861 supply an explicit body for it. In an application program, the pragma may
2862 be applied to the following sets of names:
2863
2864 @itemize @bullet
2865 @item
2866 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right,
2867 Shift_Right_Arithmetic.  The corresponding subprogram declaration must have
2868 two formal parameters. The
2869 first one must be a signed integer type or a modular type with a binary
2870 modulus, and the second parameter must be of type Natural.
2871 The return type must be the same as the type of the first argument. The size
2872 of this type can only be 8, 16, 32, or 64.
2873
2874 @item
2875 Binary arithmetic operators: ``+'', ``-'', ``*'', ``/''
2876 The corresponding operator declaration must have parameters and result type
2877 that have the same root numeric type (for example, all three are long_float
2878 types). This simplifies the definition of operations that use type checking
2879 to perform dimensional checks:
2880
2881 @smallexample @c ada
2882 type Distance is new Long_Float;
2883 type Time     is new Long_Float;
2884 type Velocity is new Long_Float;
2885 function "/" (D : Distance; T : Time)
2886   return Velocity;
2887 pragma Import (Intrinsic, "/");
2888 @end smallexample
2889
2890 @noindent
2891 This common idiom is often programmed with a generic definition and an
2892 explicit body. The pragma makes it simpler to introduce such declarations.
2893 It incurs no overhead in compilation time or code size, because it is
2894 implemented as a single machine instruction.
2895
2896 @item
2897 General subprogram entities, to bind an Ada subprogram declaration to
2898 a compiler builtin by name with back-ends where such interfaces are
2899 available. A typical example is the set of ``__builtin'' functions
2900 exposed by the GCC back-end, as in the following example:
2901
2902 @smallexample @c ada
2903    function builtin_sqrt (F : Float) return Float;
2904    pragma Import (Intrinsic, builtin_sqrt, "__builtin_sqrtf");
2905 @end smallexample
2906
2907 Most of the GCC builtins are accessible this way, and as for other
2908 import conventions (e.g. C), it is the user's responsibility to ensure
2909 that the Ada subprogram profile matches the underlying builtin
2910 expectations.
2911 @end itemize
2912
2913 @noindent
2914
2915 @ifset unw
2916 @findex Stdcall
2917 @cindex Convention Stdcall
2918 @item Stdcall
2919 This is relevant only to Windows XP/2000/NT implementations of GNAT,
2920 and specifies that the @code{Stdcall} calling sequence will be used,
2921 as defined by the NT API. Nevertheless, to ease building
2922 cross-platform bindings this convention will be handled as a @code{C} calling
2923 convention on non-Windows platforms.
2924
2925 @findex DLL
2926 @cindex Convention DLL
2927 @item DLL
2928 This is equivalent to @code{Stdcall}.
2929
2930 @findex Win32
2931 @cindex Convention Win32
2932 @item Win32
2933 This is equivalent to @code{Stdcall}.
2934 @end ifset
2935
2936 @findex Stubbed
2937 @cindex Convention Stubbed
2938 @item Stubbed
2939 This is a special convention that indicates that the compiler
2940 should provide a stub body that raises @code{Program_Error}.
2941 @end table
2942
2943 @noindent
2944 GNAT additionally provides a useful pragma @code{Convention_Identifier}
2945 that can be used to parametrize conventions and allow additional synonyms
2946 to be specified. For example if you have legacy code in which the convention
2947 identifier Fortran77 was used for Fortran, you can use the configuration
2948 pragma:
2949
2950 @smallexample @c ada
2951 pragma Convention_Identifier (Fortran77, Fortran);
2952 @end smallexample
2953
2954 @noindent
2955 And from now on the identifier Fortran77 may be used as a convention
2956 identifier (for example in an @code{Import} pragma) with the same
2957 meaning as Fortran.
2958
2959 @ifclear vms
2960 @node Building Mixed Ada & C++ Programs
2961 @section Building Mixed Ada and C++ Programs
2962
2963 @noindent
2964 A programmer inexperienced with mixed-language development may find that
2965 building an application containing both Ada and C++ code can be a
2966 challenge.  This section gives a few
2967 hints that should make this task easier. The first section addresses
2968 the differences between interfacing with C and interfacing with C++.
2969 The second section
2970 looks into the delicate problem of linking the complete application from
2971 its Ada and C++ parts. The last section gives some hints on how the GNAT
2972 run-time library can be adapted in order to allow inter-language dispatching
2973 with a new C++ compiler.
2974
2975 @menu
2976 * Interfacing to C++::
2977 * Linking a Mixed C++ & Ada Program::
2978 * A Simple Example::
2979 * Interfacing with C++ at the Class Level::
2980 @end menu
2981
2982 @node Interfacing to C++
2983 @subsection Interfacing to C++
2984
2985 @noindent
2986 GNAT supports interfacing with the G++ compiler (or any C++ compiler
2987 generating code that is compatible with the G++ Application Binary
2988 Interface ---see http://www.codesourcery.com/archives/cxx-abi).
2989
2990 @noindent
2991 Interfacing can be done at 3 levels: simple data, subprograms, and
2992 classes. In the first two cases, GNAT offers a specific @code{Convention
2993 C_Plus_Plus} (or @code{CPP}) that behaves exactly like @code{Convention C}.
2994 Usually, C++ mangles the names of subprograms, and currently, GNAT does
2995 not provide any help to solve the demangling problem. This problem can be
2996 addressed in two ways:
2997 @itemize @bullet
2998 @item
2999 by modifying the C++ code in order to force a C convention using
3000 the @code{extern "C"} syntax.
3001
3002 @item
3003 by figuring out the mangled name and use it as the Link_Name argument of
3004 the pragma import.
3005 @end itemize
3006
3007 @noindent
3008 Interfacing at the class level can be achieved by using the GNAT specific
3009 pragmas such as @code{CPP_Constructor}.  @xref{Interfacing to C++,,,
3010 gnat_rm, GNAT Reference Manual}, for additional information.
3011
3012 @node Linking a Mixed C++ & Ada Program
3013 @subsection Linking a Mixed C++ & Ada Program
3014
3015 @noindent
3016 Usually the linker of the C++ development system must be used to link
3017 mixed applications because most C++ systems will resolve elaboration
3018 issues (such as calling constructors on global class instances)
3019 transparently during the link phase. GNAT has been adapted to ease the
3020 use of a foreign linker for the last phase. Three cases can be
3021 considered:
3022 @enumerate
3023
3024 @item
3025 Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
3026 The C++ linker can simply be called by using the C++ specific driver
3027 called @code{c++}. Note that this setup is not very common because it
3028 may involve recompiling the whole GCC tree from sources, which makes it
3029 harder to upgrade the compilation system for one language without
3030 destabilizing the other.
3031
3032 @smallexample
3033 $ c++ -c file1.C
3034 $ c++ -c file2.C
3035 $ gnatmake ada_unit -largs file1.o file2.o --LINK=c++
3036 @end smallexample
3037
3038 @item
3039 Using GNAT and G++ from two different GCC installations: If both
3040 compilers are on the @env{PATH}, the previous method may be used. It is
3041 important to note that environment variables such as
3042 @env{C_INCLUDE_PATH}, @env{GCC_EXEC_PREFIX}, @env{BINUTILS_ROOT}, and
3043 @env{GCC_ROOT} will affect both compilers
3044 at the same time and may make one of the two compilers operate
3045 improperly if set during invocation of the wrong compiler.  It is also
3046 very important that the linker uses the proper @file{libgcc.a} GCC
3047 library -- that is, the one from the C++ compiler installation. The
3048 implicit link command as suggested in the @command{gnatmake} command
3049 from the former example can be replaced by an explicit link command with
3050 the full-verbosity option in order to verify which library is used:
3051 @smallexample
3052 $ gnatbind ada_unit
3053 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
3054 @end smallexample
3055 If there is a problem due to interfering environment variables, it can
3056 be worked around by using an intermediate script. The following example
3057 shows the proper script to use when GNAT has not been installed at its
3058 default location and g++ has been installed at its default location:
3059
3060 @smallexample
3061 $ cat ./my_script
3062 #!/bin/sh
3063 unset BINUTILS_ROOT
3064 unset GCC_ROOT
3065 c++ $*
3066 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
3067 @end smallexample
3068
3069 @item
3070 Using a non-GNU C++ compiler: The commands previously described can be
3071 used to insure that the C++ linker is used. Nonetheless, you need to add
3072 a few more parameters to the link command line, depending on the exception
3073 mechanism used.
3074
3075 If the @code{setjmp/longjmp} exception mechanism is used, only the paths
3076 to the libgcc libraries are required:
3077
3078 @smallexample
3079 $ cat ./my_script
3080 #!/bin/sh
3081 CC $* `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a`
3082 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3083 @end smallexample
3084
3085 Where CC is the name of the non-GNU C++ compiler.
3086
3087 If the @code{zero cost} exception mechanism is used, and the platform
3088 supports automatic registration of exception tables (e.g.@: Solaris or IRIX),
3089 paths to more objects are required:
3090
3091 @smallexample
3092 $ cat ./my_script
3093 #!/bin/sh
3094 CC `gcc -print-file-name=crtbegin.o` $* \
3095 `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a` \
3096 `gcc -print-file-name=crtend.o`
3097 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3098 @end smallexample
3099
3100 If the @code{zero cost} exception mechanism is used, and the platform
3101 doesn't support automatic registration of exception tables (e.g.@: HP-UX,
3102 Tru64 or AIX), the simple approach described above will not work and
3103 a pre-linking phase using GNAT will be necessary.
3104
3105 @end enumerate
3106
3107 @node A Simple Example
3108 @subsection  A Simple Example
3109 @noindent
3110 The following example, provided as part of the GNAT examples, shows how
3111 to achieve procedural interfacing between Ada and C++ in both
3112 directions. The C++ class A has two methods. The first method is exported
3113 to Ada by the means of an extern C wrapper function. The second method
3114 calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
3115 a limited record with a layout comparable to the C++ class. The Ada
3116 subprogram, in turn, calls the C++ method. So, starting from the C++
3117 main program, the process passes back and forth between the two
3118 languages.
3119
3120 @noindent
3121 Here are the compilation commands:
3122 @smallexample
3123 $ gnatmake -c simple_cpp_interface
3124 $ c++ -c cpp_main.C
3125 $ c++ -c ex7.C
3126 $ gnatbind -n simple_cpp_interface
3127 $ gnatlink simple_cpp_interface -o cpp_main --LINK=$(CPLUSPLUS)
3128       -lstdc++ ex7.o cpp_main.o
3129 @end smallexample
3130
3131 @noindent
3132 Here are the corresponding sources:
3133 @smallexample
3134
3135 //cpp_main.C
3136
3137 #include "ex7.h"
3138
3139 extern "C" @{
3140   void adainit (void);
3141   void adafinal (void);
3142   void method1 (A *t);
3143 @}
3144
3145 void method1 (A *t)
3146 @{
3147   t->method1 ();
3148 @}
3149
3150 int main ()
3151 @{
3152   A obj;
3153   adainit ();
3154   obj.method2 (3030);
3155   adafinal ();
3156 @}
3157
3158 //ex7.h
3159
3160 class Origin @{
3161  public:
3162   int o_value;
3163 @};
3164 class A : public Origin @{
3165  public:
3166   void method1 (void);
3167   void method2 (int v);
3168   A();
3169   int   a_value;
3170 @};
3171
3172 //ex7.C
3173
3174 #include "ex7.h"
3175 #include <stdio.h>
3176
3177 extern "C" @{ void ada_method2 (A *t, int v);@}
3178
3179 void A::method1 (void)
3180 @{
3181   a_value = 2020;
3182   printf ("in A::method1, a_value = %d \n",a_value);
3183
3184 @}
3185
3186 void A::method2 (int v)
3187 @{
3188    ada_method2 (this, v);
3189    printf ("in A::method2, a_value = %d \n",a_value);
3190
3191 @}
3192
3193 A::A(void)
3194 @{
3195    a_value = 1010;
3196   printf ("in A::A, a_value = %d \n",a_value);
3197 @}
3198 @end smallexample
3199
3200 @smallexample @c ada
3201 -- Ada sources
3202 package body Simple_Cpp_Interface is
3203
3204    procedure Ada_Method2 (This : in out A; V : Integer) is
3205    begin
3206       Method1 (This);
3207       This.A_Value := V;
3208    end Ada_Method2;
3209
3210 end Simple_Cpp_Interface;
3211
3212 with System;
3213 package Simple_Cpp_Interface is
3214    type A is limited
3215       record
3216          Vptr    : System.Address;
3217          O_Value : Integer;
3218          A_Value : Integer;
3219       end record;
3220    pragma Convention (C, A);
3221
3222    procedure Method1 (This : in out A);
3223    pragma Import (C, Method1);
3224
3225    procedure Ada_Method2 (This : in out A; V : Integer);
3226    pragma Export (C, Ada_Method2);
3227
3228 end Simple_Cpp_Interface;
3229 @end smallexample
3230
3231 @node Interfacing with C++ at the Class Level
3232 @subsection Interfacing with C++ at the Class Level
3233 @noindent
3234 In this section we demonstrate the GNAT features for interfacing with
3235 C++ by means of an example making use of Ada 2005 abstract interface
3236 types. This example consists of a classification of animals; classes
3237 have been used to model our main classification of animals, and
3238 interfaces provide support for the management of secondary
3239 classifications. We first demonstrate a case in which the types and
3240 constructors are defined on the C++ side and imported from the Ada
3241 side, and latter the reverse case.
3242
3243 The root of our derivation will be the @code{Animal} class, with a
3244 single private attribute (the @code{Age} of the animal) and two public
3245 primitives to set and get the value of this attribute.
3246
3247 @smallexample
3248 @b{class} Animal @{
3249  @b{public}:
3250    @b{virtual} void Set_Age (int New_Age);
3251    @b{virtual} int Age ();
3252  @b{private}:
3253    int Age_Count;
3254 @};
3255 @end smallexample
3256
3257 Abstract interface types are defined in C++ by means of classes with pure
3258 virtual functions and no data members. In our example we will use two
3259 interfaces that provide support for the common management of @code{Carnivore}
3260 and @code{Domestic} animals:
3261
3262 @smallexample
3263 @b{class} Carnivore @{
3264 @b{public}:
3265    @b{virtual} int Number_Of_Teeth () = 0;
3266 @};
3267
3268 @b{class} Domestic @{
3269 @b{public}:
3270    @b{virtual void} Set_Owner (char* Name) = 0;
3271 @};
3272 @end smallexample
3273
3274 Using these declarations, we can now say that a @code{Dog} is an animal that is
3275 both Carnivore and Domestic, that is:
3276
3277 @smallexample
3278 @b{class} Dog : Animal, Carnivore, Domestic @{
3279  @b{public}:
3280    @b{virtual} int  Number_Of_Teeth ();
3281    @b{virtual} void Set_Owner (char* Name);
3282
3283    Dog(); // Constructor
3284  @b{private}:
3285    int  Tooth_Count;
3286    char *Owner;
3287 @};
3288 @end smallexample
3289
3290 In the following examples we will assume that the previous declarations are
3291 located in a file named @code{animals.h}. The following package demonstrates
3292 how to import these C++ declarations from the Ada side:
3293
3294 @smallexample @c ada
3295 with Interfaces.C.Strings; use Interfaces.C.Strings;
3296 package Animals is
3297   type Carnivore is interface;
3298   pragma Convention (C_Plus_Plus, Carnivore);
3299   function Number_Of_Teeth (X : Carnivore)
3300      return Natural is abstract;
3301
3302   type Domestic is interface;
3303   pragma Convention (C_Plus_Plus, Set_Owner);
3304   procedure Set_Owner
3305     (X    : in out Domestic;
3306      Name : Chars_Ptr) is abstract;
3307
3308   type Animal is tagged record
3309     Age : Natural := 0;
3310   end record;
3311   pragma Import (C_Plus_Plus, Animal);
3312
3313   procedure Set_Age (X : in out Animal; Age : Integer);
3314   pragma Import (C_Plus_Plus, Set_Age);
3315
3316   function Age (X : Animal) return Integer;
3317   pragma Import (C_Plus_Plus, Age);
3318
3319   type Dog is new Animal and Carnivore and Domestic with record
3320     Tooth_Count : Natural;
3321     Owner       : String (1 .. 30);
3322   end record;
3323   pragma Import (C_Plus_Plus, Dog);
3324
3325   function Number_Of_Teeth (A : Dog) return Integer;
3326   pragma Import (C_Plus_Plus, Number_Of_Teeth);
3327
3328   procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3329   pragma Import (C_Plus_Plus, Set_Owner);
3330
3331   function New_Dog return Dog'Class;
3332   pragma CPP_Constructor (New_Dog);
3333   pragma Import (CPP, New_Dog, "_ZN3DogC2Ev");
3334 end Animals;
3335 @end smallexample
3336
3337 Thanks to the compatibility between GNAT run-time structures and the C++ ABI,
3338 interfacing with these C++ classes is easy. The only requirement is that all
3339 the primitives and components must be declared exactly in the same order in
3340 the two languages.
3341
3342 Regarding the abstract interfaces, we must indicate to the GNAT compiler by
3343 means of a @code{pragma Convention (C_Plus_Plus)}, the convention used to pass
3344 the arguments to the called primitives will be the same as for C++. For the
3345 imported classes we use @code{pragma Import} with convention @code{C_Plus_Plus}
3346 to indicate that they have been defined on the C++ side; this is required
3347 because the dispatch table associated with these tagged types will be built
3348 in the C++ side and therefore will not contain the predefined Ada primitives
3349 which Ada would otherwise expect.
3350
3351 As the reader can see there is no need to indicate the C++ mangled names
3352 associated with each subprogram because it is assumed that all the calls to
3353 these primitives will be dispatching calls. The only exception is the
3354 constructor, which must be registered with the compiler by means of
3355 @code{pragma CPP_Constructor} and needs to provide its associated C++
3356 mangled name because the Ada compiler generates direct calls to it.
3357
3358 With the above packages we can now declare objects of type Dog on the Ada side
3359 and dispatch calls to the corresponding subprograms on the C++ side. We can
3360 also extend the tagged type Dog with further fields and primitives, and
3361 override some of its C++ primitives on the Ada side. For example, here we have
3362 a type derivation defined on the Ada side that inherits all the dispatching
3363 primitives of the ancestor from the C++ side.
3364
3365 @smallexample
3366 @b{with} Animals; @b{use} Animals;
3367 @b{package} Vaccinated_Animals @b{is}
3368   @b{type} Vaccinated_Dog @b{is new} Dog @b{with null record};
3369   @b{function} Vaccination_Expired (A : Vaccinated_Dog) @b{return} Boolean;
3370 @b{end} Vaccinated_Animals;
3371 @end smallexample
3372
3373 It is important to note that, because of the ABI compatibility, the programmer
3374 does not need to add any further information to indicate either the object
3375 layout or the dispatch table entry associated with each dispatching operation.
3376
3377 Now let us define all the types and constructors on the Ada side and export
3378 them to C++, using the same hierarchy of our previous example:
3379
3380 @smallexample @c ada
3381 with Interfaces.C.Strings;
3382 use Interfaces.C.Strings;
3383 package Animals is
3384   type Carnivore is interface;
3385   pragma Convention (C_Plus_Plus, Carnivore);
3386   function Number_Of_Teeth (X : Carnivore)
3387      return Natural is abstract;
3388
3389   type Domestic is interface;
3390   pragma Convention (C_Plus_Plus, Set_Owner);
3391   procedure Set_Owner
3392     (X    : in out Domestic;
3393      Name : Chars_Ptr) is abstract;
3394
3395   type Animal is tagged record
3396     Age : Natural := 0;
3397   end record;
3398   pragma Convention (C_Plus_Plus, Animal);
3399
3400   procedure Set_Age (X : in out Animal; Age : Integer);
3401   pragma Export (C_Plus_Plus, Set_Age);
3402
3403   function Age (X : Animal) return Integer;
3404   pragma Export (C_Plus_Plus, Age);
3405
3406   type Dog is new Animal and Carnivore and Domestic with record
3407     Tooth_Count : Natural;
3408     Owner       : String (1 .. 30);
3409   end record;
3410   pragma Convention (C_Plus_Plus, Dog);
3411
3412   function Number_Of_Teeth (A : Dog) return Integer;
3413   pragma Export (C_Plus_Plus, Number_Of_Teeth);
3414
3415   procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3416   pragma Export (C_Plus_Plus, Set_Owner);
3417
3418   function New_Dog return Dog'Class;
3419   pragma Export (C_Plus_Plus, New_Dog);
3420 end Animals;
3421 @end smallexample
3422
3423 Compared with our previous example the only difference is the use of
3424 @code{pragma Export} to indicate to the GNAT compiler that the primitives will
3425 be available to C++. Thanks to the ABI compatibility, on the C++ side there is
3426 nothing else to be done; as explained above, the only requirement is that all
3427 the primitives and components are declared in exactly the same order.
3428
3429 For completeness, let us see a brief C++ main program that uses the
3430 declarations available in @code{animals.h} (presented in our first example) to
3431 import and use the declarations from the Ada side, properly initializing and
3432 finalizing the Ada run-time system along the way:
3433
3434 @smallexample
3435 @b{#include} "animals.h"
3436 @b{#include} <iostream>
3437 @b{using namespace} std;
3438
3439 void Check_Carnivore (Carnivore *obj) @{@dots{}@}
3440 void Check_Domestic (Domestic *obj)   @{@dots{}@}
3441 void Check_Animal (Animal *obj)       @{@dots{}@}
3442 void Check_Dog (Dog *obj)             @{@dots{}@}
3443
3444 @b{extern} "C" @{
3445   void adainit (void);
3446   void adafinal (void);
3447   Dog* new_dog ();
3448 @}
3449
3450 void test ()
3451 @{
3452   Dog *obj = new_dog();  // Ada constructor
3453   Check_Carnivore (obj); // Check secondary DT
3454   Check_Domestic (obj);  // Check secondary DT
3455   Check_Animal (obj);    // Check primary DT
3456   Check_Dog (obj);       // Check primary DT
3457 @}
3458
3459 int main ()
3460 @{
3461   adainit ();  test();  adafinal ();
3462   return 0;
3463 @}
3464 @end smallexample
3465
3466 @node Comparison between GNAT and C/C++ Compilation Models
3467 @section Comparison between GNAT and C/C++ Compilation Models
3468
3469 @noindent
3470 The GNAT model of compilation is close to the C and C++ models. You can
3471 think of Ada specs as corresponding to header files in C. As in C, you
3472 don't need to compile specs; they are compiled when they are used. The
3473 Ada @code{with} is similar in effect to the @code{#include} of a C
3474 header.
3475
3476 One notable difference is that, in Ada, you may compile specs separately
3477 to check them for semantic and syntactic accuracy. This is not always
3478 possible with C headers because they are fragments of programs that have
3479 less specific syntactic or semantic rules.
3480
3481 The other major difference is the requirement for running the binder,
3482 which performs two important functions. First, it checks for
3483 consistency. In C or C++, the only defense against assembling
3484 inconsistent programs lies outside the compiler, in a makefile, for
3485 example. The binder satisfies the Ada requirement that it be impossible
3486 to construct an inconsistent program when the compiler is used in normal
3487 mode.
3488
3489 @cindex Elaboration order control
3490 The other important function of the binder is to deal with elaboration
3491 issues. There are also elaboration issues in C++ that are handled
3492 automatically. This automatic handling has the advantage of being
3493 simpler to use, but the C++ programmer has no control over elaboration.
3494 Where @code{gnatbind} might complain there was no valid order of
3495 elaboration, a C++ compiler would simply construct a program that
3496 malfunctioned at run time.
3497 @end ifclear
3498
3499 @node Comparison between GNAT and Conventional Ada Library Models
3500 @section Comparison between GNAT and Conventional Ada Library Models
3501
3502 @noindent
3503 This section is intended for Ada programmers who have
3504 used an Ada compiler implementing the traditional Ada library
3505 model, as described in the Ada Reference Manual.
3506
3507 @cindex GNAT library
3508 In GNAT, there is no ``library'' in the normal sense. Instead, the set of
3509 source files themselves acts as the library. Compiling Ada programs does
3510 not generate any centralized information, but rather an object file and
3511 a ALI file, which are of interest only to the binder and linker.
3512 In a traditional system, the compiler reads information not only from
3513 the source file being compiled, but also from the centralized library.
3514 This means that the effect of a compilation depends on what has been
3515 previously compiled. In particular:
3516
3517 @itemize @bullet
3518 @item
3519 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3520 to the version of the unit most recently compiled into the library.
3521
3522 @item
3523 Inlining is effective only if the necessary body has already been
3524 compiled into the library.
3525
3526 @item
3527 Compiling a unit may obsolete other units in the library.
3528 @end itemize
3529
3530 @noindent
3531 In GNAT, compiling one unit never affects the compilation of any other
3532 units because the compiler reads only source files. Only changes to source
3533 files can affect the results of a compilation. In particular:
3534
3535 @itemize @bullet
3536 @item
3537 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3538 to the source version of the unit that is currently accessible to the
3539 compiler.
3540
3541 @item
3542 @cindex Inlining
3543 Inlining requires the appropriate source files for the package or
3544 subprogram bodies to be available to the compiler. Inlining is always
3545 effective, independent of the order in which units are complied.
3546
3547 @item
3548 Compiling a unit never affects any other compilations. The editing of
3549 sources may cause previous compilations to be out of date if they
3550 depended on the source file being modified.
3551 @end itemize
3552
3553 @noindent
3554 The most important result of these differences is that order of compilation
3555 is never significant in GNAT. There is no situation in which one is
3556 required to do one compilation before another. What shows up as order of
3557 compilation requirements in the traditional Ada library becomes, in
3558 GNAT, simple source dependencies; in other words, there is only a set
3559 of rules saying what source files must be present when a file is
3560 compiled.
3561
3562 @ifset vms
3563 @node Placement of temporary files
3564 @section Placement of temporary files
3565 @cindex Temporary files (user control over placement)
3566
3567 @noindent
3568 GNAT creates temporary files in the directory designated by the environment
3569 variable @env{TMPDIR}.
3570 (See the HP @emph{C RTL Reference Manual} on the function @code{getenv()}
3571 for detailed information on how environment variables are resolved.
3572 For most users the easiest way to make use of this feature is to simply
3573 define @env{TMPDIR} as a job level logical name).
3574 For example, if you wish to use a Ramdisk (assuming DECRAM is installed)
3575 for compiler temporary files, then you can include something like the
3576 following command in your @file{LOGIN.COM} file:
3577
3578 @smallexample
3579 $ define/job TMPDIR "/disk$scratchram/000000/temp/"
3580 @end smallexample
3581
3582 @noindent
3583 If @env{TMPDIR} is not defined, then GNAT uses the directory designated by
3584 @env{TMP}; if @env{TMP} is not defined, then GNAT uses the directory
3585 designated by @env{TEMP}.
3586 If none of these environment variables are defined then GNAT uses the
3587 directory designated by the logical name @code{SYS$SCRATCH:}
3588 (by default the user's home directory). If all else fails
3589 GNAT uses the current directory for temporary files.
3590 @end ifset
3591
3592 @c *************************
3593 @node Compiling Using gcc
3594 @chapter Compiling Using @command{gcc}
3595
3596 @noindent
3597 This chapter discusses how to compile Ada programs using the @command{gcc}
3598 command. It also describes the set of switches
3599 that can be used to control the behavior of the compiler.
3600 @menu
3601 * Compiling Programs::
3602 * Switches for gcc::
3603 * Search Paths and the Run-Time Library (RTL)::
3604 * Order of Compilation Issues::
3605 * Examples::
3606 @end menu
3607
3608 @node Compiling Programs
3609 @section Compiling Programs
3610
3611 @noindent
3612 The first step in creating an executable program is to compile the units
3613 of the program using the @command{gcc} command. You must compile the
3614 following files:
3615
3616 @itemize @bullet
3617 @item
3618 the body file (@file{.adb}) for a library level subprogram or generic
3619 subprogram
3620
3621 @item
3622 the spec file (@file{.ads}) for a library level package or generic
3623 package that has no body
3624
3625 @item
3626 the body file (@file{.adb}) for a library level package
3627 or generic package that has a body
3628
3629 @end itemize
3630
3631 @noindent
3632 You need @emph{not} compile the following files
3633
3634 @itemize @bullet
3635
3636 @item
3637 the spec of a library unit which has a body
3638
3639 @item
3640 subunits
3641 @end itemize
3642
3643 @noindent
3644 because they are compiled as part of compiling related units. GNAT
3645 package specs
3646 when the corresponding body is compiled, and subunits when the parent is
3647 compiled.
3648
3649 @cindex cannot generate code
3650 If you attempt to compile any of these files, you will get one of the
3651 following error messages (where @var{fff} is the name of the file you compiled):
3652
3653 @smallexample
3654 cannot generate code for file @var{fff} (package spec)
3655 to check package spec, use -gnatc
3656
3657 cannot generate code for file @var{fff} (missing subunits)
3658 to check parent unit, use -gnatc
3659
3660 cannot generate code for file @var{fff} (subprogram spec)
3661 to check subprogram spec, use -gnatc
3662
3663 cannot generate code for file @var{fff} (subunit)
3664 to check subunit, use -gnatc
3665 @end smallexample
3666
3667 @noindent
3668 As indicated by the above error messages, if you want to submit
3669 one of these files to the compiler to check for correct semantics
3670 without generating code, then use the @option{-gnatc} switch.
3671
3672 The basic command for compiling a file containing an Ada unit is
3673
3674 @smallexample
3675 $ gcc -c @ovar{switches} @file{file name}
3676 @end smallexample
3677
3678 @noindent
3679 where @var{file name} is the name of the Ada file (usually
3680 having an extension
3681 @file{.ads} for a spec or @file{.adb} for a body).
3682 @ifclear vms
3683 You specify the
3684 @option{-c} switch to tell @command{gcc} to compile, but not link, the file.
3685 @end ifclear
3686 The result of a successful compilation is an object file, which has the
3687 same name as the source file but an extension of @file{.o} and an Ada
3688 Library Information (ALI) file, which also has the same name as the
3689 source file, but with @file{.ali} as the extension. GNAT creates these
3690 two output files in the current directory, but you may specify a source
3691 file in any directory using an absolute or relative path specification
3692 containing the directory information.
3693
3694 @findex gnat1
3695 @command{gcc} is actually a driver program that looks at the extensions of
3696 the file arguments and loads the appropriate compiler. For example, the
3697 GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}.
3698 These programs are in directories known to the driver program (in some
3699 configurations via environment variables you set), but need not be in
3700 your path. The @command{gcc} driver also calls the assembler and any other
3701 utilities needed to complete the generation of the required object
3702 files.
3703
3704 It is possible to supply several file names on the same @command{gcc}
3705 command. This causes @command{gcc} to call the appropriate compiler for
3706 each file. For example, the following command lists three separate
3707 files to be compiled:
3708
3709 @smallexample
3710 $ gcc -c x.adb y.adb z.c
3711 @end smallexample
3712
3713 @noindent
3714 calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and
3715 @file{y.adb}, and @code{cc1} (the C compiler) once to compile @file{z.c}.
3716 The compiler generates three object files @file{x.o}, @file{y.o} and
3717 @file{z.o} and the two ALI files @file{x.ali} and @file{y.ali} from the
3718 Ada compilations. Any switches apply to all the files ^listed,^listed.^
3719 @ifclear vms
3720 except for
3721 @option{-gnat@var{x}} switches, which apply only to Ada compilations.
3722 @end ifclear
3723
3724 @node Switches for gcc
3725 @section Switches for @command{gcc}
3726
3727 @noindent
3728 The @command{gcc} command accepts switches that control the
3729 compilation process. These switches are fully described in this section.
3730 First we briefly list all the switches, in alphabetical order, then we
3731 describe the switches in more detail in functionally grouped sections.
3732
3733 More switches exist for GCC than those documented here, especially
3734 for specific targets. However, their use is not recommended as
3735 they may change code generation in ways that are incompatible with
3736 the Ada run-time library, or can cause inconsistencies between
3737 compilation units.
3738
3739 @menu
3740 * Output and Error Message Control::
3741 * Warning Message Control::
3742 * Debugging and Assertion Control::
3743 * Validity Checking::
3744 * Style Checking::
3745 * Run-Time Checks::
3746 * Using gcc for Syntax Checking::
3747 * Using gcc for Semantic Checking::
3748 * Compiling Different Versions of Ada::
3749 * Character Set Control::
3750 * File Naming Control::
3751 * Subprogram Inlining Control::
3752 * Auxiliary Output Control::
3753 * Debugging Control::
3754 * Exception Handling Control::
3755 * Units to Sources Mapping Files::
3756 * Integrated Preprocessing::
3757 * Code Generation Control::
3758 @ifset vms
3759 * Return Codes::
3760 @end ifset
3761 @end menu
3762
3763 @table @option
3764 @c !sort!
3765 @ifclear vms
3766 @cindex @option{-b} (@command{gcc})
3767 @item -b @var{target}
3768 Compile your program to run on @var{target}, which is the name of a
3769 system configuration. You must have a GNAT cross-compiler built if
3770 @var{target} is not the same as your host system.
3771
3772 @item -B@var{dir}
3773 @cindex @option{-B} (@command{gcc})
3774 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
3775 from @var{dir} instead of the default location. Only use this switch
3776 when multiple versions of the GNAT compiler are available.
3777 @xref{Directory Options,, Options for Directory Search, gcc, Using the
3778 GNU Compiler Collection (GCC)}, for further details. You would normally
3779 use the @option{-b} or @option{-V} switch instead.
3780
3781 @item -c
3782 @cindex @option{-c} (@command{gcc})
3783 Compile. Always use this switch when compiling Ada programs.
3784
3785 Note: for some other languages when using @command{gcc}, notably in
3786 the case of C and C++, it is possible to use
3787 use @command{gcc} without a @option{-c} switch to
3788 compile and link in one step. In the case of GNAT, you
3789 cannot use this approach, because the binder must be run
3790 and @command{gcc} cannot be used to run the GNAT binder.
3791 @end ifclear
3792
3793 @item -fno-inline
3794 @cindex @option{-fno-inline} (@command{gcc})
3795 Suppresses all back-end inlining, even if other optimization or inlining
3796 switches are set.
3797 This includes suppression of inlining that results
3798 from the use of the pragma @code{Inline_Always}.
3799 Any occurrences of pragma @code{Inline} or @code{Inline_Always}
3800 are ignored, and @option{-gnatn} and @option{-gnatN} have no
3801 effect if this switch is present.
3802
3803 @item -fno-inline-functions
3804 @cindex @option{-fno-inline-functions} (@command{gcc})
3805 Suppresses automatic inlining of small subprograms, which is enabled
3806 if @option{-O3} is used.
3807
3808 @item -fno-inline-functions-called-once
3809 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
3810 Suppresses inlining of subprograms local to the unit and called once
3811 from within it, which is enabled if @option{-O1} is used.
3812
3813 @item -fno-strict-aliasing
3814 @cindex @option{-fno-strict-aliasing} (@command{gcc})
3815 Causes the compiler to avoid assumptions regarding non-aliasing
3816 of objects of different types. See
3817 @ref{Optimization and Strict Aliasing} for details.
3818
3819 @item -fstack-check
3820 @cindex @option{-fstack-check} (@command{gcc})
3821 Activates stack checking.
3822 See @ref{Stack Overflow Checking} for details.
3823
3824 @item -fstack-usage
3825 @cindex @option{-fstack-usage} (@command{gcc})
3826 Makes the compiler output stack usage information for the program, on a
3827 per-function basis. See @ref{Static Stack Usage Analysis} for details.
3828
3829 @item -fcallgraph-info@r{[}=su@r{]}
3830 @cindex @option{-fcallgraph-info} (@command{gcc})
3831 Makes the compiler output callgraph information for the program, on a
3832 per-file basis.  The information is generated in the VCG format.  It can
3833 be decorated with stack-usage per-node information.
3834
3835 @item ^-g^/DEBUG^
3836 @cindex @option{^-g^/DEBUG^} (@command{gcc})
3837 Generate debugging information. This information is stored in the object
3838 file and copied from there to the final executable file by the linker,
3839 where it can be read by the debugger. You must use the
3840 @option{^-g^/DEBUG^} switch if you plan on using the debugger.
3841
3842 @item -gnat83
3843 @cindex @option{-gnat83} (@command{gcc})
3844 Enforce Ada 83 restrictions.
3845
3846 @item -gnat95
3847 @cindex @option{-gnat95} (@command{gcc})
3848 Enforce Ada 95 restrictions.
3849
3850 @item -gnat05
3851 @cindex @option{-gnat05} (@command{gcc})
3852 Allow full Ada 2005 features.
3853
3854 @item -gnata
3855 @cindex @option{-gnata} (@command{gcc})
3856 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
3857 activated. Note that these pragmas can also be controlled using the
3858 configuration pragmas @code{Assertion_Policy} and @code{Debug_Policy}.
3859 It also activates pragmas @code{Check}, @code{Precondition}, and
3860 @code{Postcondition}. Note that these pragmas can also be controlled
3861 using the configuration pragma @code{Check_Policy}.
3862
3863 @item -gnatA
3864 @cindex @option{-gnatA} (@command{gcc})
3865 Avoid processing @file{gnat.adc}. If a @file{gnat.adc} file is present,
3866 it will be ignored.
3867
3868 @item -gnatb
3869 @cindex @option{-gnatb} (@command{gcc})
3870 Generate brief messages to @file{stderr} even if verbose mode set.
3871
3872 @item -gnatB
3873 @cindex @option{-gnatB} (@command{gcc})
3874 Assume no invalid (bad) values except for 'Valid attribute use.
3875
3876 @item -gnatc
3877 @cindex @option{-gnatc} (@command{gcc})
3878 Check syntax and semantics only (no code generation attempted).
3879
3880 @item -gnatd
3881 @cindex @option{-gnatd} (@command{gcc})
3882 Specify debug options for the compiler. The string of characters after
3883 the @option{-gnatd} specify the specific debug options. The possible
3884 characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
3885 compiler source file @file{debug.adb} for details of the implemented
3886 debug options. Certain debug options are relevant to applications
3887 programmers, and these are documented at appropriate points in this
3888 users guide.
3889
3890 @ifclear vms
3891 @item -gnatD
3892 @cindex @option{-gnatD[nn]} (@command{gcc})
3893 @end ifclear
3894 @ifset vms
3895 @item /XDEBUG /LXDEBUG=nnn
3896 @end ifset
3897 Create expanded source files for source level debugging. This switch
3898 also suppress generation of cross-reference information
3899 (see @option{-gnatx}).
3900
3901 @item -gnatec=@var{path}
3902 @cindex @option{-gnatec} (@command{gcc})
3903 Specify a configuration pragma file
3904 @ifclear vms
3905 (the equal sign is optional)
3906 @end ifclear
3907 (@pxref{The Configuration Pragmas Files}).
3908
3909 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=@var{value}@r{]}
3910 @cindex @option{-gnateD} (@command{gcc})
3911 Defines a symbol, associated with @var{value}, for preprocessing.
3912 (@pxref{Integrated Preprocessing}).
3913
3914 @item -gnatef
3915 @cindex @option{-gnatef} (@command{gcc})
3916 Display full source path name in brief error messages.
3917
3918 @item -gnateG
3919 @cindex @option{-gnateG} (@command{gcc})
3920 Save result of preprocessing in a text file.
3921
3922 @item -gnatem=@var{path}
3923 @cindex @option{-gnatem} (@command{gcc})
3924 Specify a mapping file
3925 @ifclear vms
3926 (the equal sign is optional)
3927 @end ifclear
3928 (@pxref{Units to Sources Mapping Files}).
3929
3930 @item -gnatep=@var{file}
3931 @cindex @option{-gnatep} (@command{gcc})
3932 Specify a preprocessing data file
3933 @ifclear vms
3934 (the equal sign is optional)
3935 @end ifclear
3936 (@pxref{Integrated Preprocessing}).
3937
3938 @item -gnatE
3939 @cindex @option{-gnatE} (@command{gcc})
3940 Full dynamic elaboration checks.
3941
3942 @item -gnatf
3943 @cindex @option{-gnatf} (@command{gcc})
3944 Full errors. Multiple errors per line, all undefined references, do not
3945 attempt to suppress cascaded errors.
3946
3947 @item -gnatF
3948 @cindex @option{-gnatF} (@command{gcc})
3949 Externals names are folded to all uppercase.
3950
3951 @item ^-gnatg^/GNAT_INTERNAL^
3952 @cindex @option{^-gnatg^/GNAT_INTERNAL^} (@command{gcc})
3953 Internal GNAT implementation mode. This should not be used for
3954 applications programs, it is intended only for use by the compiler
3955 and its run-time library. For documentation, see the GNAT sources.
3956 Note that @option{^-gnatg^/GNAT_INTERNAL^} implies
3957 @option{^-gnatwae^/WARNINGS=ALL,ERRORS^} and
3958 @option{^-gnatyg^/STYLE_CHECKS=GNAT^}
3959 so that all standard warnings and all standard style options are turned on.
3960 All warnings and style error messages are treated as errors.
3961
3962 @ifclear vms
3963 @item -gnatG=nn
3964 @cindex @option{-gnatG[nn]} (@command{gcc})
3965 @end ifclear
3966 @ifset vms
3967 @item /EXPAND_SOURCE, /LEXPAND_SOURCE=nnn
3968 @end ifset
3969 List generated expanded code in source form.
3970
3971 @item ^-gnath^/HELP^
3972 @cindex @option{^-gnath^/HELP^} (@command{gcc})
3973 Output usage information. The output is written to @file{stdout}.
3974
3975 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
3976 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
3977 Identifier character set
3978 @ifclear vms
3979 (@var{c}=1/2/3/4/8/9/p/f/n/w).
3980 @end ifclear
3981 For details of the possible selections for @var{c},
3982 see @ref{Character Set Control}.
3983
3984 @item ^-gnatI^/IGNORE_REP_CLAUSES^
3985 @cindex @option{^-gnatI^IGNORE_REP_CLAUSES^} (@command{gcc})
3986 Ignore representation clauses. When this switch is used, all
3987 representation clauses are treated as comments. This is useful
3988 when initially porting code where you want to ignore rep clause
3989 problems, and also for compiling foreign code (particularly
3990 for use with ASIS).
3991
3992 @item -gnatjnn
3993 @cindex @option{-gnatjnn} (@command{gcc})
3994 Reformat error messages to fit on nn character lines
3995
3996 @item -gnatk=@var{n}
3997 @cindex @option{-gnatk} (@command{gcc})
3998 Limit file names to @var{n} (1-999) characters ^(@code{k} = krunch)^^.
3999
4000 @item -gnatl
4001 @cindex @option{-gnatl} (@command{gcc})
4002 Output full source listing with embedded error messages.
4003
4004 @item -gnatL
4005 @cindex @option{-gnatL} (@command{gcc})
4006 Used in conjunction with -gnatG or -gnatD to intersperse original
4007 source lines (as comment lines with line numbers) in the expanded
4008 source output.
4009
4010 @item -gnatm=@var{n}
4011 @cindex @option{-gnatm} (@command{gcc})
4012 Limit number of detected error or warning messages to @var{n}
4013 where @var{n} is in the range 1..999999. The default setting if
4014 no switch is given is 9999. If the number of warnings reaches this
4015 limit, then a message is output and further warnings are suppressed,
4016 but the compilation is continued. If the number of error messages
4017 reaches this limit, then a message is output and the compilation
4018 is abandoned. The equal sign here is optional. A value of zero
4019 means that no limit applies.
4020
4021 @item -gnatn
4022 @cindex @option{-gnatn} (@command{gcc})
4023 Activate inlining for subprograms for which
4024 pragma @code{inline} is specified. This inlining is performed
4025 by the GCC back-end.
4026
4027 @item -gnatN
4028 @cindex @option{-gnatN} (@command{gcc})
4029 Activate front end inlining for subprograms for which
4030 pragma @code{Inline} is specified. This inlining is performed
4031 by the front end and will be visible in the
4032 @option{-gnatG} output.
4033
4034 When using a gcc-based back end (in practice this means using any version
4035 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
4036 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
4037 Historically front end inlining was more extensive than the gcc back end
4038 inlining, but that is no longer the case.
4039
4040 @item -gnato
4041 @cindex @option{-gnato} (@command{gcc})
4042 Enable numeric overflow checking (which is not normally enabled by
4043 default). Note that division by zero is a separate check that is not
4044 controlled by this switch (division by zero checking is on by default).
4045
4046 @item -gnatp
4047 @cindex @option{-gnatp} (@command{gcc})
4048 Suppress all checks. See @ref{Run-Time Checks} for details.
4049
4050 @item -gnatP
4051 @cindex @option{-gnatP} (@command{gcc})
4052 Enable polling. This is required on some systems (notably Windows NT) to
4053 obtain asynchronous abort and asynchronous transfer of control capability.
4054 @xref{Pragma Polling,,, gnat_rm, GNAT Reference Manual}, for full
4055 details.
4056
4057 @item -gnatq
4058 @cindex @option{-gnatq} (@command{gcc})
4059 Don't quit. Try semantics, even if parse errors.
4060
4061 @item -gnatQ
4062 @cindex @option{-gnatQ} (@command{gcc})
4063 Don't quit. Generate @file{ALI} and tree files even if illegalities.
4064
4065 @item -gnatr
4066 @cindex @option{-gnatr} (@command{gcc})
4067 Treat pragma Restrictions as Restriction_Warnings.
4068
4069 @item ^-gnatR@r{[}0@r{/}1@r{/}2@r{/}3@r{[}s@r{]]}^/REPRESENTATION_INFO^
4070 @cindex @option{-gnatR} (@command{gcc})
4071 Output representation information for declared types and objects.
4072
4073 @item -gnats
4074 @cindex @option{-gnats} (@command{gcc})
4075 Syntax check only.
4076
4077 @item -gnatS
4078 @cindex @option{-gnatS} (@command{gcc})
4079 Print package Standard.
4080
4081 @item -gnatt
4082 @cindex @option{-gnatt} (@command{gcc})
4083 Generate tree output file.
4084
4085 @item ^-gnatT^/TABLE_MULTIPLIER=^@var{nnn}
4086 @cindex @option{^-gnatT^/TABLE_MULTIPLIER^} (@command{gcc})
4087 All compiler tables start at @var{nnn} times usual starting size.
4088
4089 @item -gnatu
4090 @cindex @option{-gnatu} (@command{gcc})
4091 List units for this compilation.
4092
4093 @item -gnatU
4094 @cindex @option{-gnatU} (@command{gcc})
4095 Tag all error messages with the unique string ``error:''
4096
4097 @item -gnatv
4098 @cindex @option{-gnatv} (@command{gcc})
4099 Verbose mode. Full error output with source lines to @file{stdout}.
4100
4101 @item -gnatV
4102 @cindex @option{-gnatV} (@command{gcc})
4103 Control level of validity checking. See separate section describing
4104 this feature.
4105
4106 @item ^-gnatw@var{xxx}^/WARNINGS=(@var{option}@r{[},@dots{}@r{]})^
4107 @cindex @option{^-gnatw^/WARNINGS^} (@command{gcc})
4108 Warning mode where
4109 ^@var{xxx} is a string of option letters that^the list of options^ denotes
4110 the exact warnings that
4111 are enabled or disabled (@pxref{Warning Message Control}).
4112
4113 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
4114 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
4115 Wide character encoding method
4116 @ifclear vms
4117 (@var{e}=n/h/u/s/e/8).
4118 @end ifclear
4119 @ifset vms
4120 (@var{e}=@code{BRACKETS, NONE, HEX, UPPER, SHIFT_JIS, EUC, UTF8})
4121 @end ifset
4122
4123 @item -gnatx
4124 @cindex @option{-gnatx} (@command{gcc})
4125 Suppress generation of cross-reference information.
4126
4127 @item ^-gnaty^/STYLE_CHECKS=(option,option@dots{})^
4128 @cindex @option{^-gnaty^/STYLE_CHECKS^} (@command{gcc})
4129 Enable built-in style checks (@pxref{Style Checking}).
4130
4131 @item ^-gnatz^/DISTRIBUTION_STUBS=^@var{m}
4132 @cindex @option{^-gnatz^/DISTRIBUTION_STUBS^} (@command{gcc})
4133 Distribution stub generation and compilation
4134 @ifclear vms
4135 (@var{m}=r/c for receiver/caller stubs).
4136 @end ifclear
4137 @ifset vms
4138 (@var{m}=@code{RECEIVER} or @code{CALLER} to specify the type of stubs
4139 to be generated and compiled).
4140 @end ifset
4141
4142 @item ^-I^/SEARCH=^@var{dir}
4143 @cindex @option{^-I^/SEARCH^} (@command{gcc})
4144 @cindex RTL
4145 Direct GNAT to search the @var{dir} directory for source files needed by
4146 the current compilation
4147 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4148
4149 @item ^-I-^/NOCURRENT_DIRECTORY^
4150 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gcc})
4151 @cindex RTL
4152 Except for the source file named in the command line, do not look for source
4153 files in the directory containing the source file named in the command line
4154 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4155
4156 @ifclear vms
4157 @item -mbig-switch
4158 @cindex @option{-mbig-switch} (@command{gcc})
4159 @cindex @code{case} statement (effect of @option{-mbig-switch} option)
4160 This standard gcc switch causes the compiler to use larger offsets in its
4161 jump table representation for @code{case} statements.
4162 This may result in less efficient code, but is sometimes necessary
4163 (for example on HP-UX targets)
4164 @cindex HP-UX and @option{-mbig-switch} option
4165 in order to compile large and/or nested @code{case} statements.
4166
4167 @item -o @var{file}
4168 @cindex @option{-o} (@command{gcc})
4169 This switch is used in @command{gcc} to redirect the generated object file
4170 and its associated ALI file. Beware of this switch with GNAT, because it may
4171 cause the object file and ALI file to have different names which in turn
4172 may confuse the binder and the linker.
4173 @end ifclear
4174
4175 @item -nostdinc
4176 @cindex @option{-nostdinc} (@command{gcc})
4177 Inhibit the search of the default location for the GNAT Run Time
4178 Library (RTL) source files.
4179
4180 @item -nostdlib
4181 @cindex @option{-nostdlib} (@command{gcc})
4182 Inhibit the search of the default location for the GNAT Run Time
4183 Library (RTL) ALI files.
4184
4185 @ifclear vms
4186 @item -O@ovar{n}
4187 @cindex @option{-O} (@command{gcc})
4188 @var{n} controls the optimization level.
4189
4190 @table @asis
4191 @item n = 0
4192 No optimization, the default setting if no @option{-O} appears
4193
4194 @item n = 1
4195 Normal optimization, the default if you specify @option{-O} without
4196 an operand. A good compromise between code quality and compilation
4197 time.
4198
4199 @item n = 2
4200 Extensive optimization, may improve execution time, possibly at the cost of
4201 substantially increased compilation time.
4202
4203 @item n = 3
4204 Same as @option{-O2}, and also includes inline expansion for small subprograms
4205 in the same unit.
4206
4207 @item n = s
4208 Optimize space usage
4209 @end table
4210
4211 @noindent
4212 See also @ref{Optimization Levels}.
4213 @end ifclear
4214
4215 @ifset vms
4216 @item  /NOOPTIMIZE
4217 @cindex @option{/NOOPTIMIZE} (@code{GNAT COMPILE})
4218 Equivalent to @option{/OPTIMIZE=NONE}.
4219 This is the default behavior in the absence of an @option{/OPTIMIZE}
4220 qualifier.
4221
4222 @item /OPTIMIZE@r{[}=(keyword@r{[},@dots{}@r{]})@r{]}
4223 @cindex @option{/OPTIMIZE} (@code{GNAT COMPILE})
4224 Selects the level of optimization for your program. The supported
4225 keywords are as follows:
4226 @table @code
4227 @item   ALL
4228 Perform most optimizations, including those that
4229 are expensive.
4230 This is the default if the @option{/OPTIMIZE} qualifier is supplied
4231 without keyword options.
4232
4233 @item   NONE
4234 Do not do any optimizations. Same as @code{/NOOPTIMIZE}.
4235
4236 @item SOME
4237 Perform some optimizations, but omit ones that are costly.
4238
4239 @item   DEVELOPMENT
4240 Same as @code{SOME}.
4241
4242 @item INLINING
4243 Full optimization as in @option{/OPTIMIZE=ALL}, and also attempts
4244 automatic inlining of small subprograms within a unit
4245
4246 @item   UNROLL_LOOPS
4247 Try to unroll loops. This keyword may be specified together with
4248 any keyword above other than @code{NONE}. Loop unrolling
4249 usually, but not always, improves the performance of programs.
4250
4251 @item SPACE
4252 Optimize space usage
4253 @end table
4254
4255 @noindent
4256 See also @ref{Optimization Levels}.
4257 @end ifset
4258
4259 @ifclear vms
4260 @item -pass-exit-codes
4261 @cindex @option{-pass-exit-codes} (@command{gcc})
4262 Catch exit codes from the compiler and use the most meaningful as
4263 exit status.
4264 @end ifclear
4265
4266 @item --RTS=@var{rts-path}
4267 @cindex @option{--RTS} (@command{gcc})
4268 Specifies the default location of the runtime library. Same meaning as the
4269 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
4270
4271 @item ^-S^/ASM^
4272 @cindex @option{^-S^/ASM^} (@command{gcc})
4273 ^Used in place of @option{-c} to^Used to^
4274 cause the assembler source file to be
4275 generated, using @file{^.s^.S^} as the extension,
4276 instead of the object file.
4277 This may be useful if you need to examine the generated assembly code.
4278
4279 @item ^-fverbose-asm^/VERBOSE_ASM^
4280 @cindex @option{^-fverbose-asm^/VERBOSE_ASM^} (@command{gcc})
4281 ^Used in conjunction with @option{-S}^Used in place of @option{/ASM}^
4282 to cause the generated assembly code file to be annotated with variable
4283 names, making it significantly easier to follow.
4284
4285 @item ^-v^/VERBOSE^
4286 @cindex @option{^-v^/VERBOSE^} (@command{gcc})
4287 Show commands generated by the @command{gcc} driver. Normally used only for
4288 debugging purposes or if you need to be sure what version of the
4289 compiler you are executing.
4290
4291 @ifclear vms
4292 @item -V @var{ver}
4293 @cindex @option{-V} (@command{gcc})
4294 Execute @var{ver} version of the compiler. This is the @command{gcc}
4295 version, not the GNAT version.
4296 @end ifclear
4297
4298 @item ^-w^/NO_BACK_END_WARNINGS^
4299 @cindex @option{-w} (@command{gcc})
4300 Turn off warnings generated by the back end of the compiler. Use of
4301 this switch also causes the default for front end warnings to be set
4302 to suppress (as though @option{-gnatws} had appeared at the start of
4303 the options).
4304
4305 @end table
4306
4307 @ifclear vms
4308 @c Combining qualifiers does not work on VMS
4309 You may combine a sequence of GNAT switches into a single switch. For
4310 example, the combined switch
4311
4312 @cindex Combining GNAT switches
4313 @smallexample
4314 -gnatofi3
4315 @end smallexample
4316
4317 @noindent
4318 is equivalent to specifying the following sequence of switches:
4319
4320 @smallexample
4321 -gnato -gnatf -gnati3
4322 @end smallexample
4323 @end ifclear
4324
4325 @noindent
4326 The following restrictions apply to the combination of switches
4327 in this manner:
4328
4329 @itemize @bullet
4330 @item
4331 The switch @option{-gnatc} if combined with other switches must come
4332 first in the string.
4333
4334 @item
4335 The switch @option{-gnats} if combined with other switches must come
4336 first in the string.
4337
4338 @item
4339 The switches
4340 @option{^-gnatz^/DISTRIBUTION_STUBS^}, @option{-gnatzc}, and @option{-gnatzr}
4341 may not be combined with any other switches.
4342
4343 @ifclear vms
4344 @item
4345 Once a ``y'' appears in the string (that is a use of the @option{-gnaty}
4346 switch), then all further characters in the switch are interpreted
4347 as style modifiers (see description of @option{-gnaty}).
4348
4349 @item
4350 Once a ``d'' appears in the string (that is a use of the @option{-gnatd}
4351 switch), then all further characters in the switch are interpreted
4352 as debug flags (see description of @option{-gnatd}).
4353
4354 @item
4355 Once a ``w'' appears in the string (that is a use of the @option{-gnatw}
4356 switch), then all further characters in the switch are interpreted
4357 as warning mode modifiers (see description of @option{-gnatw}).
4358
4359 @item
4360 Once a ``V'' appears in the string (that is a use of the @option{-gnatV}
4361 switch), then all further characters in the switch are interpreted
4362 as validity checking options (see description of @option{-gnatV}).
4363 @end ifclear
4364 @end itemize
4365
4366 @node Output and Error Message Control
4367 @subsection Output and Error Message Control
4368 @findex stderr
4369
4370 @noindent
4371 The standard default format for error messages is called ``brief format''.
4372 Brief format messages are written to @file{stderr} (the standard error
4373 file) and have the following form:
4374
4375 @smallexample
4376 e.adb:3:04: Incorrect spelling of keyword "function"
4377 e.adb:4:20: ";" should be "is"
4378 @end smallexample
4379
4380 @noindent
4381 The first integer after the file name is the line number in the file,
4382 and the second integer is the column number within the line.
4383 @ifclear vms
4384 @code{GPS} can parse the error messages
4385 and point to the referenced character.
4386 @end ifclear
4387 The following switches provide control over the error message
4388 format:
4389
4390 @table @option
4391 @c !sort!
4392 @item -gnatv
4393 @cindex @option{-gnatv} (@command{gcc})
4394 @findex stdout
4395 @ifclear vms
4396 The v stands for verbose.
4397 @end ifclear
4398 The effect of this setting is to write long-format error
4399 messages to @file{stdout} (the standard output file.
4400 The same program compiled with the
4401 @option{-gnatv} switch would generate:
4402
4403 @smallexample
4404 @cartouche
4405 3. funcion X (Q : Integer)
4406    |
4407 >>> Incorrect spelling of keyword "function"
4408 4. return Integer;
4409                  |
4410 >>> ";" should be "is"
4411 @end cartouche
4412 @end smallexample
4413
4414 @noindent
4415 The vertical bar indicates the location of the error, and the @samp{>>>}
4416 prefix can be used to search for error messages. When this switch is
4417 used the only source lines output are those with errors.
4418
4419 @item -gnatl
4420 @cindex @option{-gnatl} (@command{gcc})
4421 @ifclear vms
4422 The @code{l} stands for list.
4423 @end ifclear
4424 This switch causes a full listing of
4425 the file to be generated. In the case where a body is
4426 compiled, the corresponding spec is also listed, along
4427 with any subunits. Typical output from compiling a package
4428 body @file{p.adb} might look like:
4429
4430 @smallexample @c ada
4431 @cartouche
4432  Compiling: p.adb
4433
4434      1. package body p is
4435      2.    procedure a;
4436      3.    procedure a is separate;
4437      4. begin
4438      5.    null
4439                |
4440         >>> missing ";"
4441
4442      6. end;
4443
4444 Compiling: p.ads
4445
4446      1. package p is
4447      2.    pragma Elaborate_Body
4448                                 |
4449         >>> missing ";"
4450
4451      3. end p;
4452
4453 Compiling: p-a.adb
4454
4455      1. separate p
4456                 |
4457         >>> missing "("
4458
4459      2. procedure a is
4460      3. begin
4461      4.    null
4462                |
4463         >>> missing ";"
4464
4465      5. end;
4466 @end cartouche
4467 @end smallexample
4468
4469 @noindent
4470 @findex stderr
4471 When you specify the @option{-gnatv} or @option{-gnatl} switches and
4472 standard output is redirected, a brief summary is written to
4473 @file{stderr} (standard error) giving the number of error messages and
4474 warning messages generated.
4475
4476 @item -^gnatl^OUTPUT_FILE^=file
4477 @cindex @option{^-gnatl^OUTPUT_FILE^=fname} (@command{gcc})
4478 This has the same effect as @option{-gnatl} except that the output is
4479 written to a file instead of to standard output. If the given name
4480 @file{fname} does not start with a period, then it is the full name
4481 of the file to be written. If @file{fname} is an extension, it is
4482 appended to the name of the file being compiled. For example, if
4483 file @file{xyz.adb} is compiled with @option{^-gnatl^OUTPUT_FILE^=.lst},
4484 then the output is written to file ^xyz.adb.lst^xyz.adb_lst^.
4485
4486 @item -gnatU
4487 @cindex @option{-gnatU} (@command{gcc})
4488 This switch forces all error messages to be preceded by the unique
4489 string ``error:''. This means that error messages take a few more
4490 characters in space, but allows easy searching for and identification
4491 of error messages.
4492
4493 @item -gnatb
4494 @cindex @option{-gnatb} (@command{gcc})
4495 @ifclear vms
4496 The @code{b} stands for brief.
4497 @end ifclear
4498 This switch causes GNAT to generate the
4499 brief format error messages to @file{stderr} (the standard error
4500 file) as well as the verbose
4501 format message or full listing (which as usual is written to
4502 @file{stdout} (the standard output file).
4503
4504 @item -gnatm=@var{n}
4505 @cindex @option{-gnatm} (@command{gcc})
4506 @ifclear vms
4507 The @code{m} stands for maximum.
4508 @end ifclear
4509 @var{n} is a decimal integer in the
4510 range of 1 to 999999 and limits the number of error or warning
4511 messages to be generated. For example, using
4512 @option{-gnatm2} might yield
4513
4514 @smallexample
4515 e.adb:3:04: Incorrect spelling of keyword "function"
4516 e.adb:5:35: missing ".."
4517 fatal error: maximum number of errors detected
4518 compilation abandoned
4519 @end smallexample
4520
4521 @noindent
4522 The default setting if
4523 no switch is given is 9999. If the number of warnings reaches this
4524 limit, then a message is output and further warnings are suppressed,
4525 but the compilation is continued. If the number of error messages
4526 reaches this limit, then a message is output and the compilation
4527 is abandoned. A value of zero means that no limit applies.
4528
4529 @noindent
4530 Note that the equal sign is optional, so the switches
4531 @option{-gnatm2} and @option{-gnatm=2} are equivalent.
4532
4533 @item -gnatf
4534 @cindex @option{-gnatf} (@command{gcc})
4535 @cindex Error messages, suppressing
4536 @ifclear vms
4537 The @code{f} stands for full.
4538 @end ifclear
4539 Normally, the compiler suppresses error messages that are likely to be
4540 redundant. This switch causes all error
4541 messages to be generated. In particular, in the case of
4542 references to undefined variables. If a given variable is referenced
4543 several times, the normal format of messages is
4544 @smallexample
4545 e.adb:7:07: "V" is undefined (more references follow)
4546 @end smallexample
4547
4548 @noindent
4549 where the parenthetical comment warns that there are additional
4550 references to the variable @code{V}. Compiling the same program with the
4551 @option{-gnatf} switch yields
4552
4553 @smallexample
4554 e.adb:7:07: "V" is undefined
4555 e.adb:8:07: "V" is undefined
4556 e.adb:8:12: "V" is undefined
4557 e.adb:8:16: "V" is undefined
4558 e.adb:9:07: "V" is undefined
4559 e.adb:9:12: "V" is undefined
4560 @end smallexample
4561
4562 @noindent
4563 The @option{-gnatf} switch also generates additional information for
4564 some error messages.  Some examples are:
4565
4566 @itemize @bullet
4567 @item
4568 Full details on entities not available in high integrity mode
4569 @item
4570 Details on possibly non-portable unchecked conversion
4571 @item
4572 List possible interpretations for ambiguous calls
4573 @item
4574 Additional details on incorrect parameters
4575 @end itemize
4576
4577 @item -gnatjnn
4578 @cindex @option{-gnatjnn} (@command{gcc})
4579 In normal operation mode (or if @option{-gnatj0} is used, then error messages
4580 with continuation lines are treated as though the continuation lines were
4581 separate messages (and so a warning with two continuation lines counts as
4582 three warnings, and is listed as three separate messages).
4583
4584 If the @option{-gnatjnn} switch is used with a positive value for nn, then
4585 messages are output in a different manner. A message and all its continuation
4586 lines are treated as a unit, and count as only one warning or message in the
4587 statistics totals. Furthermore, the message is reformatted so that no line
4588 is longer than nn characters.
4589
4590 @item -gnatq
4591 @cindex @option{-gnatq} (@command{gcc})
4592 @ifclear vms
4593 The @code{q} stands for quit (really ``don't quit'').
4594 @end ifclear
4595 In normal operation mode, the compiler first parses the program and
4596 determines if there are any syntax errors. If there are, appropriate
4597 error messages are generated and compilation is immediately terminated.
4598 This switch tells
4599 GNAT to continue with semantic analysis even if syntax errors have been
4600 found. This may enable the detection of more errors in a single run. On
4601 the other hand, the semantic analyzer is more likely to encounter some
4602 internal fatal error when given a syntactically invalid tree.
4603
4604 @item -gnatQ
4605 @cindex @option{-gnatQ} (@command{gcc})
4606 In normal operation mode, the @file{ALI} file is not generated if any
4607 illegalities are detected in the program. The use of @option{-gnatQ} forces
4608 generation of the @file{ALI} file. This file is marked as being in
4609 error, so it cannot be used for binding purposes, but it does contain
4610 reasonably complete cross-reference information, and thus may be useful
4611 for use by tools (e.g., semantic browsing tools or integrated development
4612 environments) that are driven from the @file{ALI} file. This switch
4613 implies @option{-gnatq}, since the semantic phase must be run to get a
4614 meaningful ALI file.
4615
4616 In addition, if @option{-gnatt} is also specified, then the tree file is
4617 generated even if there are illegalities. It may be useful in this case
4618 to also specify @option{-gnatq} to ensure that full semantic processing
4619 occurs. The resulting tree file can be processed by ASIS, for the purpose
4620 of providing partial information about illegal units, but if the error
4621 causes the tree to be badly malformed, then ASIS may crash during the
4622 analysis.
4623
4624 When @option{-gnatQ} is used and the generated @file{ALI} file is marked as
4625 being in error, @command{gnatmake} will attempt to recompile the source when it
4626 finds such an @file{ALI} file, including with switch @option{-gnatc}.
4627
4628 Note that @option{-gnatQ} has no effect if @option{-gnats} is specified,
4629 since ALI files are never generated if @option{-gnats} is set.
4630
4631 @end table
4632
4633 @node Warning Message Control
4634 @subsection Warning Message Control
4635 @cindex Warning messages
4636 @noindent
4637 In addition to error messages, which correspond to illegalities as defined
4638 in the Ada Reference Manual, the compiler detects two kinds of warning
4639 situations.
4640
4641 First, the compiler considers some constructs suspicious and generates a
4642 warning message to alert you to a possible error. Second, if the
4643 compiler detects a situation that is sure to raise an exception at
4644 run time, it generates a warning message. The following shows an example
4645 of warning messages:
4646 @smallexample
4647 e.adb:4:24: warning: creation of object may raise Storage_Error
4648 e.adb:10:17: warning: static value out of range
4649 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
4650 @end smallexample
4651
4652 @noindent
4653 GNAT considers a large number of situations as appropriate
4654 for the generation of warning messages. As always, warnings are not
4655 definite indications of errors. For example, if you do an out-of-range
4656 assignment with the deliberate intention of raising a
4657 @code{Constraint_Error} exception, then the warning that may be
4658 issued does not indicate an error. Some of the situations for which GNAT
4659 issues warnings (at least some of the time) are given in the following
4660 list. This list is not complete, and new warnings are often added to
4661 subsequent versions of GNAT. The list is intended to give a general idea
4662 of the kinds of warnings that are generated.
4663
4664 @itemize @bullet
4665 @item
4666 Possible infinitely recursive calls
4667
4668 @item
4669 Out-of-range values being assigned
4670
4671 @item
4672 Possible order of elaboration problems
4673
4674 @item
4675 Assertions (pragma Assert) that are sure to fail
4676
4677 @item
4678 Unreachable code
4679
4680 @item
4681 Address clauses with possibly unaligned values, or where an attempt is
4682 made to overlay a smaller variable with a larger one.
4683
4684 @item
4685 Fixed-point type declarations with a null range
4686
4687 @item
4688 Direct_IO or Sequential_IO instantiated with a type that has access values
4689
4690 @item
4691 Variables that are never assigned a value
4692
4693 @item
4694 Variables that are referenced before being initialized
4695
4696 @item
4697 Task entries with no corresponding @code{accept} statement
4698
4699 @item
4700 Duplicate accepts for the same task entry in a @code{select}
4701
4702 @item
4703 Objects that take too much storage
4704
4705 @item
4706 Unchecked conversion between types of differing sizes
4707
4708 @item
4709 Missing @code{return} statement along some execution path in a function
4710
4711 @item
4712 Incorrect (unrecognized) pragmas
4713
4714 @item
4715 Incorrect external names
4716
4717 @item
4718 Allocation from empty storage pool
4719
4720 @item
4721 Potentially blocking operation in protected type
4722
4723 @item
4724 Suspicious parenthesization of expressions
4725
4726 @item
4727 Mismatching bounds in an aggregate
4728
4729 @item
4730 Attempt to return local value by reference
4731
4732 @item
4733 Premature instantiation of a generic body
4734
4735 @item
4736 Attempt to pack aliased components
4737
4738 @item
4739 Out of bounds array subscripts
4740
4741 @item
4742 Wrong length on string assignment
4743
4744 @item
4745 Violations of style rules if style checking is enabled
4746
4747 @item
4748 Unused @code{with} clauses
4749
4750 @item
4751 @code{Bit_Order} usage that does not have any effect
4752
4753 @item
4754 @code{Standard.Duration} used to resolve universal fixed expression
4755
4756 @item
4757 Dereference of possibly null value
4758
4759 @item
4760 Declaration that is likely to cause storage error
4761
4762 @item
4763 Internal GNAT unit @code{with}'ed by application unit
4764
4765 @item
4766 Values known to be out of range at compile time
4767
4768 @item
4769 Unreferenced labels and variables
4770
4771 @item
4772 Address overlays that could clobber memory
4773
4774 @item
4775 Unexpected initialization when address clause present
4776
4777 @item
4778 Bad alignment for address clause
4779
4780 @item
4781 Useless type conversions
4782
4783 @item
4784 Redundant assignment statements and other redundant constructs
4785
4786 @item
4787 Useless exception handlers
4788
4789 @item
4790 Accidental hiding of name by child unit
4791
4792 @item
4793 Access before elaboration detected at compile time
4794
4795 @item
4796 A range in a @code{for} loop that is known to be null or might be null
4797
4798 @end itemize
4799
4800 @noindent
4801 The following section lists compiler switches that are available
4802 to control the handling of warning messages. It is also possible
4803 to exercise much finer control over what warnings are issued and
4804 suppressed using the GNAT pragma Warnings, @xref{Pragma Warnings,,,
4805 gnat_rm, GNAT Reference manual}.
4806
4807 @table @option
4808 @c !sort!
4809 @item -gnatwa
4810 @emph{Activate all optional errors.}
4811 @cindex @option{-gnatwa} (@command{gcc})
4812 This switch activates most optional warning messages, see remaining list
4813 in this section for details on optional warning messages that can be
4814 individually controlled.  The warnings that are not turned on by this
4815 switch are
4816 @option{-gnatwd} (implicit dereferencing),
4817 @option{-gnatwh} (hiding),
4818 @option{-gnatwl} (elaboration warnings),
4819 @option{-gnatw.o} (warn on values set by out parameters ignored)
4820 and @option{-gnatwt} (tracking of deleted conditional code).
4821 All other optional warnings are turned on.
4822
4823 @item -gnatwA
4824 @emph{Suppress all optional errors.}
4825 @cindex @option{-gnatwA} (@command{gcc})
4826 This switch suppresses all optional warning messages, see remaining list
4827 in this section for details on optional warning messages that can be
4828 individually controlled.
4829
4830 @item -gnatw.a
4831 @emph{Activate warnings on failing assertions.}
4832 @cindex @option{-gnatw.a} (@command{gcc})
4833 @cindex Assert failures
4834 This switch activates warnings for assertions where the compiler can tell at
4835 compile time that the assertion will fail. Note that this warning is given
4836 even if assertions are disabled. The default is that such warnings are
4837 generated.
4838
4839 @item -gnatw.A
4840 @emph{Suppress warnings on failing assertions.}
4841 @cindex @option{-gnatw.A} (@command{gcc})
4842 @cindex Assert failures
4843 This switch suppresses warnings for assertions where the compiler can tell at
4844 compile time that the assertion will fail.
4845
4846 @item -gnatwb
4847 @emph{Activate warnings on bad fixed values.}
4848 @cindex @option{-gnatwb} (@command{gcc})
4849 @cindex Bad fixed values
4850 @cindex Fixed-point Small value
4851 @cindex Small value
4852 This switch activates warnings for static fixed-point expressions whose
4853 value is not an exact multiple of Small. Such values are implementation
4854 dependent, since an implementation is free to choose either of the multiples
4855 that surround the value. GNAT always chooses the closer one, but this is not
4856 required behavior, and it is better to specify a value that is an exact
4857 multiple, ensuring predictable execution. The default is that such warnings
4858 are not generated.
4859
4860 @item -gnatwB
4861 @emph{Suppress warnings on bad fixed values.}
4862 @cindex @option{-gnatwB} (@command{gcc})
4863 This switch suppresses warnings for static fixed-point expressions whose
4864 value is not an exact multiple of Small.
4865
4866 @item -gnatw.b
4867 @emph{Activate warnings on biased representation.}
4868 @cindex @option{-gnatw.b} (@command{gcc})
4869 @cindex Biased representation
4870 This switch activates warnings when a size clause, value size clause, component
4871 clause, or component size clause forces the use of biased representation for an
4872 integer type (e.g. representing a range of 10..11 in a single bit by using 0/1
4873 to represent 10/11). The default is that such warnings are generated.
4874
4875 @item -gnatw.B
4876 @emph{Suppress warnings on biased representation.}
4877 @cindex @option{-gnatwB} (@command{gcc})
4878 This switch suppresses warnings for representation clauses that force the use
4879 of biased representation.
4880
4881 @item -gnatwc
4882 @emph{Activate warnings on conditionals.}
4883 @cindex @option{-gnatwc} (@command{gcc})
4884 @cindex Conditionals, constant
4885 This switch activates warnings for conditional expressions used in
4886 tests that are known to be True or False at compile time. The default
4887 is that such warnings are not generated.
4888 Note that this warning does
4889 not get issued for the use of boolean variables or constants whose
4890 values are known at compile time, since this is a standard technique
4891 for conditional compilation in Ada, and this would generate too many
4892 false positive warnings.
4893
4894 This warning option also activates a special test for comparisons using
4895 the operators ``>='' and`` <=''.
4896 If the compiler can tell that only the equality condition is possible,
4897 then it will warn that the ``>'' or ``<'' part of the test
4898 is useless and that the operator could be replaced by ``=''.
4899 An example would be comparing a @code{Natural} variable <= 0.
4900
4901 This warning option also generates warnings if
4902 one or both tests is optimized away in a membership test for integer
4903 values if the result can be determined at compile time. Range tests on
4904 enumeration types are not included, since it is common for such tests
4905 to include an end point.
4906
4907 This warning can also be turned on using @option{-gnatwa}.
4908
4909 @item -gnatwC
4910 @emph{Suppress warnings on conditionals.}
4911 @cindex @option{-gnatwC} (@command{gcc})
4912 This switch suppresses warnings for conditional expressions used in
4913 tests that are known to be True or False at compile time.
4914
4915 @item -gnatw.c
4916 @emph{Activate warnings on missing component clauses.}
4917 @cindex @option{-gnatw.c} (@command{gcc})
4918 @cindex Component clause, missing
4919 This switch activates warnings for record components where a record
4920 representation clause is present and has component clauses for the
4921 majority, but not all, of the components. A warning is given for each
4922 component for which no component clause is present.
4923
4924 This warning can also be turned on using @option{-gnatwa}.
4925
4926 @item -gnatw.C
4927 @emph{Suppress warnings on missing component clauses.}
4928 @cindex @option{-gnatwC} (@command{gcc})
4929 This switch suppresses warnings for record components that are
4930 missing a component clause in the situation described above.
4931
4932 @item -gnatwd
4933 @emph{Activate warnings on implicit dereferencing.}
4934 @cindex @option{-gnatwd} (@command{gcc})
4935 If this switch is set, then the use of a prefix of an access type
4936 in an indexed component, slice, or selected component without an
4937 explicit @code{.all} will generate a warning. With this warning
4938 enabled, access checks occur only at points where an explicit
4939 @code{.all} appears in the source code (assuming no warnings are
4940 generated as a result of this switch). The default is that such
4941 warnings are not generated.
4942 Note that @option{-gnatwa} does not affect the setting of
4943 this warning option.
4944
4945 @item -gnatwD
4946 @emph{Suppress warnings on implicit dereferencing.}
4947 @cindex @option{-gnatwD} (@command{gcc})
4948 @cindex Implicit dereferencing
4949 @cindex Dereferencing, implicit
4950 This switch suppresses warnings for implicit dereferences in
4951 indexed components, slices, and selected components.
4952
4953 @item -gnatwe
4954 @emph{Treat warnings as errors.}
4955 @cindex @option{-gnatwe} (@command{gcc})
4956 @cindex Warnings, treat as error
4957 This switch causes warning messages to be treated as errors.
4958 The warning string still appears, but the warning messages are counted
4959 as errors, and prevent the generation of an object file.
4960
4961 @item -gnatw.e
4962 @emph{Activate every optional warning}
4963 @cindex @option{-gnatw.e} (@command{gcc})
4964 @cindex Warnings, activate every optional warning
4965 This switch activates all optional warnings, including those which
4966 are not activated by @code{-gnatwa}.
4967
4968 @item -gnatwf
4969 @emph{Activate warnings on unreferenced formals.}
4970 @cindex @option{-gnatwf} (@command{gcc})
4971 @cindex Formals, unreferenced
4972 This switch causes a warning to be generated if a formal parameter
4973 is not referenced in the body of the subprogram. This warning can
4974 also be turned on using @option{-gnatwa} or @option{-gnatwu}. The
4975 default is that these warnings are not generated.
4976
4977 @item -gnatwF
4978 @emph{Suppress warnings on unreferenced formals.}
4979 @cindex @option{-gnatwF} (@command{gcc})
4980 This switch suppresses warnings for unreferenced formal
4981 parameters. Note that the
4982 combination @option{-gnatwu} followed by @option{-gnatwF} has the
4983 effect of warning on unreferenced entities other than subprogram
4984 formals.
4985
4986 @item -gnatwg
4987 @emph{Activate warnings on unrecognized pragmas.}
4988 @cindex @option{-gnatwg} (@command{gcc})
4989 @cindex Pragmas, unrecognized
4990 This switch causes a warning to be generated if an unrecognized
4991 pragma is encountered. Apart from issuing this warning, the
4992 pragma is ignored and has no effect. This warning can
4993 also be turned on using @option{-gnatwa}. The default
4994 is that such warnings are issued (satisfying the Ada Reference
4995 Manual requirement that such warnings appear).
4996
4997 @item -gnatwG
4998 @emph{Suppress warnings on unrecognized pragmas.}
4999 @cindex @option{-gnatwG} (@command{gcc})
5000 This switch suppresses warnings for unrecognized pragmas.
5001
5002 @item -gnatwh
5003 @emph{Activate warnings on hiding.}
5004 @cindex @option{-gnatwh} (@command{gcc})
5005 @cindex Hiding of Declarations
5006 This switch activates warnings on hiding declarations.
5007 A declaration is considered hiding
5008 if it is for a non-overloadable entity, and it declares an entity with the
5009 same name as some other entity that is directly or use-visible. The default
5010 is that such warnings are not generated.
5011 Note that @option{-gnatwa} does not affect the setting of this warning option.
5012
5013 @item -gnatwH
5014 @emph{Suppress warnings on hiding.}
5015 @cindex @option{-gnatwH} (@command{gcc})
5016 This switch suppresses warnings on hiding declarations.
5017
5018 @item -gnatwi
5019 @emph{Activate warnings on implementation units.}
5020 @cindex @option{-gnatwi} (@command{gcc})
5021 This switch activates warnings for a @code{with} of an internal GNAT
5022 implementation unit, defined as any unit from the @code{Ada},
5023 @code{Interfaces}, @code{GNAT},
5024 ^^@code{DEC},^ or @code{System}
5025 hierarchies that is not
5026 documented in either the Ada Reference Manual or the GNAT
5027 Programmer's Reference Manual. Such units are intended only
5028 for internal implementation purposes and should not be @code{with}'ed
5029 by user programs. The default is that such warnings are generated
5030 This warning can also be turned on using @option{-gnatwa}.
5031
5032 @item -gnatwI
5033 @emph{Disable warnings on implementation units.}
5034 @cindex @option{-gnatwI} (@command{gcc})
5035 This switch disables warnings for a @code{with} of an internal GNAT
5036 implementation unit.
5037
5038 @item -gnatwj
5039 @emph{Activate warnings on obsolescent features (Annex J).}
5040 @cindex @option{-gnatwj} (@command{gcc})
5041 @cindex Features, obsolescent
5042 @cindex Obsolescent features
5043 If this warning option is activated, then warnings are generated for
5044 calls to subprograms marked with @code{pragma Obsolescent} and
5045 for use of features in Annex J of the Ada Reference Manual. In the
5046 case of Annex J, not all features are flagged. In particular use
5047 of the renamed packages (like @code{Text_IO}) and use of package
5048 @code{ASCII} are not flagged, since these are very common and
5049 would generate many annoying positive warnings. The default is that
5050 such warnings are not generated. This warning is also turned on by
5051 the use of @option{-gnatwa}.
5052
5053 In addition to the above cases, warnings are also generated for
5054 GNAT features that have been provided in past versions but which
5055 have been superseded (typically by features in the new Ada standard).
5056 For example, @code{pragma Ravenscar} will be flagged since its
5057 function is replaced by @code{pragma Profile(Ravenscar)}.
5058
5059 Note that this warning option functions differently from the
5060 restriction @code{No_Obsolescent_Features} in two respects.
5061 First, the restriction applies only to annex J features.
5062 Second, the restriction does flag uses of package @code{ASCII}.
5063
5064 @item -gnatwJ
5065 @emph{Suppress warnings on obsolescent features (Annex J).}
5066 @cindex @option{-gnatwJ} (@command{gcc})
5067 This switch disables warnings on use of obsolescent features.
5068
5069 @item -gnatwk
5070 @emph{Activate warnings on variables that could be constants.}
5071 @cindex @option{-gnatwk} (@command{gcc})
5072 This switch activates warnings for variables that are initialized but
5073 never modified, and then could be declared constants. The default is that
5074 such warnings are not given.
5075 This warning can also be turned on using @option{-gnatwa}.
5076
5077 @item -gnatwK
5078 @emph{Suppress warnings on variables that could be constants.}
5079 @cindex @option{-gnatwK} (@command{gcc})
5080 This switch disables warnings on variables that could be declared constants.
5081
5082 @item -gnatwl
5083 @emph{Activate warnings for elaboration pragmas.}
5084 @cindex @option{-gnatwl} (@command{gcc})
5085 @cindex Elaboration, warnings
5086 This switch activates warnings on missing
5087 @code{Elaborate_All} and @code{Elaborate} pragmas.
5088 See the section in this guide on elaboration checking for details on
5089 when such pragmas should be used. In dynamic elaboration mode, this switch
5090 generations warnings about the need to add elaboration pragmas. Note however,
5091 that if you blindly follow these warnings, and add @code{Elaborate_All}
5092 warnings wherever they are recommended, you basically end up with the
5093 equivalent of the static elaboration model, which may not be what you want for
5094 legacy code for which the static model does not work.
5095
5096 For the static model, the messages generated are labeled "info:" (for
5097 information messages). They are not warnings to add elaboration pragmas,
5098 merely informational messages showing what implicit elaboration pragmas
5099 have been added, for use in analyzing elaboration circularity problems.
5100
5101 Warnings are also generated if you
5102 are using the static mode of elaboration, and a @code{pragma Elaborate}
5103 is encountered. The default is that such warnings
5104 are not generated.
5105 This warning is not automatically turned on by the use of @option{-gnatwa}.
5106
5107 @item -gnatwL
5108 @emph{Suppress warnings for elaboration pragmas.}
5109 @cindex @option{-gnatwL} (@command{gcc})
5110 This switch suppresses warnings on missing Elaborate and Elaborate_All pragmas.
5111 See the section in this guide on elaboration checking for details on
5112 when such pragmas should be used.
5113
5114 @item -gnatwm
5115 @emph{Activate warnings on modified but unreferenced variables.}
5116 @cindex @option{-gnatwm} (@command{gcc})
5117 This switch activates warnings for variables that are assigned (using
5118 an initialization value or with one or more assignment statements) but
5119 whose value is never read. The warning is suppressed for volatile
5120 variables and also for variables that are renamings of other variables
5121 or for which an address clause is given.
5122 This warning can also be turned on using @option{-gnatwa}.
5123 The default is that these warnings are not given.
5124
5125 @item -gnatwM
5126 @emph{Disable warnings on modified but unreferenced variables.}
5127 @cindex @option{-gnatwM} (@command{gcc})
5128 This switch disables warnings for variables that are assigned or
5129 initialized, but never read.
5130
5131 @item -gnatwn
5132 @emph{Set normal warnings mode.}
5133 @cindex @option{-gnatwn} (@command{gcc})
5134 This switch sets normal warning mode, in which enabled warnings are
5135 issued and treated as warnings rather than errors. This is the default
5136 mode. the switch @option{-gnatwn} can be used to cancel the effect of
5137 an explicit @option{-gnatws} or
5138 @option{-gnatwe}. It also cancels the effect of the
5139 implicit @option{-gnatwe} that is activated by the
5140 use of @option{-gnatg}.
5141
5142 @item -gnatwo
5143 @emph{Activate warnings on address clause overlays.}
5144 @cindex @option{-gnatwo} (@command{gcc})
5145 @cindex Address Clauses, warnings
5146 This switch activates warnings for possibly unintended initialization
5147 effects of defining address clauses that cause one variable to overlap
5148 another. The default is that such warnings are generated.
5149 This warning can also be turned on using @option{-gnatwa}.
5150
5151 @item -gnatwO
5152 @emph{Suppress warnings on address clause overlays.}
5153 @cindex @option{-gnatwO} (@command{gcc})
5154 This switch suppresses warnings on possibly unintended initialization
5155 effects of defining address clauses that cause one variable to overlap
5156 another.
5157
5158 @item -gnatw.o
5159 @emph{Activate warnings on modified but unreferenced out parameters.}
5160 @cindex @option{-gnatw.o} (@command{gcc})
5161 This switch activates warnings for variables that are modified by using
5162 them as actuals for a call to a procedure with an out mode formal, where
5163 the resulting assigned value is never read. It is applicable in the case
5164 where there is more than one out mode formal. If there is only one out
5165 mode formal, the warning is issued by default (controlled by -gnatwu).
5166 The warning is suppressed for volatile
5167 variables and also for variables that are renamings of other variables
5168 or for which an address clause is given.
5169 The default is that these warnings are not given. Note that this warning
5170 is not included in -gnatwa, it must be activated explicitly.
5171
5172 @item -gnatw.O
5173 @emph{Disable warnings on modified but unreferenced out parameters.}
5174 @cindex @option{-gnatw.O} (@command{gcc})
5175 This switch suppresses warnings for variables that are modified by using
5176 them as actuals for a call to a procedure with an out mode formal, where
5177 the resulting assigned value is never read.
5178
5179 @item -gnatwp
5180 @emph{Activate warnings on ineffective pragma Inlines.}
5181 @cindex @option{-gnatwp} (@command{gcc})
5182 @cindex Inlining, warnings
5183 This switch activates warnings for failure of front end inlining
5184 (activated by @option{-gnatN}) to inline a particular call. There are
5185 many reasons for not being able to inline a call, including most
5186 commonly that the call is too complex to inline. The default is
5187 that such warnings are not given.
5188 This warning can also be turned on using @option{-gnatwa}.
5189 Warnings on ineffective inlining by the gcc back-end can be activated
5190 separately, using the gcc switch -Winline.
5191
5192 @item -gnatwP
5193 @emph{Suppress warnings on ineffective pragma Inlines.}
5194 @cindex @option{-gnatwP} (@command{gcc})
5195 This switch suppresses warnings on ineffective pragma Inlines. If the
5196 inlining mechanism cannot inline a call, it will simply ignore the
5197 request silently.
5198
5199 @item -gnatw.p
5200 @emph{Activate warnings on parameter ordering.}
5201 @cindex @option{-gnatw.p} (@command{gcc})
5202 @cindex Parameter order, warnings
5203 This switch activates warnings for cases of suspicious parameter
5204 ordering when the list of arguments are all simple identifiers that
5205 match the names of the formals, but are in a different order. The
5206 warning is suppressed if any use of named parameter notation is used,
5207 so this is the appropriate way to suppress a false positive (and
5208 serves to emphasize that the "misordering" is deliberate). The
5209 default is
5210 that such warnings are not given.
5211 This warning can also be turned on using @option{-gnatwa}.
5212
5213 @item -gnatw.P
5214 @emph{Suppress warnings on parameter ordering.}
5215 @cindex @option{-gnatw.P} (@command{gcc})
5216 This switch suppresses warnings on cases of suspicious parameter
5217 ordering.
5218
5219 @item -gnatwq
5220 @emph{Activate warnings on questionable missing parentheses.}
5221 @cindex @option{-gnatwq} (@command{gcc})
5222 @cindex Parentheses, warnings
5223 This switch activates warnings for cases where parentheses are not used and
5224 the result is potential ambiguity from a readers point of view. For example
5225 (not a > b) when a and b are modular means ((not a) > b) and very likely the
5226 programmer intended (not (a > b)). Similarly (-x mod 5) means (-(x mod 5)) and
5227 quite likely ((-x) mod 5) was intended. In such situations it seems best to
5228 follow the rule of always parenthesizing to make the association clear, and
5229 this warning switch warns if such parentheses are not present. The default
5230 is that these warnings are given.
5231 This warning can also be turned on using @option{-gnatwa}.
5232
5233 @item -gnatwQ
5234 @emph{Suppress warnings on questionable missing parentheses.}
5235 @cindex @option{-gnatwQ} (@command{gcc})
5236 This switch suppresses warnings for cases where the association is not
5237 clear and the use of parentheses is preferred.
5238
5239 @item -gnatwr
5240 @emph{Activate warnings on redundant constructs.}
5241 @cindex @option{-gnatwr} (@command{gcc})
5242 This switch activates warnings for redundant constructs. The following
5243 is the current list of constructs regarded as redundant:
5244
5245 @itemize @bullet
5246 @item
5247 Assignment of an item to itself.
5248 @item
5249 Type conversion that converts an expression to its own type.
5250 @item
5251 Use of the attribute @code{Base} where @code{typ'Base} is the same
5252 as @code{typ}.
5253 @item
5254 Use of pragma @code{Pack} when all components are placed by a record
5255 representation clause.
5256 @item
5257 Exception handler containing only a reraise statement (raise with no
5258 operand) which has no effect.
5259 @item
5260 Use of the operator abs on an operand that is known at compile time
5261 to be non-negative
5262 @item
5263 Comparison of boolean expressions to an explicit True value.
5264 @end itemize
5265
5266 This warning can also be turned on using @option{-gnatwa}.
5267 The default is that warnings for redundant constructs are not given.
5268
5269 @item -gnatwR
5270 @emph{Suppress warnings on redundant constructs.}
5271 @cindex @option{-gnatwR} (@command{gcc})
5272 This switch suppresses warnings for redundant constructs.
5273
5274 @item -gnatws
5275 @emph{Suppress all warnings.}
5276 @cindex @option{-gnatws} (@command{gcc})
5277 This switch completely suppresses the
5278 output of all warning messages from the GNAT front end.
5279 Note that it does not suppress warnings from the @command{gcc} back end.
5280 To suppress these back end warnings as well, use the switch @option{-w}
5281 in addition to @option{-gnatws}.
5282
5283 @item -gnatwt
5284 @emph{Activate warnings for tracking of deleted conditional code.}
5285 @cindex @option{-gnatwt} (@command{gcc})
5286 @cindex Deactivated code, warnings
5287 @cindex Deleted code, warnings
5288 This switch activates warnings for tracking of code in conditionals (IF and
5289 CASE statements) that is detected to be dead code which cannot be executed, and
5290 which is removed by the front end. This warning is off by default, and is not
5291 turned on by @option{-gnatwa}, it has to be turned on explicitly. This may be
5292 useful for detecting deactivated code in certified applications.
5293
5294 @item -gnatwT
5295 @emph{Suppress warnings for tracking of deleted conditional code.}
5296 @cindex @option{-gnatwT} (@command{gcc})
5297 This switch suppresses warnings for tracking of deleted conditional code.
5298
5299 @item -gnatwu
5300 @emph{Activate warnings on unused entities.}
5301 @cindex @option{-gnatwu} (@command{gcc})
5302 This switch activates warnings to be generated for entities that
5303 are declared but not referenced, and for units that are @code{with}'ed
5304 and not
5305 referenced. In the case of packages, a warning is also generated if
5306 no entities in the package are referenced. This means that if the package
5307 is referenced but the only references are in @code{use}
5308 clauses or @code{renames}
5309 declarations, a warning is still generated. A warning is also generated
5310 for a generic package that is @code{with}'ed but never instantiated.
5311 In the case where a package or subprogram body is compiled, and there
5312 is a @code{with} on the corresponding spec
5313 that is only referenced in the body,
5314 a warning is also generated, noting that the
5315 @code{with} can be moved to the body. The default is that
5316 such warnings are not generated.
5317 This switch also activates warnings on unreferenced formals
5318 (it includes the effect of @option{-gnatwf}).
5319 This warning can also be turned on using @option{-gnatwa}.
5320
5321 @item -gnatwU
5322 @emph{Suppress warnings on unused entities.}
5323 @cindex @option{-gnatwU} (@command{gcc})
5324 This switch suppresses warnings for unused entities and packages.
5325 It also turns off warnings on unreferenced formals (and thus includes
5326 the effect of @option{-gnatwF}).
5327
5328 @item -gnatwv
5329 @emph{Activate warnings on unassigned variables.}
5330 @cindex @option{-gnatwv} (@command{gcc})
5331 @cindex Unassigned variable warnings
5332 This switch activates warnings for access to variables which
5333 may not be properly initialized. The default is that
5334 such warnings are generated.
5335 This warning can also be turned on using @option{-gnatwa}.
5336
5337 @item -gnatwV
5338 @emph{Suppress warnings on unassigned variables.}
5339 @cindex @option{-gnatwV} (@command{gcc})
5340 This switch suppresses warnings for access to variables which
5341 may not be properly initialized.
5342 For variables of a composite type, the warning can also be suppressed in
5343 Ada 2005 by using a default initialization with a box. For example, if
5344 Table is an array of records whose components are only partially uninitialized,
5345 then the following code:
5346
5347 @smallexample @c ada
5348    Tab : Table := (others => <>);
5349 @end smallexample
5350
5351 will suppress warnings on subsequent statements that access components
5352 of variable Tab.
5353
5354 @item -gnatww
5355 @emph{Activate warnings on wrong low bound assumption.}
5356 @cindex @option{-gnatww} (@command{gcc})
5357 @cindex String indexing warnings
5358 This switch activates warnings for indexing an unconstrained string parameter
5359 with a literal or S'Length. This is a case where the code is assuming that the
5360 low bound is one, which is in general not true (for example when a slice is
5361 passed). The default is that such warnings are generated.
5362 This warning can also be turned on using @option{-gnatwa}.
5363
5364 @item -gnatwW
5365 @emph{Suppress warnings on wrong low bound assumption.}
5366 @cindex @option{-gnatwW} (@command{gcc})
5367 This switch suppresses warnings for indexing an unconstrained string parameter
5368 with a literal or S'Length. Note that this warning can also be suppressed
5369 in a particular case by adding an
5370 assertion that the lower bound is 1,
5371 as shown in the following example.
5372
5373 @smallexample @c ada
5374    procedure K (S : String) is
5375       pragma Assert (S'First = 1);
5376       @dots{}
5377 @end smallexample
5378
5379 @item -gnatw.w
5380 @emph{Activate warnings on unnecessary Warnings Off pragmas}
5381 @cindex @option{-gnatw.w} (@command{gcc})
5382 @cindex Warnings Off control
5383 This switch activates warnings for use of @code{pragma Warnings (Off, entity}
5384 where either the pragma is entirely useless (because it suppresses no
5385 warnings), or it could be replaced by @code{pragma Unreferenced} or
5386 @code{pragma Unmodified}.The default is that these warnings are not given.
5387 Note that this warning is not included in -gnatwa, it must be
5388 activated explicitly.
5389
5390 @item -gnatw.W
5391 @emph{Suppress warnings on unnecessary Warnings Off pragmas}
5392 @cindex @option{-gnatw.W} (@command{gcc})
5393 This switch suppresses warnings for use of @code{pragma Warnings (Off, entity}.
5394
5395 @item -gnatwx
5396 @emph{Activate warnings on Export/Import pragmas.}
5397 @cindex @option{-gnatwx} (@command{gcc})
5398 @cindex Export/Import pragma warnings
5399 This switch activates warnings on Export/Import pragmas when
5400 the compiler detects a possible conflict between the Ada and
5401 foreign language calling sequences. For example, the use of
5402 default parameters in a convention C procedure is dubious
5403 because the C compiler cannot supply the proper default, so
5404 a warning is issued. The default is that such warnings are
5405 generated.
5406 This warning can also be turned on using @option{-gnatwa}.
5407
5408 @item -gnatwX
5409 @emph{Suppress warnings on Export/Import pragmas.}
5410 @cindex @option{-gnatwX} (@command{gcc})
5411 This switch suppresses warnings on Export/Import pragmas.
5412 The sense of this is that you are telling the compiler that
5413 you know what you are doing in writing the pragma, and it
5414 should not complain at you.
5415
5416 @item -gnatw.x
5417 @emph{Activate warnings for No_Exception_Propagation mode.}
5418 @cindex @option{-gnatwm} (@command{gcc})
5419 This switch activates warnings for exception usage when pragma Restrictions
5420 (No_Exception_Propagation) is in effect. Warnings are given for implicit or
5421 explicit exception raises which are not covered by a local handler, and for
5422 exception handlers which do not cover a local raise. The default is that these
5423 warnings are not given.
5424
5425 @item -gnatw.X
5426 @emph{Disable warnings for No_Exception_Propagation mode.}
5427 This switch disables warnings for exception usage when pragma Restrictions
5428 (No_Exception_Propagation) is in effect.
5429
5430 @item -gnatwy
5431 @emph{Activate warnings for Ada 2005 compatibility issues.}
5432 @cindex @option{-gnatwy} (@command{gcc})
5433 @cindex Ada 2005 compatibility issues warnings
5434 For the most part Ada 2005 is upwards compatible with Ada 95,
5435 but there are some exceptions (for example the fact that
5436 @code{interface} is now a reserved word in Ada 2005). This
5437 switch activates several warnings to help in identifying
5438 and correcting such incompatibilities. The default is that
5439 these warnings are generated. Note that at one point Ada 2005
5440 was called Ada 0Y, hence the choice of character.
5441 This warning can also be turned on using @option{-gnatwa}.
5442
5443 @item -gnatwY
5444 @emph{Disable warnings for Ada 2005 compatibility issues.}
5445 @cindex @option{-gnatwY} (@command{gcc})
5446 @cindex Ada 2005 compatibility issues warnings
5447 This switch suppresses several warnings intended to help in identifying
5448 incompatibilities between Ada 95 and Ada 2005.
5449
5450 @item -gnatwz
5451 @emph{Activate warnings on unchecked conversions.}
5452 @cindex @option{-gnatwz} (@command{gcc})
5453 @cindex Unchecked_Conversion warnings
5454 This switch activates warnings for unchecked conversions
5455 where the types are known at compile time to have different
5456 sizes. The default
5457 is that such warnings are generated. Warnings are also
5458 generated for subprogram pointers with different conventions,
5459 and, on VMS only, for data pointers with different conventions.
5460 This warning can also be turned on using @option{-gnatwa}.
5461
5462 @item -gnatwZ
5463 @emph{Suppress warnings on unchecked conversions.}
5464 @cindex @option{-gnatwZ} (@command{gcc})
5465 This switch suppresses warnings for unchecked conversions
5466 where the types are known at compile time to have different
5467 sizes or conventions.
5468
5469 @item ^-Wunused^WARNINGS=UNUSED^
5470 @cindex @option{-Wunused}
5471 The warnings controlled by the @option{-gnatw} switch are generated by
5472 the front end of the compiler. The @option{GCC} back end can provide
5473 additional warnings and they are controlled by the @option{-W} switch.
5474 For example, @option{^-Wunused^WARNINGS=UNUSED^} activates back end
5475 warnings for entities that are declared but not referenced.
5476
5477 @item ^-Wuninitialized^WARNINGS=UNINITIALIZED^
5478 @cindex @option{-Wuninitialized}
5479 Similarly, @option{^-Wuninitialized^WARNINGS=UNINITIALIZED^} activates
5480 the back end warning for uninitialized variables. This switch must be
5481 used in conjunction with an optimization level greater than zero.
5482
5483 @item ^-Wall^/ALL_BACK_END_WARNINGS^
5484 @cindex @option{-Wall}
5485 This switch enables all the above warnings from the @option{GCC} back end.
5486 The code generator detects a number of warning situations that are missed
5487 by the @option{GNAT} front end, and this switch can be used to activate them.
5488 The use of this switch also sets the default front end warning mode to
5489 @option{-gnatwa}, that is, most front end warnings activated as well.
5490
5491 @item ^-w^/NO_BACK_END_WARNINGS^
5492 @cindex @option{-w}
5493 Conversely, this switch suppresses warnings from the @option{GCC} back end.
5494 The use of this switch also sets the default front end warning mode to
5495 @option{-gnatws}, that is, front end warnings suppressed as well.
5496
5497 @end table
5498
5499 @noindent
5500 @ifclear vms
5501 A string of warning parameters can be used in the same parameter. For example:
5502
5503 @smallexample
5504 -gnatwaLe
5505 @end smallexample
5506
5507 @noindent
5508 will turn on all optional warnings except for elaboration pragma warnings,
5509 and also specify that warnings should be treated as errors.
5510 @end ifclear
5511 When no switch @option{^-gnatw^/WARNINGS^} is used, this is equivalent to:
5512
5513 @table @option
5514 @c !sort!
5515 @item -gnatwC
5516 @item -gnatwD
5517 @item -gnatwF
5518 @item -gnatwg
5519 @item -gnatwH
5520 @item -gnatwi
5521 @item -gnatwJ
5522 @item -gnatwK
5523 @item -gnatwL
5524 @item -gnatwM
5525 @item -gnatwn
5526 @item -gnatwo
5527 @item -gnatwP
5528 @item -gnatwR
5529 @item -gnatwU
5530 @item -gnatwv
5531 @item -gnatwz
5532 @item -gnatwx
5533
5534 @end table
5535
5536 @node Debugging and Assertion Control
5537 @subsection Debugging and Assertion Control
5538
5539 @table @option
5540 @item -gnata
5541 @cindex @option{-gnata} (@command{gcc})
5542 @findex Assert
5543 @findex Debug
5544 @cindex Assertions
5545
5546 @noindent
5547 The pragmas @code{Assert} and @code{Debug} normally have no effect and
5548 are ignored. This switch, where @samp{a} stands for assert, causes
5549 @code{Assert} and @code{Debug} pragmas to be activated.
5550
5551 The pragmas have the form:
5552
5553 @smallexample
5554 @cartouche
5555    @b{pragma} Assert (@var{Boolean-expression} @r{[},
5556                       @var{static-string-expression}@r{]})
5557    @b{pragma} Debug (@var{procedure call})
5558 @end cartouche
5559 @end smallexample
5560
5561 @noindent
5562 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
5563 If the result is @code{True}, the pragma has no effect (other than
5564 possible side effects from evaluating the expression). If the result is
5565 @code{False}, the exception @code{Assert_Failure} declared in the package
5566 @code{System.Assertions} is
5567 raised (passing @var{static-string-expression}, if present, as the
5568 message associated with the exception). If no string expression is
5569 given the default is a string giving the file name and line number
5570 of the pragma.
5571
5572 The @code{Debug} pragma causes @var{procedure} to be called. Note that
5573 @code{pragma Debug} may appear within a declaration sequence, allowing
5574 debugging procedures to be called between declarations.
5575
5576 @ifset vms
5577 @item /DEBUG@r{[}=debug-level@r{]}
5578 @itemx  /NODEBUG
5579 Specifies how much debugging information is to be included in
5580 the resulting object file where 'debug-level' is one of the following:
5581 @table @code
5582 @item   TRACEBACK
5583 Include both debugger symbol records and traceback
5584 the object file.
5585 This is the default setting.
5586 @item   ALL
5587 Include both debugger symbol records and traceback in
5588 object file.
5589 @item   NONE
5590 Excludes both debugger symbol records and traceback
5591 the object file. Same as /NODEBUG.
5592 @item   SYMBOLS
5593 Includes only debugger symbol records in the object
5594 file. Note that this doesn't include traceback information.
5595 @end table
5596 @end ifset
5597 @end table
5598
5599 @node Validity Checking
5600 @subsection Validity Checking
5601 @findex Validity Checking
5602
5603 @noindent
5604 The Ada Reference Manual has specific requirements for checking
5605 for invalid values. In particular, RM 13.9.1 requires that the
5606 evaluation of invalid values (for example from unchecked conversions),
5607 not result in erroneous execution. In GNAT, the result of such an
5608 evaluation in normal default mode is to either use the value
5609 unmodified, or to raise Constraint_Error in those cases where use
5610 of the unmodified value would cause erroneous execution. The cases
5611 where unmodified values might lead to erroneous execution are case
5612 statements (where a wild jump might result from an invalid value),
5613 and subscripts on the left hand side (where memory corruption could
5614 occur as a result of an invalid value).
5615
5616 The @option{-gnatB} switch tells the compiler to assume that all
5617 values are valid (that is, within their declared subtype range)
5618 except in the context of a use of the Valid attribute. This means
5619 the compiler can generate more efficient code, since the range
5620 of values is better known at compile time.
5621
5622 The @option{-gnatV^@var{x}^^} switch allows more control over the validity
5623 checking mode.
5624 @ifclear vms
5625 The @code{x} argument is a string of letters that
5626 indicate validity checks that are performed or not performed in addition
5627 to the default checks described above.
5628 @end ifclear
5629 @ifset vms
5630 The options allowed for this qualifier
5631 indicate validity checks that are performed or not performed in addition
5632 to the default checks described above.
5633 @end ifset
5634
5635 @table @option
5636 @c !sort!
5637 @item -gnatVa
5638 @emph{All validity checks.}
5639 @cindex @option{-gnatVa} (@command{gcc})
5640 All validity checks are turned on.
5641 @ifclear vms
5642 That is, @option{-gnatVa} is
5643 equivalent to @option{gnatVcdfimorst}.
5644 @end ifclear
5645
5646 @item -gnatVc
5647 @emph{Validity checks for copies.}
5648 @cindex @option{-gnatVc} (@command{gcc})
5649 The right hand side of assignments, and the initializing values of
5650 object declarations are validity checked.
5651
5652 @item -gnatVd
5653 @emph{Default (RM) validity checks.}
5654 @cindex @option{-gnatVd} (@command{gcc})
5655 Some validity checks are done by default following normal Ada semantics
5656 (RM 13.9.1 (9-11)).
5657 A check is done in case statements that the expression is within the range
5658 of the subtype. If it is not, Constraint_Error is raised.
5659 For assignments to array components, a check is done that the expression used
5660 as index is within the range. If it is not, Constraint_Error is raised.
5661 Both these validity checks may be turned off using switch @option{-gnatVD}.
5662 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
5663 switch @option{-gnatVd} will leave the checks turned on.
5664 Switch @option{-gnatVD} should be used only if you are sure that all such
5665 expressions have valid values. If you use this switch and invalid values
5666 are present, then the program is erroneous, and wild jumps or memory
5667 overwriting may occur.
5668
5669 @item -gnatVe
5670 @emph{Validity checks for elementary components.}
5671 @cindex @option{-gnatVe} (@command{gcc})
5672 In the absence of this switch, assignments to record or array components are
5673 not validity checked, even if validity checks for assignments generally
5674 (@option{-gnatVc}) are turned on. In Ada, assignment of composite values do not
5675 require valid data, but assignment of individual components does. So for
5676 example, there is a difference between copying the elements of an array with a
5677 slice assignment, compared to assigning element by element in a loop. This
5678 switch allows you to turn off validity checking for components, even when they
5679 are assigned component by component.
5680
5681 @item -gnatVf
5682 @emph{Validity checks for floating-point values.}
5683 @cindex @option{-gnatVf} (@command{gcc})
5684 In the absence of this switch, validity checking occurs only for discrete
5685 values. If @option{-gnatVf} is specified, then validity checking also applies
5686 for floating-point values, and NaNs and infinities are considered invalid,
5687 as well as out of range values for constrained types. Note that this means
5688 that standard IEEE infinity mode is not allowed. The exact contexts
5689 in which floating-point values are checked depends on the setting of other
5690 options. For example,
5691 @option{^-gnatVif^VALIDITY_CHECKING=(IN_PARAMS,FLOATS)^} or
5692 @option{^-gnatVfi^VALIDITY_CHECKING=(FLOATS,IN_PARAMS)^}
5693 (the order does not matter) specifies that floating-point parameters of mode
5694 @code{in} should be validity checked.
5695
5696 @item -gnatVi
5697 @emph{Validity checks for @code{in} mode parameters}
5698 @cindex @option{-gnatVi} (@command{gcc})
5699 Arguments for parameters of mode @code{in} are validity checked in function
5700 and procedure calls at the point of call.
5701
5702 @item -gnatVm
5703 @emph{Validity checks for @code{in out} mode parameters.}
5704 @cindex @option{-gnatVm} (@command{gcc})
5705 Arguments for parameters of mode @code{in out} are validity checked in
5706 procedure calls at the point of call. The @code{'m'} here stands for
5707 modify, since this concerns parameters that can be modified by the call.
5708 Note that there is no specific option to test @code{out} parameters,
5709 but any reference within the subprogram will be tested in the usual
5710 manner, and if an invalid value is copied back, any reference to it
5711 will be subject to validity checking.
5712
5713 @item -gnatVn
5714 @emph{No validity checks.}
5715 @cindex @option{-gnatVn} (@command{gcc})
5716 This switch turns off all validity checking, including the default checking
5717 for case statements and left hand side subscripts. Note that the use of
5718 the switch @option{-gnatp} suppresses all run-time checks, including
5719 validity checks, and thus implies @option{-gnatVn}. When this switch
5720 is used, it cancels any other @option{-gnatV} previously issued.
5721
5722 @item -gnatVo
5723 @emph{Validity checks for operator and attribute operands.}
5724 @cindex @option{-gnatVo} (@command{gcc})
5725 Arguments for predefined operators and attributes are validity checked.
5726 This includes all operators in package @code{Standard},
5727 the shift operators defined as intrinsic in package @code{Interfaces}
5728 and operands for attributes such as @code{Pos}. Checks are also made
5729 on individual component values for composite comparisons, and on the
5730 expressions in type conversions and qualified expressions. Checks are
5731 also made on explicit ranges using @samp{..} (e.g.@: slices, loops etc).
5732
5733 @item -gnatVp
5734 @emph{Validity checks for parameters.}
5735 @cindex @option{-gnatVp} (@command{gcc})
5736 This controls the treatment of parameters within a subprogram (as opposed
5737 to @option{-gnatVi} and @option{-gnatVm} which control validity testing
5738 of parameters on a call. If either of these call options is used, then
5739 normally an assumption is made within a subprogram that the input arguments
5740 have been validity checking at the point of call, and do not need checking
5741 again within a subprogram). If @option{-gnatVp} is set, then this assumption
5742 is not made, and parameters are not assumed to be valid, so their validity
5743 will be checked (or rechecked) within the subprogram.
5744
5745 @item -gnatVr
5746 @emph{Validity checks for function returns.}
5747 @cindex @option{-gnatVr} (@command{gcc})
5748 The expression in @code{return} statements in functions is validity
5749 checked.
5750
5751 @item -gnatVs
5752 @emph{Validity checks for subscripts.}
5753 @cindex @option{-gnatVs} (@command{gcc})
5754 All subscripts expressions are checked for validity, whether they appear
5755 on the right side or left side (in default mode only left side subscripts
5756 are validity checked).
5757
5758 @item -gnatVt
5759 @emph{Validity checks for tests.}
5760 @cindex @option{-gnatVt} (@command{gcc})
5761 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
5762 statements are checked, as well as guard expressions in entry calls.
5763
5764 @end table
5765
5766 @noindent
5767 The @option{-gnatV} switch may be followed by
5768 ^a string of letters^a list of options^
5769 to turn on a series of validity checking options.
5770 For example,
5771 @option{^-gnatVcr^/VALIDITY_CHECKING=(COPIES, RETURNS)^}
5772 specifies that in addition to the default validity checking, copies and
5773 function return expressions are to be validity checked.
5774 In order to make it easier
5775 to specify the desired combination of effects,
5776 @ifclear vms
5777 the upper case letters @code{CDFIMORST} may
5778 be used to turn off the corresponding lower case option.
5779 @end ifclear
5780 @ifset vms
5781 the prefix @code{NO} on an option turns off the corresponding validity
5782 checking:
5783 @itemize @bullet
5784 @item @code{NOCOPIES}
5785 @item @code{NODEFAULT}
5786 @item @code{NOFLOATS}
5787 @item @code{NOIN_PARAMS}
5788 @item @code{NOMOD_PARAMS}
5789 @item @code{NOOPERANDS}
5790 @item @code{NORETURNS}
5791 @item @code{NOSUBSCRIPTS}
5792 @item @code{NOTESTS}
5793 @end itemize
5794 @end ifset
5795 Thus
5796 @option{^-gnatVaM^/VALIDITY_CHECKING=(ALL, NOMOD_PARAMS)^}
5797 turns on all validity checking options except for
5798 checking of @code{@b{in out}} procedure arguments.
5799
5800 The specification of additional validity checking generates extra code (and
5801 in the case of @option{-gnatVa} the code expansion can be substantial).
5802 However, these additional checks can be very useful in detecting
5803 uninitialized variables, incorrect use of unchecked conversion, and other
5804 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
5805 is useful in conjunction with the extra validity checking, since this
5806 ensures that wherever possible uninitialized variables have invalid values.
5807
5808 See also the pragma @code{Validity_Checks} which allows modification of
5809 the validity checking mode at the program source level, and also allows for
5810 temporary disabling of validity checks.
5811
5812 @node Style Checking
5813 @subsection Style Checking
5814 @findex Style checking
5815
5816 @noindent
5817 The @option{-gnaty^x^(option,option,@dots{})^} switch
5818 @cindex @option{-gnaty} (@command{gcc})
5819 causes the compiler to
5820 enforce specified style rules. A limited set of style rules has been used
5821 in writing the GNAT sources themselves. This switch allows user programs
5822 to activate all or some of these checks. If the source program fails a
5823 specified style check, an appropriate warning message is given, preceded by
5824 the character sequence ``(style)''.
5825 @ifset vms
5826 @code{(option,option,@dots{})} is a sequence of keywords
5827 @end ifset
5828 @ifclear vms
5829 The string @var{x} is a sequence of letters or digits
5830 @end ifclear
5831 indicating the particular style
5832 checks to be performed. The following checks are defined:
5833
5834 @table @option
5835 @c !sort!
5836 @item 0-9
5837 @emph{Specify indentation level.}
5838 If a digit from 1-9 appears
5839 ^in the string after @option{-gnaty}^as an option for /STYLE_CHECKS^
5840 then proper indentation is checked, with the digit indicating the
5841 indentation level required. A value of zero turns off this style check.
5842 The general style of required indentation is as specified by
5843 the examples in the Ada Reference Manual. Full line comments must be
5844 aligned with the @code{--} starting on a column that is a multiple of
5845 the alignment level, or they may be aligned the same way as the following
5846 non-blank line (this is useful when full line comments appear in the middle
5847 of a statement.
5848
5849 @item ^a^ATTRIBUTE^
5850 @emph{Check attribute casing.}
5851 Attribute names, including the case of keywords such as @code{digits}
5852 used as attributes names, must be written in mixed case, that is, the
5853 initial letter and any letter following an underscore must be uppercase.
5854 All other letters must be lowercase.
5855
5856 @item ^A^ARRAY_INDEXES^
5857 @emph{Use of array index numbers in array attributes.}
5858 When using the array attributes First, Last, Range,
5859 or Length, the index number must be omitted for one-dimensional arrays
5860 and is required for multi-dimensional arrays.
5861
5862 @item ^b^BLANKS^
5863 @emph{Blanks not allowed at statement end.}
5864 Trailing blanks are not allowed at the end of statements. The purpose of this
5865 rule, together with h (no horizontal tabs), is to enforce a canonical format
5866 for the use of blanks to separate source tokens.
5867
5868 @item ^c^COMMENTS^
5869 @emph{Check comments.}
5870 Comments must meet the following set of rules:
5871
5872 @itemize @bullet
5873
5874 @item
5875 The ``@code{--}'' that starts the column must either start in column one,
5876 or else at least one blank must precede this sequence.
5877
5878 @item
5879 Comments that follow other tokens on a line must have at least one blank
5880 following the ``@code{--}'' at the start of the comment.
5881
5882 @item
5883 Full line comments must have two blanks following the ``@code{--}'' that
5884 starts the comment, with the following exceptions.
5885
5886 @item
5887 A line consisting only of the ``@code{--}'' characters, possibly preceded
5888 by blanks is permitted.
5889
5890 @item
5891 A comment starting with ``@code{--x}'' where @code{x} is a special character
5892 is permitted.
5893 This allows proper processing of the output generated by specialized tools
5894 including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK
5895 annotation
5896 language (where ``@code{--#}'' is used). For the purposes of this rule, a
5897 special character is defined as being in one of the ASCII ranges
5898 @code{16#21#@dots{}16#2F#} or @code{16#3A#@dots{}16#3F#}.
5899 Note that this usage is not permitted
5900 in GNAT implementation units (i.e., when @option{-gnatg} is used).
5901
5902 @item
5903 A line consisting entirely of minus signs, possibly preceded by blanks, is
5904 permitted. This allows the construction of box comments where lines of minus
5905 signs are used to form the top and bottom of the box.
5906
5907 @item
5908 A comment that starts and ends with ``@code{--}'' is permitted as long as at
5909 least one blank follows the initial ``@code{--}''. Together with the preceding
5910 rule, this allows the construction of box comments, as shown in the following
5911 example:
5912 @smallexample
5913 ---------------------------
5914 -- This is a box comment --
5915 -- with two text lines.  --
5916 ---------------------------
5917 @end smallexample
5918 @end itemize
5919
5920 @item ^d^DOS_LINE_ENDINGS^
5921 @emph{Check no DOS line terminators present.}
5922 All lines must be terminated by a single ASCII.LF
5923 character (in particular the DOS line terminator sequence CR/LF is not
5924 allowed).
5925
5926 @item ^e^END^
5927 @emph{Check end/exit labels.}
5928 Optional labels on @code{end} statements ending subprograms and on
5929 @code{exit} statements exiting named loops, are required to be present.
5930
5931 @item ^f^VTABS^
5932 @emph{No form feeds or vertical tabs.}
5933 Neither form feeds nor vertical tab characters are permitted
5934 in the source text.
5935
5936 @item ^g^GNAT^
5937 @emph{GNAT style mode}
5938 The set of style check switches is set to match that used by the GNAT sources.
5939 This may be useful when developing code that is eventually intended to be
5940 incorporated into GNAT. For further details, see GNAT sources.
5941
5942 @item ^h^HTABS^
5943 @emph{No horizontal tabs.}
5944 Horizontal tab characters are not permitted in the source text.
5945 Together with the b (no blanks at end of line) check, this
5946 enforces a canonical form for the use of blanks to separate
5947 source tokens.
5948
5949 @item ^i^IF_THEN^
5950 @emph{Check if-then layout.}
5951 The keyword @code{then} must appear either on the same
5952 line as corresponding @code{if}, or on a line on its own, lined
5953 up under the @code{if} with at least one non-blank line in between
5954 containing all or part of the condition to be tested.
5955
5956 @item ^I^IN_MODE^
5957 @emph{check mode IN keywords}
5958 Mode @code{in} (the default mode) is not
5959 allowed to be given explicitly. @code{in out} is fine,
5960 but not @code{in} on its own.
5961
5962 @item ^k^KEYWORD^
5963 @emph{Check keyword casing.}
5964 All keywords must be in lower case (with the exception of keywords
5965 such as @code{digits} used as attribute names to which this check
5966 does not apply).
5967
5968 @item ^l^LAYOUT^
5969 @emph{Check layout.}
5970 Layout of statement and declaration constructs must follow the
5971 recommendations in the Ada Reference Manual, as indicated by the
5972 form of the syntax rules. For example an @code{else} keyword must
5973 be lined up with the corresponding @code{if} keyword.
5974
5975 There are two respects in which the style rule enforced by this check
5976 option are more liberal than those in the Ada Reference Manual. First
5977 in the case of record declarations, it is permissible to put the
5978 @code{record} keyword on the same line as the @code{type} keyword, and
5979 then the @code{end} in @code{end record} must line up under @code{type}.
5980 This is also permitted when the type declaration is split on two lines.
5981 For example, any of the following three layouts is acceptable:
5982
5983 @smallexample @c ada
5984 @cartouche
5985 type q is record
5986    a : integer;
5987    b : integer;
5988 end record;
5989
5990 type q is
5991    record
5992       a : integer;
5993       b : integer;
5994    end record;
5995
5996 type q is
5997    record
5998       a : integer;
5999       b : integer;
6000 end record;
6001
6002 @end cartouche
6003 @end smallexample
6004
6005 @noindent
6006 Second, in the case of a block statement, a permitted alternative
6007 is to put the block label on the same line as the @code{declare} or
6008 @code{begin} keyword, and then line the @code{end} keyword up under
6009 the block label. For example both the following are permitted:
6010
6011 @smallexample @c ada
6012 @cartouche
6013 Block : declare
6014    A : Integer := 3;
6015 begin
6016    Proc (A, A);
6017 end Block;
6018
6019 Block :
6020    declare
6021       A : Integer := 3;
6022    begin
6023       Proc (A, A);
6024    end Block;
6025 @end cartouche
6026 @end smallexample
6027
6028 @noindent
6029 The same alternative format is allowed for loops. For example, both of
6030 the following are permitted:
6031
6032 @smallexample @c ada
6033 @cartouche
6034 Clear : while J < 10 loop
6035    A (J) := 0;
6036 end loop Clear;
6037
6038 Clear :
6039    while J < 10 loop
6040       A (J) := 0;
6041    end loop Clear;
6042 @end cartouche
6043 @end smallexample
6044
6045 @item ^Lnnn^MAX_NESTING=nnn^
6046 @emph{Set maximum nesting level}
6047 The maximum level of nesting of constructs (including subprograms, loops,
6048 blocks, packages, and conditionals) may not exceed the given value
6049 @option{nnn}. A value of zero disconnects this style check.
6050
6051 @item ^m^LINE_LENGTH^
6052 @emph{Check maximum line length.}
6053 The length of source lines must not exceed 79 characters, including
6054 any trailing blanks. The value of 79 allows convenient display on an
6055 80 character wide device or window, allowing for possible special
6056 treatment of 80 character lines. Note that this count is of
6057 characters in the source text. This means that a tab character counts
6058 as one character in this count but a wide character sequence counts as
6059 a single character (however many bytes are needed in the encoding).
6060
6061 @item ^Mnnn^MAX_LENGTH=nnn^
6062 @emph{Set maximum line length.}
6063 The length of lines must not exceed the
6064 given value @option{nnn}. The maximum value that can be specified is 32767.
6065
6066 @item ^n^STANDARD_CASING^
6067 @emph{Check casing of entities in Standard.}
6068 Any identifier from Standard must be cased
6069 to match the presentation in the Ada Reference Manual (for example,
6070 @code{Integer} and @code{ASCII.NUL}).
6071
6072 @item ^N^NONE^
6073 @emph{Turn off all style checks}
6074 All style check options are turned off.
6075
6076 @item ^o^ORDERED_SUBPROGRAMS^
6077 @emph{Check order of subprogram bodies.}
6078 All subprogram bodies in a given scope
6079 (e.g.@: a package body) must be in alphabetical order. The ordering
6080 rule uses normal Ada rules for comparing strings, ignoring casing
6081 of letters, except that if there is a trailing numeric suffix, then
6082 the value of this suffix is used in the ordering (e.g.@: Junk2 comes
6083 before Junk10).
6084
6085 @item ^O^OVERRIDING_INDICATORS^
6086 @emph{Check that overriding subprograms are explicitly marked as such.}
6087 The declaration of a primitive operation of a type extension that overrides
6088 an inherited operation must carry an overriding indicator.
6089
6090 @item ^p^PRAGMA^
6091 @emph{Check pragma casing.}
6092 Pragma names must be written in mixed case, that is, the
6093 initial letter and any letter following an underscore must be uppercase.
6094 All other letters must be lowercase.
6095
6096 @item ^r^REFERENCES^
6097 @emph{Check references.}
6098 All identifier references must be cased in the same way as the
6099 corresponding declaration. No specific casing style is imposed on
6100 identifiers. The only requirement is for consistency of references
6101 with declarations.
6102
6103 @item ^S^STATEMENTS_AFTER_THEN_ELSE^
6104 @emph{Check no statements after THEN/ELSE.}
6105 No statements are allowed
6106 on the same line as a THEN or ELSE keyword following the
6107 keyword in an IF statement. OR ELSE and AND THEN are not affected,
6108 and a special exception allows a pragma to appear after ELSE.
6109
6110 @item ^s^SPECS^
6111 @emph{Check separate specs.}
6112 Separate declarations (``specs'') are required for subprograms (a
6113 body is not allowed to serve as its own declaration). The only
6114 exception is that parameterless library level procedures are
6115 not required to have a separate declaration. This exception covers
6116 the most frequent form of main program procedures.
6117
6118 @item ^t^TOKEN^
6119 @emph{Check token spacing.}
6120 The following token spacing rules are enforced:
6121
6122 @itemize @bullet
6123
6124 @item
6125 The keywords @code{@b{abs}} and @code{@b{not}} must be followed by a space.
6126
6127 @item
6128 The token @code{=>} must be surrounded by spaces.
6129
6130 @item
6131 The token @code{<>} must be preceded by a space or a left parenthesis.
6132
6133 @item
6134 Binary operators other than @code{**} must be surrounded by spaces.
6135 There is no restriction on the layout of the @code{**} binary operator.
6136
6137 @item
6138 Colon must be surrounded by spaces.
6139
6140 @item
6141 Colon-equal (assignment, initialization) must be surrounded by spaces.
6142
6143 @item
6144 Comma must be the first non-blank character on the line, or be
6145 immediately preceded by a non-blank character, and must be followed
6146 by a space.
6147
6148 @item
6149 If the token preceding a left parenthesis ends with a letter or digit, then
6150 a space must separate the two tokens.
6151
6152 @item
6153 A right parenthesis must either be the first non-blank character on
6154 a line, or it must be preceded by a non-blank character.
6155
6156 @item
6157 A semicolon must not be preceded by a space, and must not be followed by
6158 a non-blank character.
6159
6160 @item
6161 A unary plus or minus may not be followed by a space.
6162
6163 @item
6164 A vertical bar must be surrounded by spaces.
6165 @end itemize
6166
6167 @item ^u^UNNECESSARY_BLANK_LINES^
6168 @emph{Check unnecessary blank lines.}
6169 Unnecessary blank lines are not allowed. A blank line is considered
6170 unnecessary if it appears at the end of the file, or if more than
6171 one blank line occurs in sequence.
6172
6173 @item ^x^XTRA_PARENS^
6174 @emph{Check extra parentheses.}
6175 Unnecessary extra level of parentheses (C-style) are not allowed
6176 around conditions in @code{if} statements, @code{while} statements and
6177 @code{exit} statements.
6178
6179 @item ^y^ALL_BUILTIN^
6180 @emph{Set all standard style check options}
6181 This is equivalent to @code{gnaty3aAbcefhiklmnprst}, that is all checking
6182 options enabled with the exception of @option{-gnatyo}, @option{-gnatyI},
6183 @option{-gnatyS}, @option{-gnatyLnnn},
6184 @option{-gnatyd}, @option{-gnatyu}, and @option{-gnatyx}.
6185
6186 @ifclear vms
6187 @item -
6188 @emph{Remove style check options}
6189 This causes any subsequent options in the string to act as canceling the
6190 corresponding style check option. To cancel maximum nesting level control,
6191 use @option{L} parameter witout any integer value after that, because any
6192 digit following @option{-} in the parameter string of the @option{-gnaty}
6193 option will be threated as canceling indentation check. The same is true
6194 for @option{M} parameter. @option{y} and @option{N} parameters are not
6195 allowed after @option{-}.
6196
6197 @item +
6198 This causes any subsequent options in the string to enable the corresponding
6199 style check option. That is, it cancels the effect of a previous ^-^REMOVE^,
6200 if any.
6201 @end ifclear
6202
6203 @ifset vms
6204 @item NOxxx
6205 @emph{Removing style check options}
6206 If the name of a style check is preceded by @option{NO} then the corresponding
6207 style check is turned off. For example @option{NOCOMMENTS} turns off style
6208 checking for comments.
6209 @end ifset
6210 @end table
6211
6212 @noindent
6213 In the above rules, appearing in column one is always permitted, that is,
6214 counts as meeting either a requirement for a required preceding space,
6215 or as meeting a requirement for no preceding space.
6216
6217 Appearing at the end of a line is also always permitted, that is, counts
6218 as meeting either a requirement for a following space, or as meeting
6219 a requirement for no following space.
6220
6221 @noindent
6222 If any of these style rules is violated, a message is generated giving
6223 details on the violation. The initial characters of such messages are
6224 always ``@code{(style)}''. Note that these messages are treated as warning
6225 messages, so they normally do not prevent the generation of an object
6226 file. The @option{-gnatwe} switch can be used to treat warning messages,
6227 including style messages, as fatal errors.
6228
6229 The switch
6230 @ifclear vms
6231 @option{-gnaty} on its own (that is not
6232 followed by any letters or digits), then the effect is equivalent
6233 to the use of @option{-gnatyy}, as described above, that is all
6234 built-in standard style check options are enabled.
6235
6236 @end ifclear
6237 @ifset vms
6238 /STYLE_CHECKS=ALL_BUILTIN enables all checking options with
6239 the exception of ORDERED_SUBPROGRAMS, UNNECESSARY_BLANK_LINES,
6240 XTRA_PARENS, and DOS_LINE_ENDINGS. In addition
6241 @end ifset
6242
6243
6244
6245 The switch
6246 @ifclear vms
6247 @option{-gnatyN}
6248 @end ifclear
6249 @ifset vms
6250 /STYLE_CHECKS=NONE
6251 @end ifset
6252 clears any previously set style checks.
6253
6254 @node Run-Time Checks
6255 @subsection Run-Time Checks
6256 @cindex Division by zero
6257 @cindex Access before elaboration
6258 @cindex Checks, division by zero
6259 @cindex Checks, access before elaboration
6260 @cindex Checks, stack overflow checking
6261
6262 @noindent
6263 By default, the following checks are suppressed: integer overflow
6264 checks, stack overflow checks, and checks for access before
6265 elaboration on subprogram calls. All other checks, including range
6266 checks and array bounds checks, are turned on by default. The
6267 following @command{gcc} switches refine this default behavior.
6268
6269 @table @option
6270 @c !sort!
6271 @item -gnatp
6272 @cindex @option{-gnatp} (@command{gcc})
6273 @cindex Suppressing checks
6274 @cindex Checks, suppressing
6275 @findex Suppress
6276 Suppress all run-time checks as though @code{pragma Suppress (All_checks)}
6277 had been present in the source. Validity checks are also suppressed (in
6278 other words @option{-gnatp} also implies @option{-gnatVn}.
6279 Use this switch to improve the performance
6280 of the code at the expense of safety in the presence of invalid data or
6281 program bugs.
6282
6283 Note that when checks are suppressed, the compiler is allowed, but not
6284 required, to omit the checking code. If the run-time cost of the
6285 checking code is zero or near-zero, the compiler will generate it even
6286 if checks are suppressed. In particular, if the compiler can prove
6287 that a certain check will necessarily fail, it will generate code to
6288 do an unconditional ``raise'', even if checks are suppressed. The
6289 compiler warns in this case.
6290
6291 Of course, run-time checks are omitted whenever the compiler can prove
6292 that they will not fail, whether or not checks are suppressed.
6293
6294 Note that if you suppress a check that would have failed, program
6295 execution is erroneous, which means the behavior is totally
6296 unpredictable. The program might crash, or print wrong answers, or
6297 do anything else. It might even do exactly what you wanted it to do
6298 (and then it might start failing mysteriously next week or next
6299 year). The compiler will generate code based on the assumption that
6300 the condition being checked is true, which can result in disaster if
6301 that assumption is wrong.
6302
6303 @item -gnato
6304 @cindex @option{-gnato} (@command{gcc})
6305 @cindex Overflow checks
6306 @cindex Check, overflow
6307 Enables overflow checking for integer operations.
6308 This causes GNAT to generate slower and larger executable
6309 programs by adding code to check for overflow (resulting in raising
6310 @code{Constraint_Error} as required by standard Ada
6311 semantics). These overflow checks correspond to situations in which
6312 the true value of the result of an operation may be outside the base
6313 range of the result type. The following example shows the distinction:
6314
6315 @smallexample @c ada
6316 X1 : Integer := "Integer'Last";
6317 X2 : Integer range 1 .. 5 := "5";
6318 X3 : Integer := "Integer'Last";
6319 X4 : Integer range 1 .. 5 := "5";
6320 F  : Float := "2.0E+20";
6321 @dots{}
6322 X1 := X1 + 1;
6323 X2 := X2 + 1;
6324 X3 := Integer (F);
6325 X4 := Integer (F);
6326 @end smallexample
6327
6328 @noindent
6329 Note that if explicit values are assigned at compile time, the
6330 compiler may be able to detect overflow at compile time, in which case
6331 no actual run-time checking code is required, and Constraint_Error
6332 will be raised unconditionally, with or without
6333 @option{-gnato}. That's why the assigned values in the above fragment
6334 are in quotes, the meaning is "assign a value not known to the
6335 compiler that happens to be equal to ...". The remaining discussion
6336 assumes that the compiler cannot detect the values at compile time.
6337
6338 Here the first addition results in a value that is outside the base range
6339 of Integer, and hence requires an overflow check for detection of the
6340 constraint error. Thus the first assignment to @code{X1} raises a
6341 @code{Constraint_Error} exception only if @option{-gnato} is set.
6342
6343 The second increment operation results in a violation of the explicit
6344 range constraint; such range checks are performed by default, and are
6345 unaffected by @option{-gnato}.
6346
6347 The two conversions of @code{F} both result in values that are outside
6348 the base range of type @code{Integer} and thus will raise
6349 @code{Constraint_Error} exceptions only if @option{-gnato} is used.
6350 The fact that the result of the second conversion is assigned to
6351 variable @code{X4} with a restricted range is irrelevant, since the problem
6352 is in the conversion, not the assignment.
6353
6354 Basically the rule is that in the default mode (@option{-gnato} not
6355 used), the generated code assures that all integer variables stay
6356 within their declared ranges, or within the base range if there is
6357 no declared range. This prevents any serious problems like indexes
6358 out of range for array operations.
6359
6360 What is not checked in default mode is an overflow that results in
6361 an in-range, but incorrect value. In the above example, the assignments
6362 to @code{X1}, @code{X2}, @code{X3} all give results that are within the
6363 range of the target variable, but the result is wrong in the sense that
6364 it is too large to be represented correctly. Typically the assignment
6365 to @code{X1} will result in wrap around to the largest negative number.
6366 The conversions of @code{F} will result in some @code{Integer} value
6367 and if that integer value is out of the @code{X4} range then the
6368 subsequent assignment would generate an exception.
6369
6370 @findex Machine_Overflows
6371 Note that the @option{-gnato} switch does not affect the code generated
6372 for any floating-point operations; it applies only to integer
6373 semantics).
6374 For floating-point, GNAT has the @code{Machine_Overflows}
6375 attribute set to @code{False} and the normal mode of operation is to
6376 generate IEEE NaN and infinite values on overflow or invalid operations
6377 (such as dividing 0.0 by 0.0).
6378
6379 The reason that we distinguish overflow checking from other kinds of
6380 range constraint checking is that a failure of an overflow check, unlike
6381 for example the failure of a range check, can result in an incorrect
6382 value, but cannot cause random memory destruction (like an out of range
6383 subscript), or a wild jump (from an out of range case value). Overflow
6384 checking is also quite expensive in time and space, since in general it
6385 requires the use of double length arithmetic.
6386
6387 Note again that @option{-gnato} is off by default, so overflow checking is
6388 not performed in default mode. This means that out of the box, with the
6389 default settings, GNAT does not do all the checks expected from the
6390 language description in the Ada Reference Manual. If you want all constraint
6391 checks to be performed, as described in this Manual, then you must
6392 explicitly use the -gnato switch either on the @command{gnatmake} or
6393 @command{gcc} command.
6394
6395 @item -gnatE
6396 @cindex @option{-gnatE} (@command{gcc})
6397 @cindex Elaboration checks
6398 @cindex Check, elaboration
6399 Enables dynamic checks for access-before-elaboration
6400 on subprogram calls and generic instantiations.
6401 Note that @option{-gnatE} is not necessary for safety, because in the
6402 default mode, GNAT ensures statically that the checks would not fail.
6403 For full details of the effect and use of this switch,
6404 @xref{Compiling Using gcc}.
6405
6406 @item -fstack-check
6407 @cindex @option{-fstack-check} (@command{gcc})
6408 @cindex Stack Overflow Checking
6409 @cindex Checks, stack overflow checking
6410 Activates stack overflow checking. For full details of the effect and use of
6411 this switch see @ref{Stack Overflow Checking}.
6412 @end table
6413
6414 @findex Unsuppress
6415 @noindent
6416 The setting of these switches only controls the default setting of the
6417 checks. You may modify them using either @code{Suppress} (to remove
6418 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
6419 the program source.
6420
6421 @node Using gcc for Syntax Checking
6422 @subsection Using @command{gcc} for Syntax Checking
6423 @table @option
6424 @item -gnats
6425 @cindex @option{-gnats} (@command{gcc})
6426 @ifclear vms
6427
6428 @noindent
6429 The @code{s} stands for ``syntax''.
6430 @end ifclear
6431
6432 Run GNAT in syntax checking only mode. For
6433 example, the command
6434
6435 @smallexample
6436 $ gcc -c -gnats x.adb
6437 @end smallexample
6438
6439 @noindent
6440 compiles file @file{x.adb} in syntax-check-only mode. You can check a
6441 series of files in a single command
6442 @ifclear vms
6443 , and can use wild cards to specify such a group of files.
6444 Note that you must specify the @option{-c} (compile
6445 only) flag in addition to the @option{-gnats} flag.
6446 @end ifclear
6447 .
6448 You may use other switches in conjunction with @option{-gnats}. In
6449 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
6450 format of any generated error messages.
6451
6452 When the source file is empty or contains only empty lines and/or comments,
6453 the output is a warning:
6454
6455 @smallexample
6456 $ gcc -c -gnats -x ada toto.txt
6457 toto.txt:1:01: warning: empty file, contains no compilation units
6458 $
6459 @end smallexample
6460
6461 Otherwise, the output is simply the error messages, if any. No object file or
6462 ALI file is generated by a syntax-only compilation. Also, no units other
6463 than the one specified are accessed. For example, if a unit @code{X}
6464 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
6465 check only mode does not access the source file containing unit
6466 @code{Y}.
6467
6468 @cindex Multiple units, syntax checking
6469 Normally, GNAT allows only a single unit in a source file. However, this
6470 restriction does not apply in syntax-check-only mode, and it is possible
6471 to check a file containing multiple compilation units concatenated
6472 together. This is primarily used by the @code{gnatchop} utility
6473 (@pxref{Renaming Files Using gnatchop}).
6474 @end table
6475
6476 @node Using gcc for Semantic Checking
6477 @subsection Using @command{gcc} for Semantic Checking
6478 @table @option
6479 @item -gnatc
6480 @cindex @option{-gnatc} (@command{gcc})
6481
6482 @ifclear vms
6483 @noindent
6484 The @code{c} stands for ``check''.
6485 @end ifclear
6486 Causes the compiler to operate in semantic check mode,
6487 with full checking for all illegalities specified in the
6488 Ada Reference Manual, but without generation of any object code
6489 (no object file is generated).
6490
6491 Because dependent files must be accessed, you must follow the GNAT
6492 semantic restrictions on file structuring to operate in this mode:
6493
6494 @itemize @bullet
6495 @item
6496 The needed source files must be accessible
6497 (@pxref{Search Paths and the Run-Time Library (RTL)}).
6498
6499 @item
6500 Each file must contain only one compilation unit.
6501
6502 @item
6503 The file name and unit name must match (@pxref{File Naming Rules}).
6504 @end itemize
6505
6506 The output consists of error messages as appropriate. No object file is
6507 generated. An @file{ALI} file is generated for use in the context of
6508 cross-reference tools, but this file is marked as not being suitable
6509 for binding (since no object file is generated).
6510 The checking corresponds exactly to the notion of
6511 legality in the Ada Reference Manual.
6512
6513 Any unit can be compiled in semantics-checking-only mode, including
6514 units that would not normally be compiled (subunits,
6515 and specifications where a separate body is present).
6516 @end table
6517
6518 @node Compiling Different Versions of Ada
6519 @subsection Compiling Different Versions of Ada
6520
6521 @noindent
6522 The switches described in this section allow you to explicitly specify
6523 the version of the Ada language that your programs are written in.
6524 By default @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION},
6525 but you can also specify @value{NONDEFAULTLANGUAGEVERSION} or
6526 indicate Ada 83 compatibility mode.
6527
6528 @table @option
6529 @cindex Compatibility with Ada 83
6530
6531 @item -gnat83 (Ada 83 Compatibility Mode)
6532 @cindex @option{-gnat83} (@command{gcc})
6533 @cindex ACVC, Ada 83 tests
6534 @cindex Ada 83 mode
6535
6536 @noindent
6537 Although GNAT is primarily an Ada 95 / Ada 2005 compiler, this switch
6538 specifies that the program is to be compiled in Ada 83 mode. With
6539 @option{-gnat83}, GNAT rejects most post-Ada 83 extensions and applies Ada 83
6540 semantics where this can be done easily.
6541 It is not possible to guarantee this switch does a perfect
6542 job; some subtle tests, such as are
6543 found in earlier ACVC tests (and that have been removed from the ACATS suite
6544 for Ada 95), might not compile correctly.
6545 Nevertheless, this switch may be useful in some circumstances, for example
6546 where, due to contractual reasons, existing code needs to be maintained
6547 using only Ada 83 features.
6548
6549 With few exceptions (most notably the need to use @code{<>} on
6550 @cindex Generic formal parameters
6551 unconstrained generic formal parameters, the use of the new Ada 95 / Ada 2005
6552 reserved words, and the use of packages
6553 with optional bodies), it is not necessary to specify the
6554 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
6555 exceptions, Ada 95 and Ada 2005 are upwardly compatible with Ada 83. Thus
6556 a correct Ada 83 program is usually also a correct program
6557 in these later versions of the language standard.
6558 For further information, please refer to @ref{Compatibility and Porting Guide}.
6559
6560 @item -gnat95 (Ada 95 mode)
6561 @cindex @option{-gnat95} (@command{gcc})
6562 @cindex Ada 95 mode
6563
6564 @noindent
6565 This switch directs the compiler to implement the Ada 95 version of the
6566 language.
6567 Since Ada 95 is almost completely upwards
6568 compatible with Ada 83, Ada 83 programs may generally be compiled using
6569 this switch (see the description of the @option{-gnat83} switch for further
6570 information about Ada 83 mode).
6571 If an Ada 2005 program is compiled in Ada 95 mode,
6572 uses of the new Ada 2005 features will cause error
6573 messages or warnings.
6574
6575 This switch also can be used to cancel the effect of a previous
6576 @option{-gnat83} or @option{-gnat05} switch earlier in the command line.
6577
6578 @item -gnat05 (Ada 2005 mode)
6579 @cindex @option{-gnat05} (@command{gcc})
6580 @cindex Ada 2005 mode
6581
6582 @noindent
6583 This switch directs the compiler to implement the Ada 2005 version of the
6584 language.
6585 Since Ada 2005 is almost completely upwards
6586 compatible with Ada 95 (and thus also with Ada 83), Ada 83 and Ada 95 programs
6587 may generally be compiled using this switch (see the description of the
6588 @option{-gnat83} and @option{-gnat95} switches for further
6589 information).
6590
6591 For information about the approved ``Ada Issues'' that have been incorporated
6592 into Ada 2005, see @url{http://www.ada-auth.org/cgi-bin/cvsweb.cgi/AIs}.
6593 Included with GNAT releases is a file @file{features-ada0y} that describes
6594 the set of implemented Ada 2005 features.
6595 @end table
6596
6597
6598 @node Character Set Control
6599 @subsection Character Set Control
6600 @table @option
6601 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
6602 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
6603
6604 @noindent
6605 Normally GNAT recognizes the Latin-1 character set in source program
6606 identifiers, as described in the Ada Reference Manual.
6607 This switch causes
6608 GNAT to recognize alternate character sets in identifiers. @var{c} is a
6609 single character ^^or word^ indicating the character set, as follows:
6610
6611 @table @code
6612 @item 1
6613 ISO 8859-1 (Latin-1) identifiers
6614
6615 @item 2
6616 ISO 8859-2 (Latin-2) letters allowed in identifiers
6617
6618 @item 3
6619 ISO 8859-3 (Latin-3) letters allowed in identifiers
6620
6621 @item 4
6622 ISO 8859-4 (Latin-4) letters allowed in identifiers
6623
6624 @item 5
6625 ISO 8859-5 (Cyrillic) letters allowed in identifiers
6626
6627 @item 9
6628 ISO 8859-15 (Latin-9) letters allowed in identifiers
6629
6630 @item ^p^PC^
6631 IBM PC letters (code page 437) allowed in identifiers
6632
6633 @item ^8^PC850^
6634 IBM PC letters (code page 850) allowed in identifiers
6635
6636 @item ^f^FULL_UPPER^
6637 Full upper-half codes allowed in identifiers
6638
6639 @item ^n^NO_UPPER^
6640 No upper-half codes allowed in identifiers
6641
6642 @item ^w^WIDE^
6643 Wide-character codes (that is, codes greater than 255)
6644 allowed in identifiers
6645 @end table
6646
6647 @xref{Foreign Language Representation}, for full details on the
6648 implementation of these character sets.
6649
6650 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
6651 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
6652 Specify the method of encoding for wide characters.
6653 @var{e} is one of the following:
6654
6655 @table @code
6656
6657 @item ^h^HEX^
6658 Hex encoding (brackets coding also recognized)
6659
6660 @item ^u^UPPER^
6661 Upper half encoding (brackets encoding also recognized)
6662
6663 @item ^s^SHIFT_JIS^
6664 Shift/JIS encoding (brackets encoding also recognized)
6665
6666 @item ^e^EUC^
6667 EUC encoding (brackets encoding also recognized)
6668
6669 @item ^8^UTF8^
6670 UTF-8 encoding (brackets encoding also recognized)
6671
6672 @item ^b^BRACKETS^
6673 Brackets encoding only (default value)
6674 @end table
6675 For full details on these encoding
6676 methods see @ref{Wide Character Encodings}.
6677 Note that brackets coding is always accepted, even if one of the other
6678 options is specified, so for example @option{-gnatW8} specifies that both
6679 brackets and UTF-8 encodings will be recognized. The units that are
6680 with'ed directly or indirectly will be scanned using the specified
6681 representation scheme, and so if one of the non-brackets scheme is
6682 used, it must be used consistently throughout the program. However,
6683 since brackets encoding is always recognized, it may be conveniently
6684 used in standard libraries, allowing these libraries to be used with
6685 any of the available coding schemes.
6686 scheme.
6687
6688 If no @option{-gnatW?} parameter is present, then the default
6689 representation is normally Brackets encoding only. However, if the
6690 first three characters of the file are 16#EF# 16#BB# 16#BF# (the standard
6691 byte order mark or BOM for UTF-8), then these three characters are
6692 skipped and the default representation for the file is set to UTF-8.
6693
6694 Note that the wide character representation that is specified (explicitly
6695 or by default) for the main program also acts as the default encoding used
6696 for Wide_Text_IO files if not specifically overridden by a WCEM form
6697 parameter.
6698
6699 @end table
6700 @node File Naming Control
6701 @subsection File Naming Control
6702
6703 @table @option
6704 @item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n}
6705 @cindex @option{-gnatk} (@command{gcc})
6706 Activates file name ``krunching''. @var{n}, a decimal integer in the range
6707 1-999, indicates the maximum allowable length of a file name (not
6708 including the @file{.ads} or @file{.adb} extension). The default is not
6709 to enable file name krunching.
6710
6711 For the source file naming rules, @xref{File Naming Rules}.
6712 @end table
6713
6714 @node Subprogram Inlining Control
6715 @subsection Subprogram Inlining Control
6716
6717 @table @option
6718 @c !sort!
6719 @item -gnatn
6720 @cindex @option{-gnatn} (@command{gcc})
6721 @ifclear vms
6722 The @code{n} here is intended to suggest the first syllable of the
6723 word ``inline''.
6724 @end ifclear
6725 GNAT recognizes and processes @code{Inline} pragmas. However, for the
6726 inlining to actually occur, optimization must be enabled. To enable
6727 inlining of subprograms specified by pragma @code{Inline},
6728 you must also specify this switch.
6729 In the absence of this switch, GNAT does not attempt
6730 inlining and does not need to access the bodies of
6731 subprograms for which @code{pragma Inline} is specified if they are not
6732 in the current unit.
6733
6734 If you specify this switch the compiler will access these bodies,
6735 creating an extra source dependency for the resulting object file, and
6736 where possible, the call will be inlined.
6737 For further details on when inlining is possible
6738 see @ref{Inlining of Subprograms}.
6739
6740 @item -gnatN
6741 @cindex @option{-gnatN} (@command{gcc})
6742 This switch activates front-end inlining which also
6743 generates additional dependencies.
6744
6745 When using a gcc-based back end (in practice this means using any version
6746 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
6747 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
6748 Historically front end inlining was more extensive than the gcc back end
6749 inlining, but that is no longer the case.
6750 @end table
6751
6752 @node Auxiliary Output Control
6753 @subsection Auxiliary Output Control
6754
6755 @table @option
6756 @item -gnatt
6757 @cindex @option{-gnatt} (@command{gcc})
6758 @cindex Writing internal trees
6759 @cindex Internal trees, writing to file
6760 Causes GNAT to write the internal tree for a unit to a file (with the
6761 extension @file{.adt}.
6762 This not normally required, but is used by separate analysis tools.
6763 Typically
6764 these tools do the necessary compilations automatically, so you should
6765 not have to specify this switch in normal operation.
6766
6767 @item -gnatu
6768 @cindex @option{-gnatu} (@command{gcc})
6769 Print a list of units required by this compilation on @file{stdout}.
6770 The listing includes all units on which the unit being compiled depends
6771 either directly or indirectly.
6772
6773 @ifclear vms
6774 @item -pass-exit-codes
6775 @cindex @option{-pass-exit-codes} (@command{gcc})
6776 If this switch is not used, the exit code returned by @command{gcc} when
6777 compiling multiple files indicates whether all source files have
6778 been successfully used to generate object files or not.
6779
6780 When @option{-pass-exit-codes} is used, @command{gcc} exits with an extended
6781 exit status and allows an integrated development environment to better
6782 react to a compilation failure. Those exit status are:
6783
6784 @table @asis
6785 @item 5
6786 There was an error in at least one source file.
6787 @item 3
6788 At least one source file did not generate an object file.
6789 @item 2
6790 The compiler died unexpectedly (internal error for example).
6791 @item 0
6792 An object file has been generated for every source file.
6793 @end table
6794 @end ifclear
6795 @end table
6796
6797 @node Debugging Control
6798 @subsection Debugging Control
6799
6800 @table @option
6801 @c !sort!
6802 @cindex Debugging options
6803 @ifclear vms
6804 @item -gnatd@var{x}
6805 @cindex @option{-gnatd} (@command{gcc})
6806 Activate internal debugging switches. @var{x} is a letter or digit, or
6807 string of letters or digits, which specifies the type of debugging
6808 outputs desired. Normally these are used only for internal development
6809 or system debugging purposes. You can find full documentation for these
6810 switches in the body of the @code{Debug} unit in the compiler source
6811 file @file{debug.adb}.
6812 @end ifclear
6813
6814 @item -gnatG[=nn]
6815 @cindex @option{-gnatG} (@command{gcc})
6816 This switch causes the compiler to generate auxiliary output containing
6817 a pseudo-source listing of the generated expanded code. Like most Ada
6818 compilers, GNAT works by first transforming the high level Ada code into
6819 lower level constructs. For example, tasking operations are transformed
6820 into calls to the tasking run-time routines. A unique capability of GNAT
6821 is to list this expanded code in a form very close to normal Ada source.
6822 This is very useful in understanding the implications of various Ada
6823 usage on the efficiency of the generated code. There are many cases in
6824 Ada (e.g.@: the use of controlled types), where simple Ada statements can
6825 generate a lot of run-time code. By using @option{-gnatG} you can identify
6826 these cases, and consider whether it may be desirable to modify the coding
6827 approach to improve efficiency.
6828
6829 The optional parameter @code{nn} if present after -gnatG specifies an
6830 alternative maximum line length that overrides the normal default of 72.
6831 This value is in the range 40-999999, values less than 40 being silently
6832 reset to 40. The equal sign is optional.
6833
6834 The format of the output is very similar to standard Ada source, and is
6835 easily understood by an Ada programmer. The following special syntactic
6836 additions correspond to low level features used in the generated code that
6837 do not have any exact analogies in pure Ada source form. The following
6838 is a partial list of these special constructions. See the spec
6839 of package @code{Sprint} in file @file{sprint.ads} for a full list.
6840
6841 If the switch @option{-gnatL} is used in conjunction with
6842 @cindex @option{-gnatL} (@command{gcc})
6843 @option{-gnatG}, then the original source lines are interspersed
6844 in the expanded source (as comment lines with the original line number).
6845
6846 @table @code
6847 @item new @var{xxx} @r{[}storage_pool = @var{yyy}@r{]}
6848 Shows the storage pool being used for an allocator.
6849
6850 @item at end @var{procedure-name};
6851 Shows the finalization (cleanup) procedure for a scope.
6852
6853 @item (if @var{expr} then @var{expr} else @var{expr})
6854 Conditional expression equivalent to the @code{x?y:z} construction in C.
6855
6856 @item @var{target}^^^(@var{source})
6857 A conversion with floating-point truncation instead of rounding.
6858
6859 @item @var{target}?(@var{source})
6860 A conversion that bypasses normal Ada semantic checking. In particular
6861 enumeration types and fixed-point types are treated simply as integers.
6862
6863 @item @var{target}?^^^(@var{source})
6864 Combines the above two cases.
6865
6866 @item @var{x} #/ @var{y}
6867 @itemx @var{x} #mod @var{y}
6868 @itemx @var{x} #* @var{y}
6869 @itemx @var{x} #rem @var{y}
6870 A division or multiplication of fixed-point values which are treated as
6871 integers without any kind of scaling.
6872
6873 @item free @var{expr} @r{[}storage_pool = @var{xxx}@r{]}
6874 Shows the storage pool associated with a @code{free} statement.
6875
6876 @item [subtype or type declaration]
6877 Used to list an equivalent declaration for an internally generated
6878 type that is referenced elsewhere in the listing.
6879
6880 @item freeze @var{type-name} @ovar{actions}
6881 Shows the point at which @var{type-name} is frozen, with possible
6882 associated actions to be performed at the freeze point.
6883
6884 @item reference @var{itype}
6885 Reference (and hence definition) to internal type @var{itype}.
6886
6887 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
6888 Intrinsic function call.
6889
6890 @item @var{label-name} : label
6891 Declaration of label @var{labelname}.
6892
6893 @item #$ @var{subprogram-name}
6894 An implicit call to a run-time support routine
6895 (to meet the requirement of H.3.1(9) in a
6896 convenient manner).
6897
6898 @item @var{expr} && @var{expr} && @var{expr} @dots{} && @var{expr}
6899 A multiple concatenation (same effect as @var{expr} & @var{expr} &
6900 @var{expr}, but handled more efficiently).
6901
6902 @item [constraint_error]
6903 Raise the @code{Constraint_Error} exception.
6904
6905 @item @var{expression}'reference
6906 A pointer to the result of evaluating @var{expression}.
6907
6908 @item @var{target-type}!(@var{source-expression})
6909 An unchecked conversion of @var{source-expression} to @var{target-type}.
6910
6911 @item [@var{numerator}/@var{denominator}]
6912 Used to represent internal real literals (that) have no exact
6913 representation in base 2-16 (for example, the result of compile time
6914 evaluation of the expression 1.0/27.0).
6915 @end table
6916
6917 @item -gnatD[=nn]
6918 @cindex @option{-gnatD} (@command{gcc})
6919 When used in conjunction with @option{-gnatG}, this switch causes
6920 the expanded source, as described above for
6921 @option{-gnatG} to be written to files with names
6922 @file{^xxx.dg^XXX_DG^}, where @file{xxx} is the normal file name,
6923 instead of to the standard output file. For
6924 example, if the source file name is @file{hello.adb}, then a file
6925 @file{^hello.adb.dg^HELLO.ADB_DG^} will be written.  The debugging
6926 information generated by the @command{gcc} @option{^-g^/DEBUG^} switch
6927 will refer to the generated @file{^xxx.dg^XXX_DG^} file. This allows
6928 you to do source level debugging using the generated code which is
6929 sometimes useful for complex code, for example to find out exactly
6930 which part of a complex construction raised an exception. This switch
6931 also suppress generation of cross-reference information (see
6932 @option{-gnatx}) since otherwise the cross-reference information
6933 would refer to the @file{^.dg^.DG^} file, which would cause
6934 confusion since this is not the original source file.
6935
6936 Note that @option{-gnatD} actually implies @option{-gnatG}
6937 automatically, so it is not necessary to give both options.
6938 In other words @option{-gnatD} is equivalent to @option{-gnatDG}).
6939
6940 If the switch @option{-gnatL} is used in conjunction with
6941 @cindex @option{-gnatL} (@command{gcc})
6942 @option{-gnatDG}, then the original source lines are interspersed
6943 in the expanded source (as comment lines with the original line number).
6944
6945 The optional parameter @code{nn} if present after -gnatD specifies an
6946 alternative maximum line length that overrides the normal default of 72.
6947 This value is in the range 40-999999, values less than 40 being silently
6948 reset to 40. The equal sign is optional.
6949
6950 @item -gnatr
6951 @cindex @option{-gnatr} (@command{gcc})
6952 @cindex pragma Restrictions
6953 This switch causes pragma Restrictions to be treated as Restriction_Warnings
6954 so that violation of restrictions causes warnings rather than illegalities.
6955 This is useful during the development process when new restrictions are added
6956 or investigated. The switch also causes pragma Profile to be treated as
6957 Profile_Warnings, and pragma Restricted_Run_Time and pragma Ravenscar set
6958 restriction warnings rather than restrictions.
6959
6960 @ifclear vms
6961 @item -gnatR@r{[}0@r{|}1@r{|}2@r{|}3@r{[}s@r{]]}
6962 @cindex @option{-gnatR} (@command{gcc})
6963 This switch controls output from the compiler of a listing showing
6964 representation information for declared types and objects. For
6965 @option{-gnatR0}, no information is output (equivalent to omitting
6966 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
6967 so @option{-gnatR} with no parameter has the same effect), size and alignment
6968 information is listed for declared array and record types. For
6969 @option{-gnatR2}, size and alignment information is listed for all
6970 declared types and objects. Finally @option{-gnatR3} includes symbolic
6971 expressions for values that are computed at run time for
6972 variant records. These symbolic expressions have a mostly obvious
6973 format with #n being used to represent the value of the n'th
6974 discriminant. See source files @file{repinfo.ads/adb} in the
6975 @code{GNAT} sources for full details on the format of @option{-gnatR3}
6976 output. If the switch is followed by an s (e.g.@: @option{-gnatR2s}), then
6977 the output is to a file with the name @file{^file.rep^file_REP^} where
6978 file is the name of the corresponding source file.
6979 @end ifclear
6980 @ifset vms
6981 @item /REPRESENTATION_INFO
6982 @cindex @option{/REPRESENTATION_INFO} (@command{gcc})
6983 This qualifier controls output from the compiler of a listing showing
6984 representation information for declared types and objects. For
6985 @option{/REPRESENTATION_INFO=NONE}, no information is output
6986 (equivalent to omitting the @option{/REPRESENTATION_INFO} qualifier).
6987 @option{/REPRESENTATION_INFO} without option is equivalent to
6988 @option{/REPRESENTATION_INFO=ARRAYS}.
6989 For @option{/REPRESENTATION_INFO=ARRAYS}, size and alignment
6990 information is listed for declared array and record types. For
6991 @option{/REPRESENTATION_INFO=OBJECTS}, size and alignment information
6992 is listed for all expression information for values that are computed
6993 at run time for variant records. These symbolic expressions have a mostly
6994 obvious format with #n being used to represent the value of the n'th
6995 discriminant. See source files @file{REPINFO.ADS/ADB} in the
6996 @code{GNAT} sources for full details on the format of
6997 @option{/REPRESENTATION_INFO=SYMBOLIC} output.
6998 If _FILE is added at the end of an option
6999 (e.g.@: @option{/REPRESENTATION_INFO=ARRAYS_FILE}),
7000 then the output is to a file with the name @file{file_REP} where
7001 file is the name of the corresponding source file.
7002 @end ifset
7003 Note that it is possible for record components to have zero size. In
7004 this case, the component clause uses an obvious extension of permitted
7005 Ada syntax, for example @code{at 0 range 0 .. -1}.
7006
7007 Representation information requires that code be generated (since it is the
7008 code generator that lays out complex data structures). If an attempt is made
7009 to output representation information when no code is generated, for example
7010 when a subunit is compiled on its own, then no information can be generated
7011 and the compiler outputs a message to this effect.
7012
7013 @item -gnatS
7014 @cindex @option{-gnatS} (@command{gcc})
7015 The use of the switch @option{-gnatS} for an
7016 Ada compilation will cause the compiler to output a
7017 representation of package Standard in a form very
7018 close to standard Ada. It is not quite possible to
7019 do this entirely in standard Ada (since new
7020 numeric base types cannot be created in standard
7021 Ada), but the output is easily
7022 readable to any Ada programmer, and is useful to
7023 determine the characteristics of target dependent
7024 types in package Standard.
7025
7026 @item -gnatx
7027 @cindex @option{-gnatx} (@command{gcc})
7028 Normally the compiler generates full cross-referencing information in
7029 the @file{ALI} file. This information is used by a number of tools,
7030 including @code{gnatfind} and @code{gnatxref}. The @option{-gnatx} switch
7031 suppresses this information. This saves some space and may slightly
7032 speed up compilation, but means that these tools cannot be used.
7033 @end table
7034
7035 @node Exception Handling Control
7036 @subsection Exception Handling Control
7037
7038 @noindent
7039 GNAT uses two methods for handling exceptions at run-time. The
7040 @code{setjmp/longjmp} method saves the context when entering
7041 a frame with an exception handler. Then when an exception is
7042 raised, the context can be restored immediately, without the
7043 need for tracing stack frames. This method provides very fast
7044 exception propagation, but introduces significant overhead for
7045 the use of exception handlers, even if no exception is raised.
7046
7047 The other approach is called ``zero cost'' exception handling.
7048 With this method, the compiler builds static tables to describe
7049 the exception ranges. No dynamic code is required when entering
7050 a frame containing an exception handler. When an exception is
7051 raised, the tables are used to control a back trace of the
7052 subprogram invocation stack to locate the required exception
7053 handler. This method has considerably poorer performance for
7054 the propagation of exceptions, but there is no overhead for
7055 exception handlers if no exception is raised. Note that in this
7056 mode and in the context of mixed Ada and C/C++ programming,
7057 to propagate an exception through a C/C++ code, the C/C++ code
7058 must be compiled with the @option{-funwind-tables} GCC's
7059 option.
7060
7061 The following switches may be used to control which of the
7062 two exception handling methods is used.
7063
7064 @table @option
7065 @c !sort!
7066
7067 @item --RTS=sjlj
7068 @cindex @option{--RTS=sjlj} (@command{gnatmake})
7069 This switch causes the setjmp/longjmp run-time (when available) to be used
7070 for exception handling. If the default
7071 mechanism for the target is zero cost exceptions, then
7072 this switch can be used to modify this default, and must be
7073 used for all units in the partition.
7074 This option is rarely used. One case in which it may be
7075 advantageous is if you have an application where exception
7076 raising is common and the overall performance of the
7077 application is improved by favoring exception propagation.
7078
7079 @item --RTS=zcx
7080 @cindex @option{--RTS=zcx} (@command{gnatmake})
7081 @cindex Zero Cost Exceptions
7082 This switch causes the zero cost approach to be used
7083 for exception handling. If this is the default mechanism for the
7084 target (see below), then this switch is unneeded. If the default
7085 mechanism for the target is setjmp/longjmp exceptions, then
7086 this switch can be used to modify this default, and must be
7087 used for all units in the partition.
7088 This option can only be used if the zero cost approach
7089 is available for the target in use, otherwise it will generate an error.
7090 @end table
7091
7092 @noindent
7093 The same option @option{--RTS} must be used both for @command{gcc}
7094 and @command{gnatbind}. Passing this option to @command{gnatmake}
7095 (@pxref{Switches for gnatmake}) will ensure the required consistency
7096 through the compilation and binding steps.
7097
7098 @node Units to Sources Mapping Files
7099 @subsection Units to Sources Mapping Files
7100
7101 @table @option
7102
7103 @item -gnatem^^=^@var{path}
7104 @cindex @option{-gnatem} (@command{gcc})
7105 A mapping file is a way to communicate to the compiler two mappings:
7106 from unit names to file names (without any directory information) and from
7107 file names to path names (with full directory information). These mappings
7108 are used by the compiler to short-circuit the path search.
7109
7110 The use of mapping files is not required for correct operation of the
7111 compiler, but mapping files can improve efficiency, particularly when
7112 sources are read over a slow network connection. In normal operation,
7113 you need not be concerned with the format or use of mapping files,
7114 and the @option{-gnatem} switch is not a switch that you would use
7115 explicitly. it is intended only for use by automatic tools such as
7116 @command{gnatmake} running under the project file facility. The
7117 description here of the format of mapping files is provided
7118 for completeness and for possible use by other tools.
7119
7120 A mapping file is a sequence of sets of three lines. In each set,
7121 the first line is the unit name, in lower case, with ``@code{%s}''
7122 appended for
7123 specs and ``@code{%b}'' appended for bodies; the second line is the
7124 file name; and the third line is the path name.
7125
7126 Example:
7127 @smallexample
7128    main%b
7129    main.2.ada
7130    /gnat/project1/sources/main.2.ada
7131 @end smallexample
7132
7133 When the switch @option{-gnatem} is specified, the compiler will create
7134 in memory the two mappings from the specified file. If there is any problem
7135 (nonexistent file, truncated file or duplicate entries), no mapping will
7136 be created.
7137
7138 Several @option{-gnatem} switches may be specified; however, only the last
7139 one on the command line will be taken into account.
7140
7141 When using a project file, @command{gnatmake} create a temporary mapping file
7142 and communicates it to the compiler using this switch.
7143
7144 @end table
7145
7146 @node Integrated Preprocessing
7147 @subsection Integrated Preprocessing
7148
7149 @noindent
7150 GNAT sources may be preprocessed immediately before compilation.
7151 In this case, the actual
7152 text of the source is not the text of the source file, but is derived from it
7153 through a process called preprocessing. Integrated preprocessing is specified
7154 through switches @option{-gnatep} and/or @option{-gnateD}. @option{-gnatep}
7155 indicates, through a text file, the preprocessing data to be used.
7156 @option{-gnateD} specifies or modifies the values of preprocessing symbol.
7157
7158 @noindent
7159 Note that when integrated preprocessing is used, the output from the
7160 preprocessor is not written to any external file. Instead it is passed
7161 internally to the compiler. If you need to preserve the result of
7162 preprocessing in a file, then you should use @command{gnatprep}
7163 to perform the desired preprocessing in stand-alone mode.
7164
7165 @noindent
7166 It is recommended that @command{gnatmake} switch ^-s^/SWITCH_CHECK^ should be
7167 used when Integrated Preprocessing is used. The reason is that preprocessing
7168 with another Preprocessing Data file without changing the sources will
7169 not trigger recompilation without this switch.
7170
7171 @noindent
7172 Note that @command{gnatmake} switch ^-m^/MINIMAL_RECOMPILATION^ will almost
7173 always trigger recompilation for sources that are preprocessed,
7174 because @command{gnatmake} cannot compute the checksum of the source after
7175 preprocessing.
7176
7177 @noindent
7178 The actual preprocessing function is described in details in section
7179 @ref{Preprocessing Using gnatprep}. This section only describes how integrated
7180 preprocessing is triggered and parameterized.
7181
7182 @table @code
7183
7184 @item -gnatep=@var{file}
7185 @cindex @option{-gnatep} (@command{gcc})
7186 This switch indicates to the compiler the file name (without directory
7187 information) of the preprocessor data file to use. The preprocessor data file
7188 should be found in the source directories.
7189
7190 @noindent
7191 A preprocessing data file is a text file with significant lines indicating
7192 how should be preprocessed either a specific source or all sources not
7193 mentioned in other lines. A significant line is a nonempty, non-comment line.
7194 Comments are similar to Ada comments.
7195
7196 @noindent
7197 Each significant line starts with either a literal string or the character '*'.
7198 A literal string is the file name (without directory information) of the source
7199 to preprocess. A character '*' indicates the preprocessing for all the sources
7200 that are not specified explicitly on other lines (order of the lines is not
7201 significant). It is an error to have two lines with the same file name or two
7202 lines starting with the character '*'.
7203
7204 @noindent
7205 After the file name or the character '*', another optional literal string
7206 indicating the file name of the definition file to be used for preprocessing
7207 (@pxref{Form of Definitions File}). The definition files are found by the
7208 compiler in one of the source directories. In some cases, when compiling
7209 a source in a directory other than the current directory, if the definition
7210 file is in the current directory, it may be necessary to add the current
7211 directory as a source directory through switch ^-I.^/SEARCH=[]^, otherwise
7212 the compiler would not find the definition file.
7213
7214 @noindent
7215 Then, optionally, ^switches^switches^ similar to those of @code{gnatprep} may
7216 be found. Those ^switches^switches^ are:
7217
7218 @table @code
7219
7220 @item -b
7221 Causes both preprocessor lines and the lines deleted by
7222 preprocessing to be replaced by blank lines, preserving the line number.
7223 This ^switch^switch^ is always implied; however, if specified after @option{-c}
7224 it cancels the effect of @option{-c}.
7225
7226 @item -c
7227 Causes both preprocessor lines and the lines deleted
7228 by preprocessing to be retained as comments marked
7229 with the special string ``@code{--! }''.
7230
7231 @item -Dsymbol=value
7232 Define or redefine a symbol, associated with value. A symbol is an Ada
7233 identifier, or an Ada reserved word, with the exception of @code{if},
7234 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7235 @code{value} is either a literal string, an Ada identifier or any Ada reserved
7236 word. A symbol declared with this ^switch^switch^ replaces a symbol with the
7237 same name defined in a definition file.
7238
7239 @item -s
7240 Causes a sorted list of symbol names and values to be
7241 listed on the standard output file.
7242
7243 @item -u
7244 Causes undefined symbols to be treated as having the value @code{FALSE}
7245 in the context
7246 of a preprocessor test. In the absence of this option, an undefined symbol in
7247 a @code{#if} or @code{#elsif} test will be treated as an error.
7248
7249 @end table
7250
7251 @noindent
7252 Examples of valid lines in a preprocessor data file:
7253
7254 @smallexample
7255   "toto.adb"  "prep.def" -u
7256   --  preprocess "toto.adb", using definition file "prep.def",
7257   --  undefined symbol are False.
7258
7259   * -c -DVERSION=V101
7260   --  preprocess all other sources without a definition file;
7261   --  suppressed lined are commented; symbol VERSION has the value V101.
7262
7263   "titi.adb" "prep2.def" -s
7264   --  preprocess "titi.adb", using definition file "prep2.def";
7265   --  list all symbols with their values.
7266 @end smallexample
7267
7268 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=value@r{]}
7269 @cindex @option{-gnateD} (@command{gcc})
7270 Define or redefine a preprocessing symbol, associated with value. If no value
7271 is given on the command line, then the value of the symbol is @code{True}.
7272 A symbol is an identifier, following normal Ada (case-insensitive)
7273 rules for its syntax, and value is any sequence (including an empty sequence)
7274 of characters from the set (letters, digits, period, underline).
7275 Ada reserved words may be used as symbols, with the exceptions of @code{if},
7276 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7277
7278 @noindent
7279 A symbol declared with this ^switch^switch^ on the command line replaces a
7280 symbol with the same name either in a definition file or specified with a
7281 ^switch^switch^ -D in the preprocessor data file.
7282
7283 @noindent
7284 This switch is similar to switch @option{^-D^/ASSOCIATE^} of @code{gnatprep}.
7285
7286 @item -gnateG
7287 When integrated preprocessing is performed and the preprocessor modifies
7288 the source text, write the result of this preprocessing into a file
7289 <source>^.prep^_prep^.
7290
7291 @end table
7292
7293 @node Code Generation Control
7294 @subsection Code Generation Control
7295
7296 @noindent
7297
7298 The GCC technology provides a wide range of target dependent
7299 @option{-m} switches for controlling
7300 details of code generation with respect to different versions of
7301 architectures. This includes variations in instruction sets (e.g.@:
7302 different members of the power pc family), and different requirements
7303 for optimal arrangement of instructions (e.g.@: different members of
7304 the x86 family). The list of available @option{-m} switches may be
7305 found in the GCC documentation.
7306
7307 Use of these @option{-m} switches may in some cases result in improved
7308 code performance.
7309
7310 The GNAT Pro technology is tested and qualified without any
7311 @option{-m} switches,
7312 so generally the most reliable approach is to avoid the use of these
7313 switches. However, we generally expect most of these switches to work
7314 successfully with GNAT Pro, and many customers have reported successful
7315 use of these options.
7316
7317 Our general advice is to avoid the use of @option{-m} switches unless
7318 special needs lead to requirements in this area. In particular,
7319 there is no point in using @option{-m} switches to improve performance
7320 unless you actually see a performance improvement.
7321
7322 @ifset vms
7323 @node Return Codes
7324 @subsection Return Codes
7325 @cindex Return Codes
7326 @cindex @option{/RETURN_CODES=VMS}
7327
7328 @noindent
7329 On VMS, GNAT compiled programs return POSIX-style codes by default,
7330 e.g.@: @option{/RETURN_CODES=POSIX}.
7331
7332 To enable VMS style return codes, use GNAT BIND and LINK with the option
7333 @option{/RETURN_CODES=VMS}. For example:
7334
7335 @smallexample
7336 GNAT BIND MYMAIN.ALI /RETURN_CODES=VMS
7337 GNAT LINK MYMAIN.ALI /RETURN_CODES=VMS
7338 @end smallexample
7339
7340 @noindent
7341 Programs built with /RETURN_CODES=VMS are suitable to be called in
7342 VMS DCL scripts. Programs compiled with the default /RETURN_CODES=POSIX
7343 are suitable for spawning with appropriate GNAT RTL routines.
7344
7345 @end ifset
7346
7347 @node Search Paths and the Run-Time Library (RTL)
7348 @section Search Paths and the Run-Time Library (RTL)
7349
7350 @noindent
7351 With the GNAT source-based library system, the compiler must be able to
7352 find source files for units that are needed by the unit being compiled.
7353 Search paths are used to guide this process.
7354
7355 The compiler compiles one source file whose name must be given
7356 explicitly on the command line. In other words, no searching is done
7357 for this file. To find all other source files that are needed (the most
7358 common being the specs of units), the compiler examines the following
7359 directories, in the following order:
7360
7361 @enumerate
7362 @item
7363 The directory containing the source file of the main unit being compiled
7364 (the file name on the command line).
7365
7366 @item
7367 Each directory named by an @option{^-I^/SOURCE_SEARCH^} switch given on the
7368 @command{gcc} command line, in the order given.
7369
7370 @item
7371 @findex ADA_PRJ_INCLUDE_FILE
7372 Each of the directories listed in the text file whose name is given
7373 by the @env{ADA_PRJ_INCLUDE_FILE} ^environment variable^logical name^.
7374
7375 @noindent
7376 @env{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
7377 driver when project files are used. It should not normally be set
7378 by other means.
7379
7380 @item
7381 @findex ADA_INCLUDE_PATH
7382 Each of the directories listed in the value of the
7383 @env{ADA_INCLUDE_PATH} ^environment variable^logical name^.
7384 @ifclear vms
7385 Construct this value
7386 exactly as the @env{PATH} environment variable: a list of directory
7387 names separated by colons (semicolons when working with the NT version).
7388 @end ifclear
7389 @ifset vms
7390 Normally, define this value as a logical name containing a comma separated
7391 list of directory names.
7392
7393 This variable can also be defined by means of an environment string
7394 (an argument to the HP C exec* set of functions).
7395
7396 Logical Name:
7397 @smallexample
7398 DEFINE ANOTHER_PATH FOO:[BAG]
7399 DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
7400 @end smallexample
7401
7402 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
7403 first, followed by the standard Ada
7404 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADAINCLUDE].
7405 If this is not redefined, the user will obtain the HP Ada 83 IO packages
7406 (Text_IO, Sequential_IO, etc)
7407 instead of the standard Ada packages. Thus, in order to get the standard Ada
7408 packages by default, ADA_INCLUDE_PATH must be redefined.
7409 @end ifset
7410
7411 @item
7412 The content of the @file{ada_source_path} file which is part of the GNAT
7413 installation tree and is used to store standard libraries such as the
7414 GNAT Run Time Library (RTL) source files.
7415 @ifclear vms
7416 @ref{Installing a library}
7417 @end ifclear
7418 @end enumerate
7419
7420 @noindent
7421 Specifying the switch @option{^-I-^/NOCURRENT_DIRECTORY^}
7422 inhibits the use of the directory
7423 containing the source file named in the command line. You can still
7424 have this directory on your search path, but in this case it must be
7425 explicitly requested with a @option{^-I^/SOURCE_SEARCH^} switch.
7426
7427 Specifying the switch @option{-nostdinc}
7428 inhibits the search of the default location for the GNAT Run Time
7429 Library (RTL) source files.
7430
7431 The compiler outputs its object files and ALI files in the current
7432 working directory.
7433 @ifclear vms
7434 Caution: The object file can be redirected with the @option{-o} switch;
7435 however, @command{gcc} and @code{gnat1} have not been coordinated on this
7436 so the @file{ALI} file will not go to the right place. Therefore, you should
7437 avoid using the @option{-o} switch.
7438 @end ifclear
7439
7440 @findex System.IO
7441 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
7442 children make up the GNAT RTL, together with the simple @code{System.IO}
7443 package used in the @code{"Hello World"} example. The sources for these units
7444 are needed by the compiler and are kept together in one directory. Not
7445 all of the bodies are needed, but all of the sources are kept together
7446 anyway. In a normal installation, you need not specify these directory
7447 names when compiling or binding. Either the environment variables or
7448 the built-in defaults cause these files to be found.
7449
7450 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
7451 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
7452 consisting of child units of @code{GNAT}. This is a collection of generally
7453 useful types, subprograms, etc. @xref{Top, GNAT Reference Manual, About
7454 This Guid, gnat_rm, GNAT Reference Manual}, for further details.
7455
7456 Besides simplifying access to the RTL, a major use of search paths is
7457 in compiling sources from multiple directories. This can make
7458 development environments much more flexible.
7459
7460 @node Order of Compilation Issues
7461 @section Order of Compilation Issues
7462
7463 @noindent
7464 If, in our earlier example, there was a spec for the @code{hello}
7465 procedure, it would be contained in the file @file{hello.ads}; yet this
7466 file would not have to be explicitly compiled. This is the result of the
7467 model we chose to implement library management. Some of the consequences
7468 of this model are as follows:
7469
7470 @itemize @bullet
7471 @item
7472 There is no point in compiling specs (except for package
7473 specs with no bodies) because these are compiled as needed by clients. If
7474 you attempt a useless compilation, you will receive an error message.
7475 It is also useless to compile subunits because they are compiled as needed
7476 by the parent.
7477
7478 @item
7479 There are no order of compilation requirements: performing a
7480 compilation never obsoletes anything. The only way you can obsolete
7481 something and require recompilations is to modify one of the
7482 source files on which it depends.
7483
7484 @item
7485 There is no library as such, apart from the ALI files
7486 (@pxref{The Ada Library Information Files}, for information on the format
7487 of these files). For now we find it convenient to create separate ALI files,
7488 but eventually the information therein may be incorporated into the object
7489 file directly.
7490
7491 @item
7492 When you compile a unit, the source files for the specs of all units
7493 that it @code{with}'s, all its subunits, and the bodies of any generics it
7494 instantiates must be available (reachable by the search-paths mechanism
7495 described above), or you will receive a fatal error message.
7496 @end itemize
7497
7498 @node Examples
7499 @section Examples
7500
7501 @noindent
7502 The following are some typical Ada compilation command line examples:
7503
7504 @table @code
7505 @item $ gcc -c xyz.adb
7506 Compile body in file @file{xyz.adb} with all default options.
7507
7508 @ifclear vms
7509 @item $ gcc -c -O2 -gnata xyz-def.adb
7510 @end ifclear
7511 @ifset vms
7512 @item $ GNAT COMPILE /OPTIMIZE=ALL -gnata xyz-def.adb
7513 @end ifset
7514
7515 Compile the child unit package in file @file{xyz-def.adb} with extensive
7516 optimizations, and pragma @code{Assert}/@code{Debug} statements
7517 enabled.
7518
7519 @item $ gcc -c -gnatc abc-def.adb
7520 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
7521 mode.
7522 @end table
7523
7524 @node Binding Using gnatbind
7525 @chapter Binding Using @code{gnatbind}
7526 @findex gnatbind
7527
7528 @menu
7529 * Running gnatbind::
7530 * Switches for gnatbind::
7531 * Command-Line Access::
7532 * Search Paths for gnatbind::
7533 * Examples of gnatbind Usage::
7534 @end menu
7535
7536 @noindent
7537 This chapter describes the GNAT binder, @code{gnatbind}, which is used
7538 to bind compiled GNAT objects.
7539
7540 Note: to invoke @code{gnatbind} with a project file, use the @code{gnat}
7541 driver (see @ref{The GNAT Driver and Project Files}).
7542
7543 The @code{gnatbind} program performs four separate functions:
7544
7545 @enumerate
7546 @item
7547 Checks that a program is consistent, in accordance with the rules in
7548 Chapter 10 of the Ada Reference Manual. In particular, error
7549 messages are generated if a program uses inconsistent versions of a
7550 given unit.
7551
7552 @item
7553 Checks that an acceptable order of elaboration exists for the program
7554 and issues an error message if it cannot find an order of elaboration
7555 that satisfies the rules in Chapter 10 of the Ada Language Manual.
7556
7557 @item
7558 Generates a main program incorporating the given elaboration order.
7559 This program is a small Ada package (body and spec) that
7560 must be subsequently compiled
7561 using the GNAT compiler. The necessary compilation step is usually
7562 performed automatically by @command{gnatlink}. The two most important
7563 functions of this program
7564 are to call the elaboration routines of units in an appropriate order
7565 and to call the main program.
7566
7567 @item
7568 Determines the set of object files required by the given main program.
7569 This information is output in the forms of comments in the generated program,
7570 to be read by the @command{gnatlink} utility used to link the Ada application.
7571 @end enumerate
7572
7573 @node Running gnatbind
7574 @section Running @code{gnatbind}
7575
7576 @noindent
7577 The form of the @code{gnatbind} command is
7578
7579 @smallexample
7580 $ gnatbind @ovar{switches} @var{mainprog}@r{[}.ali@r{]} @ovar{switches}
7581 @end smallexample
7582
7583 @noindent
7584 where @file{@var{mainprog}.adb} is the Ada file containing the main program
7585 unit body. If no switches are specified, @code{gnatbind} constructs an Ada
7586 package in two files whose names are
7587 @file{b~@var{mainprog}.ads}, and @file{b~@var{mainprog}.adb}.
7588 For example, if given the
7589 parameter @file{hello.ali}, for a main program contained in file
7590 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
7591 and @file{b~hello.adb}.
7592
7593 When doing consistency checking, the binder takes into consideration
7594 any source files it can locate. For example, if the binder determines
7595 that the given main program requires the package @code{Pack}, whose
7596 @file{.ALI}
7597 file is @file{pack.ali} and whose corresponding source spec file is
7598 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
7599 (using the same search path conventions as previously described for the
7600 @command{gcc} command). If it can locate this source file, it checks that
7601 the time stamps
7602 or source checksums of the source and its references to in @file{ALI} files
7603 match. In other words, any @file{ALI} files that mentions this spec must have
7604 resulted from compiling this version of the source file (or in the case
7605 where the source checksums match, a version close enough that the
7606 difference does not matter).
7607
7608 @cindex Source files, use by binder
7609 The effect of this consistency checking, which includes source files, is
7610 that the binder ensures that the program is consistent with the latest
7611 version of the source files that can be located at bind time. Editing a
7612 source file without compiling files that depend on the source file cause
7613 error messages to be generated by the binder.
7614
7615 For example, suppose you have a main program @file{hello.adb} and a
7616 package @code{P}, from file @file{p.ads} and you perform the following
7617 steps:
7618
7619 @enumerate
7620 @item
7621 Enter @code{gcc -c hello.adb} to compile the main program.
7622
7623 @item
7624 Enter @code{gcc -c p.ads} to compile package @code{P}.
7625
7626 @item
7627 Edit file @file{p.ads}.
7628
7629 @item
7630 Enter @code{gnatbind hello}.
7631 @end enumerate
7632
7633 @noindent
7634 At this point, the file @file{p.ali} contains an out-of-date time stamp
7635 because the file @file{p.ads} has been edited. The attempt at binding
7636 fails, and the binder generates the following error messages:
7637
7638 @smallexample
7639 error: "hello.adb" must be recompiled ("p.ads" has been modified)
7640 error: "p.ads" has been modified and must be recompiled
7641 @end smallexample
7642
7643 @noindent
7644 Now both files must be recompiled as indicated, and then the bind can
7645 succeed, generating a main program. You need not normally be concerned
7646 with the contents of this file, but for reference purposes a sample
7647 binder output file is given in @ref{Example of Binder Output File}.
7648
7649 In most normal usage, the default mode of @command{gnatbind} which is to
7650 generate the main package in Ada, as described in the previous section.
7651 In particular, this means that any Ada programmer can read and understand
7652 the generated main program. It can also be debugged just like any other
7653 Ada code provided the @option{^-g^/DEBUG^} switch is used for
7654 @command{gnatbind} and @command{gnatlink}.
7655
7656 However for some purposes it may be convenient to generate the main
7657 program in C rather than Ada. This may for example be helpful when you
7658 are generating a mixed language program with the main program in C. The
7659 GNAT compiler itself is an example.
7660 The use of the @option{^-C^/BIND_FILE=C^} switch
7661 for both @code{gnatbind} and @command{gnatlink} will cause the program to
7662 be generated in C (and compiled using the gnu C compiler).
7663
7664 @node Switches for gnatbind
7665 @section Switches for @command{gnatbind}
7666
7667 @noindent
7668 The following switches are available with @code{gnatbind}; details will
7669 be presented in subsequent sections.
7670
7671 @menu
7672 * Consistency-Checking Modes::
7673 * Binder Error Message Control::
7674 * Elaboration Control::
7675 * Output Control::
7676 * Binding with Non-Ada Main Programs::
7677 * Binding Programs with No Main Subprogram::
7678 @end menu
7679
7680 @table @option
7681 @c !sort!
7682
7683 @item --version
7684 @cindex @option{--version} @command{gnatbind}
7685 Display Copyright and version, then exit disregarding all other options.
7686
7687 @item --help
7688 @cindex @option{--help} @command{gnatbind}
7689 If @option{--version} was not used, display usage, then exit disregarding
7690 all other options.
7691
7692 @item -a
7693 @cindex @option{-a} @command{gnatbind}
7694 Indicates that, if supported by the platform, the adainit procedure should
7695 be treated as an initialisation routine by the linker (a constructor). This
7696 is intended to be used by the Project Manager to automatically initialize
7697 shared Stand-Alone Libraries.
7698
7699 @item ^-aO^/OBJECT_SEARCH^
7700 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatbind})
7701 Specify directory to be searched for ALI files.
7702
7703 @item ^-aI^/SOURCE_SEARCH^
7704 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
7705 Specify directory to be searched for source file.
7706
7707 @item ^-A^/BIND_FILE=ADA^
7708 @cindex @option{^-A^/BIND_FILE=ADA^} (@command{gnatbind})
7709 Generate binder program in Ada (default)
7710
7711 @item ^-b^/REPORT_ERRORS=BRIEF^
7712 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@command{gnatbind})
7713 Generate brief messages to @file{stderr} even if verbose mode set.
7714
7715 @item ^-c^/NOOUTPUT^
7716 @cindex @option{^-c^/NOOUTPUT^} (@command{gnatbind})
7717 Check only, no generation of binder output file.
7718
7719 @item ^-C^/BIND_FILE=C^
7720 @cindex @option{^-C^/BIND_FILE=C^} (@command{gnatbind})
7721 Generate binder program in C
7722
7723 @item ^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
7724 @cindex @option{^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}} (@command{gnatbind})
7725 This switch can be used to change the default task stack size value
7726 to a specified size @var{nn}, which is expressed in bytes by default, or
7727 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
7728 with @var{m}.
7729 In the absence of a @samp{@r{[}k@r{|}m@r{]}} suffix, this switch is equivalent,
7730 in effect, to completing all task specs with
7731 @smallexample @c ada
7732    pragma Storage_Size (nn);
7733 @end smallexample
7734 When they do not already have such a pragma.
7735
7736 @item ^-D^/DEFAULT_SECONDARY_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
7737 @cindex @option{^-D^/DEFAULT_SECONDARY_STACK_SIZE=nnnnn^} (@command{gnatbind})
7738 This switch can be used to change the default secondary stack size value
7739 to a specified size @var{nn}, which is expressed in bytes by default, or
7740 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
7741 with @var{m}.
7742
7743 The secondary stack is used to deal with functions that return a variable
7744 sized result, for example a function returning an unconstrained
7745 String. There are two ways in which this secondary stack is allocated.
7746
7747 For most targets, the secondary stack is growing on demand and is allocated
7748 as a chain of blocks in the heap. The -D option is not very
7749 relevant. It only give some control over the size of the allocated
7750 blocks (whose size is the minimum of the default secondary stack size value,
7751 and the actual size needed for the current allocation request).
7752
7753 For certain targets, notably VxWorks 653,
7754 the secondary stack is allocated by carving off a fixed ratio chunk of the
7755 primary task stack. The -D option is used to define the
7756 size of the environment task's secondary stack.
7757
7758 @item ^-e^/ELABORATION_DEPENDENCIES^
7759 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@command{gnatbind})
7760 Output complete list of elaboration-order dependencies.
7761
7762 @item ^-E^/STORE_TRACEBACKS^
7763 @cindex @option{^-E^/STORE_TRACEBACKS^} (@command{gnatbind})
7764 Store tracebacks in exception occurrences when the target supports it.
7765 This is the default with the zero cost exception mechanism.
7766 @ignore
7767 @c The following may get moved to an appendix
7768 This option is currently supported on the following targets:
7769 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
7770 @end ignore
7771 See also the packages @code{GNAT.Traceback} and
7772 @code{GNAT.Traceback.Symbolic} for more information.
7773 @ifclear vms
7774 Note that on x86 ports, you must not use @option{-fomit-frame-pointer}
7775 @command{gcc} option.
7776 @end ifclear
7777
7778 @item ^-F^/FORCE_ELABS_FLAGS^
7779 @cindex @option{^-F^/FORCE_ELABS_FLAGS^} (@command{gnatbind})
7780 Force the checks of elaboration flags. @command{gnatbind} does not normally
7781 generate checks of elaboration flags for the main executable, except when
7782 a Stand-Alone Library is used. However, there are cases when this cannot be
7783 detected by gnatbind. An example is importing an interface of a Stand-Alone
7784 Library through a pragma Import and only specifying through a linker switch
7785 this Stand-Alone Library. This switch is used to guarantee that elaboration
7786 flag checks are generated.
7787
7788 @item ^-h^/HELP^
7789 @cindex @option{^-h^/HELP^} (@command{gnatbind})
7790 Output usage (help) information
7791
7792 @item ^-I^/SEARCH^
7793 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
7794 Specify directory to be searched for source and ALI files.
7795
7796 @item ^-I-^/NOCURRENT_DIRECTORY^
7797 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatbind})
7798 Do not look for sources in the current directory where @code{gnatbind} was
7799 invoked, and do not look for ALI files in the directory containing the
7800 ALI file named in the @code{gnatbind} command line.
7801
7802 @item ^-l^/ORDER_OF_ELABORATION^
7803 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@command{gnatbind})
7804 Output chosen elaboration order.
7805
7806 @item ^-L@var{xxx}^/BUILD_LIBRARY=@var{xxx}^
7807 @cindex @option{^-L^/BUILD_LIBRARY^} (@command{gnatbind})
7808 Bind the units for library building. In this case the adainit and
7809 adafinal procedures (@pxref{Binding with Non-Ada Main Programs})
7810 are renamed to ^@var{xxx}init^@var{XXX}INIT^ and
7811 ^@var{xxx}final^@var{XXX}FINAL^.
7812 Implies ^-n^/NOCOMPILE^.
7813 @ifclear vms
7814 (@xref{GNAT and Libraries}, for more details.)
7815 @end ifclear
7816 @ifset vms
7817 On OpenVMS, these init and final procedures are exported in uppercase
7818 letters. For example if /BUILD_LIBRARY=toto is used, the exported name of
7819 the init procedure will be "TOTOINIT" and the exported name of the final
7820 procedure will be "TOTOFINAL".
7821 @end ifset
7822
7823 @item ^-Mxyz^/RENAME_MAIN=xyz^
7824 @cindex @option{^-M^/RENAME_MAIN^} (@command{gnatbind})
7825 Rename generated main program from main to xyz. This option is
7826 supported on cross environments only.
7827
7828 @item ^-m^/ERROR_LIMIT=^@var{n}
7829 @cindex @option{^-m^/ERROR_LIMIT^} (@command{gnatbind})
7830 Limit number of detected errors or warnings to @var{n}, where @var{n} is
7831 in the range 1..999999. The default value if no switch is
7832 given is 9999. If the number of warnings reaches this limit, then a
7833 message is output and further warnings are suppressed, the bind
7834 continues in this case. If the number of errors reaches this
7835 limit, then a message is output and the bind is abandoned.
7836 A value of zero means that no limit is enforced. The equal
7837 sign is optional.
7838
7839 @ifset unw
7840 Furthermore, under Windows, the sources pointed to by the libraries path
7841 set in the registry are not searched for.
7842 @end ifset
7843
7844 @item ^-n^/NOMAIN^
7845 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
7846 No main program.
7847
7848 @item -nostdinc
7849 @cindex @option{-nostdinc} (@command{gnatbind})
7850 Do not look for sources in the system default directory.
7851
7852 @item -nostdlib
7853 @cindex @option{-nostdlib} (@command{gnatbind})
7854 Do not look for library files in the system default directory.
7855
7856 @item --RTS=@var{rts-path}
7857 @cindex @option{--RTS} (@code{gnatbind})
7858 Specifies the default location of the runtime library. Same meaning as the
7859 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
7860
7861 @item ^-o ^/OUTPUT=^@var{file}
7862 @cindex @option{^-o ^/OUTPUT^} (@command{gnatbind})
7863 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
7864 Note that if this option is used, then linking must be done manually,
7865 gnatlink cannot be used.
7866
7867 @item ^-O^/OBJECT_LIST^
7868 @cindex @option{^-O^/OBJECT_LIST^} (@command{gnatbind})
7869 Output object list.
7870
7871 @item ^-p^/PESSIMISTIC_ELABORATION^
7872 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@command{gnatbind})
7873 Pessimistic (worst-case) elaboration order
7874
7875 @item ^-R^-R^
7876 @cindex @option{^-R^-R^} (@command{gnatbind})
7877 Output closure source list.
7878
7879 @item ^-s^/READ_SOURCES=ALL^
7880 @cindex @option{^-s^/READ_SOURCES=ALL^} (@command{gnatbind})
7881 Require all source files to be present.
7882
7883 @item ^-S@var{xxx}^/INITIALIZE_SCALARS=@var{xxx}^
7884 @cindex @option{^-S^/INITIALIZE_SCALARS^} (@command{gnatbind})
7885 Specifies the value to be used when detecting uninitialized scalar
7886 objects with pragma Initialize_Scalars.
7887 The @var{xxx} ^string specified with the switch^option^ may be either
7888 @itemize @bullet
7889 @item ``@option{^in^INVALID^}'' requesting an invalid value where possible
7890 @item ``@option{^lo^LOW^}'' for the lowest possible value
7891 @item ``@option{^hi^HIGH^}'' for the highest possible value
7892 @item ``@option{@var{xx}}'' for a value consisting of repeated bytes with the
7893 value @code{16#@var{xx}#} (i.e., @var{xx} is a string of two hexadecimal digits).
7894 @end itemize
7895
7896 In addition, you can specify @option{-Sev} to indicate that the value is
7897 to be set at run time. In this case, the program will look for an environment
7898 @cindex GNAT_INIT_SCALARS
7899 variable of the form @env{GNAT_INIT_SCALARS=@var{xx}}, where @var{xx} is one
7900 of @option{in/lo/hi/@var{xx}} with the same meanings as above.
7901 If no environment variable is found, or if it does not have a valid value,
7902 then the default is @option{in} (invalid values).
7903
7904 @ifclear vms
7905 @item -static
7906 @cindex @option{-static} (@code{gnatbind})
7907 Link against a static GNAT run time.
7908
7909 @item -shared
7910 @cindex @option{-shared} (@code{gnatbind})
7911 Link against a shared GNAT run time when available.
7912 @end ifclear
7913
7914 @item ^-t^/NOTIME_STAMP_CHECK^
7915 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
7916 Tolerate time stamp and other consistency errors
7917
7918 @item ^-T@var{n}^/TIME_SLICE=@var{n}^
7919 @cindex @option{^-T^/TIME_SLICE^} (@code{gnatbind})
7920 Set the time slice value to @var{n} milliseconds. If the system supports
7921 the specification of a specific time slice value, then the indicated value
7922 is used. If the system does not support specific time slice values, but
7923 does support some general notion of round-robin scheduling, then any
7924 nonzero value will activate round-robin scheduling.
7925
7926 A value of zero is treated specially. It turns off time
7927 slicing, and in addition, indicates to the tasking run time that the
7928 semantics should match as closely as possible the Annex D
7929 requirements of the Ada RM, and in particular sets the default
7930 scheduling policy to @code{FIFO_Within_Priorities}.
7931
7932 @item ^-u@var{n}^/DYNAMIC_STACK_USAGE=@var{n}^
7933 @cindex @option{^-u^/DYNAMIC_STACK_USAGE^} (@code{gnatbind})
7934 Enable dynamic stack usage, with @var{n} results stored and displayed
7935 at program termination. A result is generated when a task
7936 terminates. Results that can't be stored are displayed on the fly, at
7937 task termination. This option is currently not supported on Itanium
7938 platforms. (See @ref{Dynamic Stack Usage Analysis} for details.)
7939
7940 @item ^-v^/REPORT_ERRORS=VERBOSE^
7941 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
7942 Verbose mode. Write error messages, header, summary output to
7943 @file{stdout}.
7944
7945 @ifclear vms
7946 @item -w@var{x}
7947 @cindex @option{-w} (@code{gnatbind})
7948 Warning mode (@var{x}=s/e for suppress/treat as error)
7949 @end ifclear
7950
7951 @ifset vms
7952 @item /WARNINGS=NORMAL
7953 @cindex @option{/WARNINGS} (@code{gnatbind})
7954 Normal warnings mode. Warnings are issued but ignored
7955
7956 @item /WARNINGS=SUPPRESS
7957 @cindex @option{/WARNINGS} (@code{gnatbind})
7958 All warning messages are suppressed
7959
7960 @item /WARNINGS=ERROR
7961 @cindex @option{/WARNINGS} (@code{gnatbind})
7962 Warning messages are treated as fatal errors
7963 @end ifset
7964
7965 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
7966 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
7967 Override default wide character encoding for standard Text_IO files.
7968
7969 @item ^-x^/READ_SOURCES=NONE^
7970 @cindex @option{^-x^/READ_SOURCES^} (@code{gnatbind})
7971 Exclude source files (check object consistency only).
7972
7973 @ifset vms
7974 @item /READ_SOURCES=AVAILABLE
7975 @cindex @option{/READ_SOURCES} (@code{gnatbind})
7976 Default mode, in which sources are checked for consistency only if
7977 they are available.
7978 @end ifset
7979
7980 @item ^-y^/ENABLE_LEAP_SECONDS^
7981 @cindex @option{^-y^/ENABLE_LEAP_SECONDS^} (@code{gnatbind})
7982 Enable leap seconds support in @code{Ada.Calendar} and its children.
7983
7984 @item ^-z^/ZERO_MAIN^
7985 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
7986 No main subprogram.
7987 @end table
7988
7989 @ifclear vms
7990 @noindent
7991 You may obtain this listing of switches by running @code{gnatbind} with
7992 no arguments.
7993 @end ifclear
7994
7995 @node Consistency-Checking Modes
7996 @subsection Consistency-Checking Modes
7997
7998 @noindent
7999 As described earlier, by default @code{gnatbind} checks
8000 that object files are consistent with one another and are consistent
8001 with any source files it can locate. The following switches control binder
8002 access to sources.
8003
8004 @table @option
8005 @c !sort!
8006 @item ^-s^/READ_SOURCES=ALL^
8007 @cindex @option{^-s^/READ_SOURCES=ALL^} (@code{gnatbind})
8008 Require source files to be present. In this mode, the binder must be
8009 able to locate all source files that are referenced, in order to check
8010 their consistency. In normal mode, if a source file cannot be located it
8011 is simply ignored. If you specify this switch, a missing source
8012 file is an error.
8013
8014 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8015 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8016 Override default wide character encoding for standard Text_IO files.
8017 Normally the default wide character encoding method used for standard
8018 [Wide_[Wide_]]Text_IO files is taken from the encoding specified for
8019 the main source input (see description of switch
8020 @option{^-gnatWx^/WIDE_CHARACTER_ENCODING^} for the compiler). The
8021 use of this switch for the binder (which has the same set of
8022 possible arguments) overrides this default as specified.
8023
8024 @item ^-x^/READ_SOURCES=NONE^
8025 @cindex @option{^-x^/READ_SOURCES=NONE^} (@code{gnatbind})
8026 Exclude source files. In this mode, the binder only checks that ALI
8027 files are consistent with one another. Source files are not accessed.
8028 The binder runs faster in this mode, and there is still a guarantee that
8029 the resulting program is self-consistent.
8030 If a source file has been edited since it was last compiled, and you
8031 specify this switch, the binder will not detect that the object
8032 file is out of date with respect to the source file. Note that this is the
8033 mode that is automatically used by @command{gnatmake} because in this
8034 case the checking against sources has already been performed by
8035 @command{gnatmake} in the course of compilation (i.e.@: before binding).
8036
8037 @ifset vms
8038 @item /READ_SOURCES=AVAILABLE
8039 @cindex @code{/READ_SOURCES=AVAILABLE} (@code{gnatbind})
8040 This is the default mode in which source files are checked if they are
8041 available, and ignored if they are not available.
8042 @end ifset
8043 @end table
8044
8045 @node Binder Error Message Control
8046 @subsection Binder Error Message Control
8047
8048 @noindent
8049 The following switches provide control over the generation of error
8050 messages from the binder:
8051
8052 @table @option
8053 @c !sort!
8054 @item ^-v^/REPORT_ERRORS=VERBOSE^
8055 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8056 Verbose mode. In the normal mode, brief error messages are generated to
8057 @file{stderr}. If this switch is present, a header is written
8058 to @file{stdout} and any error messages are directed to @file{stdout}.
8059 All that is written to @file{stderr} is a brief summary message.
8060
8061 @item ^-b^/REPORT_ERRORS=BRIEF^
8062 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@code{gnatbind})
8063 Generate brief error messages to @file{stderr} even if verbose mode is
8064 specified. This is relevant only when used with the
8065 @option{^-v^/REPORT_ERRORS=VERBOSE^} switch.
8066
8067 @ifclear vms
8068 @item -m@var{n}
8069 @cindex @option{-m} (@code{gnatbind})
8070 Limits the number of error messages to @var{n}, a decimal integer in the
8071 range 1-999. The binder terminates immediately if this limit is reached.
8072
8073 @item -M@var{xxx}
8074 @cindex @option{-M} (@code{gnatbind})
8075 Renames the generated main program from @code{main} to @code{xxx}.
8076 This is useful in the case of some cross-building environments, where
8077 the actual main program is separate from the one generated
8078 by @code{gnatbind}.
8079 @end ifclear
8080
8081 @item ^-ws^/WARNINGS=SUPPRESS^
8082 @cindex @option{^-ws^/WARNINGS=SUPPRESS^} (@code{gnatbind})
8083 @cindex Warnings
8084 Suppress all warning messages.
8085
8086 @item ^-we^/WARNINGS=ERROR^
8087 @cindex @option{^-we^/WARNINGS=ERROR^} (@code{gnatbind})
8088 Treat any warning messages as fatal errors.
8089
8090 @ifset vms
8091 @item /WARNINGS=NORMAL
8092 Standard mode with warnings generated, but warnings do not get treated
8093 as errors.
8094 @end ifset
8095
8096 @item ^-t^/NOTIME_STAMP_CHECK^
8097 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8098 @cindex Time stamp checks, in binder
8099 @cindex Binder consistency checks
8100 @cindex Consistency checks, in binder
8101 The binder performs a number of consistency checks including:
8102
8103 @itemize @bullet
8104 @item
8105 Check that time stamps of a given source unit are consistent
8106 @item
8107 Check that checksums of a given source unit are consistent
8108 @item
8109 Check that consistent versions of @code{GNAT} were used for compilation
8110 @item
8111 Check consistency of configuration pragmas as required
8112 @end itemize
8113
8114 @noindent
8115 Normally failure of such checks, in accordance with the consistency
8116 requirements of the Ada Reference Manual, causes error messages to be
8117 generated which abort the binder and prevent the output of a binder
8118 file and subsequent link to obtain an executable.
8119
8120 The @option{^-t^/NOTIME_STAMP_CHECK^} switch converts these error messages
8121 into warnings, so that
8122 binding and linking can continue to completion even in the presence of such
8123 errors. The result may be a failed link (due to missing symbols), or a
8124 non-functional executable which has undefined semantics.
8125 @emph{This means that
8126 @option{^-t^/NOTIME_STAMP_CHECK^} should be used only in unusual situations,
8127 with extreme care.}
8128 @end table
8129
8130 @node Elaboration Control
8131 @subsection Elaboration Control
8132
8133 @noindent
8134 The following switches provide additional control over the elaboration
8135 order. For full details see @ref{Elaboration Order Handling in GNAT}.
8136
8137 @table @option
8138 @item ^-p^/PESSIMISTIC_ELABORATION^
8139 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@code{gnatbind})
8140 Normally the binder attempts to choose an elaboration order that is
8141 likely to minimize the likelihood of an elaboration order error resulting
8142 in raising a @code{Program_Error} exception. This switch reverses the
8143 action of the binder, and requests that it deliberately choose an order
8144 that is likely to maximize the likelihood of an elaboration error.
8145 This is useful in ensuring portability and avoiding dependence on
8146 accidental fortuitous elaboration ordering.
8147
8148 Normally it only makes sense to use the @option{^-p^/PESSIMISTIC_ELABORATION^}
8149 switch if dynamic
8150 elaboration checking is used (@option{-gnatE} switch used for compilation).
8151 This is because in the default static elaboration mode, all necessary
8152 @code{Elaborate} and @code{Elaborate_All} pragmas are implicitly inserted.
8153 These implicit pragmas are still respected by the binder in
8154 @option{^-p^/PESSIMISTIC_ELABORATION^} mode, so a
8155 safe elaboration order is assured.
8156 @end table
8157
8158 @node Output Control
8159 @subsection Output Control
8160
8161 @noindent
8162 The following switches allow additional control over the output
8163 generated by the binder.
8164
8165 @table @option
8166 @c !sort!
8167
8168 @item ^-A^/BIND_FILE=ADA^
8169 @cindex @option{^-A^/BIND_FILE=ADA^} (@code{gnatbind})
8170 Generate binder program in Ada (default). The binder program is named
8171 @file{b~@var{mainprog}.adb} by default. This can be changed with
8172 @option{^-o^/OUTPUT^} @code{gnatbind} option.
8173
8174 @item ^-c^/NOOUTPUT^
8175 @cindex @option{^-c^/NOOUTPUT^} (@code{gnatbind})
8176 Check only. Do not generate the binder output file. In this mode the
8177 binder performs all error checks but does not generate an output file.
8178
8179 @item ^-C^/BIND_FILE=C^
8180 @cindex @option{^-C^/BIND_FILE=C^} (@code{gnatbind})
8181 Generate binder program in C. The binder program is named
8182 @file{b_@var{mainprog}.c}.
8183 This can be changed with @option{^-o^/OUTPUT^} @code{gnatbind}
8184 option.
8185
8186 @item ^-e^/ELABORATION_DEPENDENCIES^
8187 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@code{gnatbind})
8188 Output complete list of elaboration-order dependencies, showing the
8189 reason for each dependency. This output can be rather extensive but may
8190 be useful in diagnosing problems with elaboration order. The output is
8191 written to @file{stdout}.
8192
8193 @item ^-h^/HELP^
8194 @cindex @option{^-h^/HELP^} (@code{gnatbind})
8195 Output usage information. The output is written to @file{stdout}.
8196
8197 @item ^-K^/LINKER_OPTION_LIST^
8198 @cindex @option{^-K^/LINKER_OPTION_LIST^} (@code{gnatbind})
8199 Output linker options to @file{stdout}. Includes library search paths,
8200 contents of pragmas Ident and Linker_Options, and libraries added
8201 by @code{gnatbind}.
8202
8203 @item ^-l^/ORDER_OF_ELABORATION^
8204 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@code{gnatbind})
8205 Output chosen elaboration order. The output is written to @file{stdout}.
8206
8207 @item ^-O^/OBJECT_LIST^
8208 @cindex @option{^-O^/OBJECT_LIST^} (@code{gnatbind})
8209 Output full names of all the object files that must be linked to provide
8210 the Ada component of the program. The output is written to @file{stdout}.
8211 This list includes the files explicitly supplied and referenced by the user
8212 as well as implicitly referenced run-time unit files. The latter are
8213 omitted if the corresponding units reside in shared libraries. The
8214 directory names for the run-time units depend on the system configuration.
8215
8216 @item ^-o ^/OUTPUT=^@var{file}
8217 @cindex @option{^-o^/OUTPUT^} (@code{gnatbind})
8218 Set name of output file to @var{file} instead of the normal
8219 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
8220 binder generated body filename. In C mode you would normally give
8221 @var{file} an extension of @file{.c} because it will be a C source program.
8222 Note that if this option is used, then linking must be done manually.
8223 It is not possible to use gnatlink in this case, since it cannot locate
8224 the binder file.
8225
8226 @item ^-r^/RESTRICTION_LIST^
8227 @cindex @option{^-r^/RESTRICTION_LIST^} (@code{gnatbind})
8228 Generate list of @code{pragma Restrictions} that could be applied to
8229 the current unit. This is useful for code audit purposes, and also may
8230 be used to improve code generation in some cases.
8231
8232 @end table
8233
8234 @node Binding with Non-Ada Main Programs
8235 @subsection Binding with Non-Ada Main Programs
8236
8237 @noindent
8238 In our description so far we have assumed that the main
8239 program is in Ada, and that the task of the binder is to generate a
8240 corresponding function @code{main} that invokes this Ada main
8241 program. GNAT also supports the building of executable programs where
8242 the main program is not in Ada, but some of the called routines are
8243 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
8244 The following switch is used in this situation:
8245
8246 @table @option
8247 @item ^-n^/NOMAIN^
8248 @cindex @option{^-n^/NOMAIN^} (@code{gnatbind})
8249 No main program. The main program is not in Ada.
8250 @end table
8251
8252 @noindent
8253 In this case, most of the functions of the binder are still required,
8254 but instead of generating a main program, the binder generates a file
8255 containing the following callable routines:
8256
8257 @table @code
8258 @item adainit
8259 @findex adainit
8260 You must call this routine to initialize the Ada part of the program by
8261 calling the necessary elaboration routines. A call to @code{adainit} is
8262 required before the first call to an Ada subprogram.
8263
8264 Note that it is assumed that the basic execution environment must be setup
8265 to be appropriate for Ada execution at the point where the first Ada
8266 subprogram is called. In particular, if the Ada code will do any
8267 floating-point operations, then the FPU must be setup in an appropriate
8268 manner. For the case of the x86, for example, full precision mode is
8269 required. The procedure GNAT.Float_Control.Reset may be used to ensure
8270 that the FPU is in the right state.
8271
8272 @item adafinal
8273 @findex adafinal
8274 You must call this routine to perform any library-level finalization
8275 required by the Ada subprograms. A call to @code{adafinal} is required
8276 after the last call to an Ada subprogram, and before the program
8277 terminates.
8278 @end table
8279
8280 @noindent
8281 If the @option{^-n^/NOMAIN^} switch
8282 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8283 @cindex Binder, multiple input files
8284 is given, more than one ALI file may appear on
8285 the command line for @code{gnatbind}. The normal @dfn{closure}
8286 calculation is performed for each of the specified units. Calculating
8287 the closure means finding out the set of units involved by tracing
8288 @code{with} references. The reason it is necessary to be able to
8289 specify more than one ALI file is that a given program may invoke two or
8290 more quite separate groups of Ada units.
8291
8292 The binder takes the name of its output file from the last specified ALI
8293 file, unless overridden by the use of the @option{^-o file^/OUTPUT=file^}.
8294 @cindex @option{^-o^/OUTPUT^} (@command{gnatbind})
8295 The output is an Ada unit in source form that can
8296 be compiled with GNAT unless the -C switch is used in which case the
8297 output is a C source file, which must be compiled using the C compiler.
8298 This compilation occurs automatically as part of the @command{gnatlink}
8299 processing.
8300
8301 Currently the GNAT run time requires a FPU using 80 bits mode
8302 precision. Under targets where this is not the default it is required to
8303 call GNAT.Float_Control.Reset before using floating point numbers (this
8304 include float computation, float input and output) in the Ada code. A
8305 side effect is that this could be the wrong mode for the foreign code
8306 where floating point computation could be broken after this call.
8307
8308 @node Binding Programs with No Main Subprogram
8309 @subsection Binding Programs with No Main Subprogram
8310
8311 @noindent
8312 It is possible to have an Ada program which does not have a main
8313 subprogram. This program will call the elaboration routines of all the
8314 packages, then the finalization routines.
8315
8316 The following switch is used to bind programs organized in this manner:
8317
8318 @table @option
8319 @item ^-z^/ZERO_MAIN^
8320 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8321 Normally the binder checks that the unit name given on the command line
8322 corresponds to a suitable main subprogram. When this switch is used,
8323 a list of ALI files can be given, and the execution of the program
8324 consists of elaboration of these units in an appropriate order. Note
8325 that the default wide character encoding method for standard Text_IO
8326 files is always set to Brackets if this switch is set (you can use
8327 the binder switch
8328 @option{^-Wx^WIDE_CHARACTER_ENCODING^} to override this default).
8329 @end table
8330
8331 @node Command-Line Access
8332 @section Command-Line Access
8333
8334 @noindent
8335 The package @code{Ada.Command_Line} provides access to the command-line
8336 arguments and program name. In order for this interface to operate
8337 correctly, the two variables
8338
8339 @smallexample
8340 @group
8341 int gnat_argc;
8342 char **gnat_argv;
8343 @end group
8344 @end smallexample
8345
8346 @noindent
8347 @findex gnat_argv
8348 @findex gnat_argc
8349 are declared in one of the GNAT library routines. These variables must
8350 be set from the actual @code{argc} and @code{argv} values passed to the
8351 main program. With no @option{^n^/NOMAIN^} present, @code{gnatbind}
8352 generates the C main program to automatically set these variables.
8353 If the @option{^n^/NOMAIN^} switch is used, there is no automatic way to
8354 set these variables. If they are not set, the procedures in
8355 @code{Ada.Command_Line} will not be available, and any attempt to use
8356 them will raise @code{Constraint_Error}. If command line access is
8357 required, your main program must set @code{gnat_argc} and
8358 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
8359 it.
8360
8361 @node Search Paths for gnatbind
8362 @section Search Paths for @code{gnatbind}
8363
8364 @noindent
8365 The binder takes the name of an ALI file as its argument and needs to
8366 locate source files as well as other ALI files to verify object consistency.
8367
8368 For source files, it follows exactly the same search rules as @command{gcc}
8369 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
8370 directories searched are:
8371
8372 @enumerate
8373 @item
8374 The directory containing the ALI file named in the command line, unless
8375 the switch @option{^-I-^/NOCURRENT_DIRECTORY^} is specified.
8376
8377 @item
8378 All directories specified by @option{^-I^/SEARCH^}
8379 switches on the @code{gnatbind}
8380 command line, in the order given.
8381
8382 @item
8383 @findex ADA_PRJ_OBJECTS_FILE
8384 Each of the directories listed in the text file whose name is given
8385 by the @env{ADA_PRJ_OBJECTS_FILE} ^environment variable^logical name^.
8386
8387 @noindent
8388 @env{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
8389 driver when project files are used. It should not normally be set
8390 by other means.
8391
8392 @item
8393 @findex ADA_OBJECTS_PATH
8394 Each of the directories listed in the value of the
8395 @env{ADA_OBJECTS_PATH} ^environment variable^logical name^.
8396 @ifset unw
8397 Construct this value
8398 exactly as the @env{PATH} environment variable: a list of directory
8399 names separated by colons (semicolons when working with the NT version
8400 of GNAT).
8401 @end ifset
8402 @ifset vms
8403 Normally, define this value as a logical name containing a comma separated
8404 list of directory names.
8405
8406 This variable can also be defined by means of an environment string
8407 (an argument to the HP C exec* set of functions).
8408
8409 Logical Name:
8410 @smallexample
8411 DEFINE ANOTHER_PATH FOO:[BAG]
8412 DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
8413 @end smallexample
8414
8415 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
8416 first, followed by the standard Ada
8417 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB].
8418 If this is not redefined, the user will obtain the HP Ada 83 IO packages
8419 (Text_IO, Sequential_IO, etc)
8420 instead of the standard Ada packages. Thus, in order to get the standard Ada
8421 packages by default, ADA_OBJECTS_PATH must be redefined.
8422 @end ifset
8423
8424 @item
8425 The content of the @file{ada_object_path} file which is part of the GNAT
8426 installation tree and is used to store standard libraries such as the
8427 GNAT Run Time Library (RTL) unless the switch @option{-nostdlib} is
8428 specified.
8429 @ifclear vms
8430 @ref{Installing a library}
8431 @end ifclear
8432 @end enumerate
8433
8434 @noindent
8435 In the binder the switch @option{^-I^/SEARCH^}
8436 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8437 is used to specify both source and
8438 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
8439 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
8440 instead if you want to specify
8441 source paths only, and @option{^-aO^/LIBRARY_SEARCH^}
8442 @cindex @option{^-aO^/LIBRARY_SEARCH^} (@command{gnatbind})
8443 if you want to specify library paths
8444 only. This means that for the binder
8445 @option{^-I^/SEARCH=^}@var{dir} is equivalent to
8446 @option{^-aI^/SOURCE_SEARCH=^}@var{dir}
8447 @option{^-aO^/OBJECT_SEARCH=^}@var{dir}.
8448 The binder generates the bind file (a C language source file) in the
8449 current working directory.
8450
8451 @findex Ada
8452 @findex System
8453 @findex Interfaces
8454 @findex GNAT
8455 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
8456 children make up the GNAT Run-Time Library, together with the package
8457 GNAT and its children, which contain a set of useful additional
8458 library functions provided by GNAT. The sources for these units are
8459 needed by the compiler and are kept together in one directory. The ALI
8460 files and object files generated by compiling the RTL are needed by the
8461 binder and the linker and are kept together in one directory, typically
8462 different from the directory containing the sources. In a normal
8463 installation, you need not specify these directory names when compiling
8464 or binding. Either the environment variables or the built-in defaults
8465 cause these files to be found.
8466
8467 Besides simplifying access to the RTL, a major use of search paths is
8468 in compiling sources from multiple directories. This can make
8469 development environments much more flexible.
8470
8471 @node Examples of gnatbind Usage
8472 @section Examples of @code{gnatbind} Usage
8473
8474 @noindent
8475 This section contains a number of examples of using the GNAT binding
8476 utility @code{gnatbind}.
8477
8478 @table @code
8479 @item gnatbind hello
8480 The main program @code{Hello} (source program in @file{hello.adb}) is
8481 bound using the standard switch settings. The generated main program is
8482 @file{b~hello.adb}. This is the normal, default use of the binder.
8483
8484 @ifclear vms
8485 @item gnatbind hello -o mainprog.adb
8486 @end ifclear
8487 @ifset vms
8488 @item gnatbind HELLO.ALI /OUTPUT=Mainprog.ADB
8489 @end ifset
8490 The main program @code{Hello} (source program in @file{hello.adb}) is
8491 bound using the standard switch settings. The generated main program is
8492 @file{mainprog.adb} with the associated spec in
8493 @file{mainprog.ads}. Note that you must specify the body here not the
8494 spec, in the case where the output is in Ada. Note that if this option
8495 is used, then linking must be done manually, since gnatlink will not
8496 be able to find the generated file.
8497
8498 @ifclear vms
8499 @item gnatbind main -C -o mainprog.c -x
8500 @end ifclear
8501 @ifset vms
8502 @item gnatbind MAIN.ALI /BIND_FILE=C /OUTPUT=Mainprog.C /READ_SOURCES=NONE
8503 @end ifset
8504 The main program @code{Main} (source program in
8505 @file{main.adb}) is bound, excluding source files from the
8506 consistency checking, generating
8507 the file @file{mainprog.c}.
8508
8509 @ifclear vms
8510 @item gnatbind -x main_program -C -o mainprog.c
8511 This command is exactly the same as the previous example. Switches may
8512 appear anywhere in the command line, and single letter switches may be
8513 combined into a single switch.
8514 @end ifclear
8515
8516 @ifclear vms
8517 @item gnatbind -n math dbase -C -o ada-control.c
8518 @end ifclear
8519 @ifset vms
8520 @item gnatbind /NOMAIN math dbase /BIND_FILE=C /OUTPUT=ada-control.c
8521 @end ifset
8522 The main program is in a language other than Ada, but calls to
8523 subprograms in packages @code{Math} and @code{Dbase} appear. This call
8524 to @code{gnatbind} generates the file @file{ada-control.c} containing
8525 the @code{adainit} and @code{adafinal} routines to be called before and
8526 after accessing the Ada units.
8527 @end table
8528
8529 @c ------------------------------------
8530 @node Linking Using gnatlink
8531 @chapter Linking Using @command{gnatlink}
8532 @c ------------------------------------
8533 @findex gnatlink
8534
8535 @noindent
8536 This chapter discusses @command{gnatlink}, a tool that links
8537 an Ada program and builds an executable file. This utility
8538 invokes the system linker ^(via the @command{gcc} command)^^
8539 with a correct list of object files and library references.
8540 @command{gnatlink} automatically determines the list of files and
8541 references for the Ada part of a program. It uses the binder file
8542 generated by the @command{gnatbind} to determine this list.
8543
8544 Note: to invoke @code{gnatlink} with a project file, use the @code{gnat}
8545 driver (see @ref{The GNAT Driver and Project Files}).
8546
8547 @menu
8548 * Running gnatlink::
8549 * Switches for gnatlink::
8550 @end menu
8551
8552 @node Running gnatlink
8553 @section Running @command{gnatlink}
8554
8555 @noindent
8556 The form of the @command{gnatlink} command is
8557
8558 @smallexample
8559 $ gnatlink @ovar{switches} @var{mainprog}@r{[}.ali@r{]}
8560            @ovar{non-Ada objects} @ovar{linker options}
8561 @end smallexample
8562
8563 @noindent
8564 The arguments of @command{gnatlink} (switches, main @file{ALI} file,
8565 non-Ada objects
8566 or linker options) may be in any order, provided that no non-Ada object may
8567 be mistaken for a main @file{ALI} file.
8568 Any file name @file{F} without the @file{.ali}
8569 extension will be taken as the main @file{ALI} file if a file exists
8570 whose name is the concatenation of @file{F} and @file{.ali}.
8571
8572 @noindent
8573 @file{@var{mainprog}.ali} references the ALI file of the main program.
8574 The @file{.ali} extension of this file can be omitted. From this
8575 reference, @command{gnatlink} locates the corresponding binder file
8576 @file{b~@var{mainprog}.adb} and, using the information in this file along
8577 with the list of non-Ada objects and linker options, constructs a
8578 linker command file to create the executable.
8579
8580 The arguments other than the @command{gnatlink} switches and the main
8581 @file{ALI} file are passed to the linker uninterpreted.
8582 They typically include the names of
8583 object files for units written in other languages than Ada and any library
8584 references required to resolve references in any of these foreign language
8585 units, or in @code{Import} pragmas in any Ada units.
8586
8587 @var{linker options} is an optional list of linker specific
8588 switches.
8589 The default linker called by gnatlink is @command{gcc} which in
8590 turn calls the appropriate system linker.
8591 Standard options for the linker such as @option{-lmy_lib} or
8592 @option{-Ldir} can be added as is.
8593 For options that are not recognized by
8594 @command{gcc} as linker options, use the @command{gcc} switches
8595 @option{-Xlinker} or @option{-Wl,}.
8596 Refer to the GCC documentation for
8597 details. Here is an example showing how to generate a linker map:
8598
8599 @smallexample
8600 $ ^gnatlink my_prog -Wl,-Map,MAPFILE^GNAT LINK my_prog.ali /MAP^
8601 @end smallexample
8602
8603 Using @var{linker options} it is possible to set the program stack and
8604 heap size.
8605 @ifset unw
8606 See @ref{Setting Stack Size from gnatlink} and
8607 @ref{Setting Heap Size from gnatlink}.
8608 @end ifset
8609
8610 @command{gnatlink} determines the list of objects required by the Ada
8611 program and prepends them to the list of objects passed to the linker.
8612 @command{gnatlink} also gathers any arguments set by the use of
8613 @code{pragma Linker_Options} and adds them to the list of arguments
8614 presented to the linker.
8615
8616 @ifset vms
8617 @command{gnatlink} accepts the following types of extra files on the command
8618 line: objects (@file{.OBJ}), libraries (@file{.OLB}), sharable images
8619 (@file{.EXE}), and options files (@file{.OPT}). These are recognized and
8620 handled according to their extension.
8621 @end ifset
8622
8623 @node Switches for gnatlink
8624 @section Switches for @command{gnatlink}
8625
8626 @noindent
8627 The following switches are available with the @command{gnatlink} utility:
8628
8629 @table @option
8630 @c !sort!
8631
8632 @item --version
8633 @cindex @option{--version} @command{gnatlink}
8634 Display Copyright and version, then exit disregarding all other options.
8635
8636 @item --help
8637 @cindex @option{--help} @command{gnatlink}
8638 If @option{--version} was not used, display usage, then exit disregarding
8639 all other options.
8640
8641 @item ^-A^/BIND_FILE=ADA^
8642 @cindex @option{^-A^/BIND_FILE=ADA^} (@command{gnatlink})
8643 The binder has generated code in Ada. This is the default.
8644
8645 @item ^-C^/BIND_FILE=C^
8646 @cindex @option{^-C^/BIND_FILE=C^} (@command{gnatlink})
8647 If instead of generating a file in Ada, the binder has generated one in
8648 C, then the linker needs to know about it. Use this switch to signal
8649 to @command{gnatlink} that the binder has generated C code rather than
8650 Ada code.
8651
8652 @item ^-f^/FORCE_OBJECT_FILE_LIST^
8653 @cindex Command line length
8654 @cindex @option{^-f^/FORCE_OBJECT_FILE_LIST^} (@command{gnatlink})
8655 On some targets, the command line length is limited, and @command{gnatlink}
8656 will generate a separate file for the linker if the list of object files
8657 is too long.
8658 The @option{^-f^/FORCE_OBJECT_FILE_LIST^} switch forces this file
8659 to be generated even if
8660 the limit is not exceeded. This is useful in some cases to deal with
8661 special situations where the command line length is exceeded.
8662
8663 @item ^-g^/DEBUG^
8664 @cindex Debugging information, including
8665 @cindex @option{^-g^/DEBUG^} (@command{gnatlink})
8666 The option to include debugging information causes the Ada bind file (in
8667 other words, @file{b~@var{mainprog}.adb}) to be compiled with
8668 @option{^-g^/DEBUG^}.
8669 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
8670 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
8671 Without @option{^-g^/DEBUG^}, the binder removes these files by
8672 default. The same procedure apply if a C bind file was generated using
8673 @option{^-C^/BIND_FILE=C^} @code{gnatbind} option, in this case the filenames
8674 are @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
8675
8676 @item ^-n^/NOCOMPILE^
8677 @cindex @option{^-n^/NOCOMPILE^} (@command{gnatlink})
8678 Do not compile the file generated by the binder. This may be used when
8679 a link is rerun with different options, but there is no need to recompile
8680 the binder file.
8681
8682 @item ^-v^/VERBOSE^
8683 @cindex @option{^-v^/VERBOSE^} (@command{gnatlink})
8684 Causes additional information to be output, including a full list of the
8685 included object files. This switch option is most useful when you want
8686 to see what set of object files are being used in the link step.
8687
8688 @item ^-v -v^/VERBOSE/VERBOSE^
8689 @cindex @option{^-v -v^/VERBOSE/VERBOSE^} (@command{gnatlink})
8690 Very verbose mode. Requests that the compiler operate in verbose mode when
8691 it compiles the binder file, and that the system linker run in verbose mode.
8692
8693 @item ^-o ^/EXECUTABLE=^@var{exec-name}
8694 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatlink})
8695 @var{exec-name} specifies an alternate name for the generated
8696 executable program. If this switch is omitted, the executable has the same
8697 name as the main unit. For example, @code{gnatlink try.ali} creates
8698 an executable called @file{^try^TRY.EXE^}.
8699
8700 @ifclear vms
8701 @item -b @var{target}
8702 @cindex @option{-b} (@command{gnatlink})
8703 Compile your program to run on @var{target}, which is the name of a
8704 system configuration. You must have a GNAT cross-compiler built if
8705 @var{target} is not the same as your host system.
8706
8707 @item -B@var{dir}
8708 @cindex @option{-B} (@command{gnatlink})
8709 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
8710 from @var{dir} instead of the default location. Only use this switch
8711 when multiple versions of the GNAT compiler are available.
8712 @xref{Directory Options,,, gcc, The GNU Compiler Collection},
8713 for further details. You would normally use the @option{-b} or
8714 @option{-V} switch instead.
8715
8716 @item --GCC=@var{compiler_name}
8717 @cindex @option{--GCC=compiler_name} (@command{gnatlink})
8718 Program used for compiling the binder file. The default is
8719 @command{gcc}. You need to use quotes around @var{compiler_name} if
8720 @code{compiler_name} contains spaces or other separator characters.
8721 As an example @option{--GCC="foo -x -y"} will instruct @command{gnatlink} to
8722 use @code{foo -x -y} as your compiler. Note that switch @option{-c} is always
8723 inserted after your command name. Thus in the above example the compiler
8724 command that will be used by @command{gnatlink} will be @code{foo -c -x -y}.
8725 A limitation of this syntax is that the name and path name of the executable
8726 itself must not include any embedded spaces. If the compiler executable is
8727 different from the default one (gcc or <prefix>-gcc), then the back-end
8728 switches in the ALI file are not used to compile the binder generated source.
8729 For example, this is the case with @option{--GCC="foo -x -y"}. But the back end
8730 switches will be used for @option{--GCC="gcc -gnatv"}. If several
8731 @option{--GCC=compiler_name} are used, only the last @var{compiler_name}
8732 is taken into account. However, all the additional switches are also taken
8733 into account. Thus,
8734 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
8735 @option{--GCC="bar -x -y -z -t"}.
8736
8737 @item --LINK=@var{name}
8738 @cindex @option{--LINK=} (@command{gnatlink})
8739 @var{name} is the name of the linker to be invoked. This is especially
8740 useful in mixed language programs since languages such as C++ require
8741 their own linker to be used. When this switch is omitted, the default
8742 name for the linker is @command{gcc}. When this switch is used, the
8743 specified linker is called instead of @command{gcc} with exactly the same
8744 parameters that would have been passed to @command{gcc} so if the desired
8745 linker requires different parameters it is necessary to use a wrapper
8746 script that massages the parameters before invoking the real linker. It
8747 may be useful to control the exact invocation by using the verbose
8748 switch.
8749
8750 @end ifclear
8751
8752 @ifset vms
8753 @item /DEBUG=TRACEBACK
8754 @cindex @code{/DEBUG=TRACEBACK} (@command{gnatlink})
8755 This qualifier causes sufficient information to be included in the
8756 executable file to allow a traceback, but does not include the full
8757 symbol information needed by the debugger.
8758
8759 @item /IDENTIFICATION="<string>"
8760 @code{"<string>"} specifies the string to be stored in the image file
8761 identification field in the image header.
8762 It overrides any pragma @code{Ident} specified string.
8763
8764 @item /NOINHIBIT-EXEC
8765 Generate the executable file even if there are linker warnings.
8766
8767 @item /NOSTART_FILES
8768 Don't link in the object file containing the ``main'' transfer address.
8769 Used when linking with a foreign language main program compiled with an
8770 HP compiler.
8771
8772 @item /STATIC
8773 Prefer linking with object libraries over sharable images, even without
8774 /DEBUG.
8775 @end ifset
8776
8777 @end table
8778
8779 @node The GNAT Make Program gnatmake
8780 @chapter The GNAT Make Program @command{gnatmake}
8781 @findex gnatmake
8782
8783 @menu
8784 * Running gnatmake::
8785 * Switches for gnatmake::
8786 * Mode Switches for gnatmake::
8787 * Notes on the Command Line::
8788 * How gnatmake Works::
8789 * Examples of gnatmake Usage::
8790 @end menu
8791 @noindent
8792 A typical development cycle when working on an Ada program consists of
8793 the following steps:
8794
8795 @enumerate
8796 @item
8797 Edit some sources to fix bugs.
8798
8799 @item
8800 Add enhancements.
8801
8802 @item
8803 Compile all sources affected.
8804
8805 @item
8806 Rebind and relink.
8807
8808 @item
8809 Test.
8810 @end enumerate
8811
8812 @noindent
8813 The third step can be tricky, because not only do the modified files
8814 @cindex Dependency rules
8815 have to be compiled, but any files depending on these files must also be
8816 recompiled. The dependency rules in Ada can be quite complex, especially
8817 in the presence of overloading, @code{use} clauses, generics and inlined
8818 subprograms.
8819
8820 @command{gnatmake} automatically takes care of the third and fourth steps
8821 of this process. It determines which sources need to be compiled,
8822 compiles them, and binds and links the resulting object files.
8823
8824 Unlike some other Ada make programs, the dependencies are always
8825 accurately recomputed from the new sources. The source based approach of
8826 the GNAT compilation model makes this possible. This means that if
8827 changes to the source program cause corresponding changes in
8828 dependencies, they will always be tracked exactly correctly by
8829 @command{gnatmake}.
8830
8831 @node Running gnatmake
8832 @section Running @command{gnatmake}
8833
8834 @noindent
8835 The usual form of the @command{gnatmake} command is
8836
8837 @smallexample
8838 $ gnatmake @ovar{switches} @var{file_name}
8839       @ovar{file_names} @ovar{mode_switches}
8840 @end smallexample
8841
8842 @noindent
8843 The only required argument is one @var{file_name}, which specifies
8844 a compilation unit that is a main program. Several @var{file_names} can be
8845 specified: this will result in several executables being built.
8846 If @code{switches} are present, they can be placed before the first
8847 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
8848 If @var{mode_switches} are present, they must always be placed after
8849 the last @var{file_name} and all @code{switches}.
8850
8851 If you are using standard file extensions (@file{.adb} and @file{.ads}), then the
8852 extension may be omitted from the @var{file_name} arguments. However, if
8853 you are using non-standard extensions, then it is required that the
8854 extension be given. A relative or absolute directory path can be
8855 specified in a @var{file_name}, in which case, the input source file will
8856 be searched for in the specified directory only. Otherwise, the input
8857 source file will first be searched in the directory where
8858 @command{gnatmake} was invoked and if it is not found, it will be search on
8859 the source path of the compiler as described in
8860 @ref{Search Paths and the Run-Time Library (RTL)}.
8861
8862 All @command{gnatmake} output (except when you specify
8863 @option{^-M^/DEPENDENCIES_LIST^}) is to
8864 @file{stderr}. The output produced by the
8865 @option{^-M^/DEPENDENCIES_LIST^} switch is send to
8866 @file{stdout}.
8867
8868 @node Switches for gnatmake
8869 @section Switches for @command{gnatmake}
8870
8871 @noindent
8872 You may specify any of the following switches to @command{gnatmake}:
8873
8874 @table @option
8875 @c !sort!
8876
8877 @item --version
8878 @cindex @option{--version} @command{gnatmake}
8879 Display Copyright and version, then exit disregarding all other options.
8880
8881 @item --help
8882 @cindex @option{--help} @command{gnatmake}
8883 If @option{--version} was not used, display usage, then exit disregarding
8884 all other options.
8885
8886 @ifclear vms
8887 @item --GCC=@var{compiler_name}
8888 @cindex @option{--GCC=compiler_name} (@command{gnatmake})
8889 Program used for compiling. The default is `@command{gcc}'. You need to use
8890 quotes around @var{compiler_name} if @code{compiler_name} contains
8891 spaces or other separator characters. As an example @option{--GCC="foo -x
8892 -y"} will instruct @command{gnatmake} to use @code{foo -x -y} as your
8893 compiler. A limitation of this syntax is that the name and path name of
8894 the executable itself must not include any embedded spaces. Note that
8895 switch @option{-c} is always inserted after your command name. Thus in the
8896 above example the compiler command that will be used by @command{gnatmake}
8897 will be @code{foo -c -x -y}. If several @option{--GCC=compiler_name} are
8898 used, only the last @var{compiler_name} is taken into account. However,
8899 all the additional switches are also taken into account. Thus,
8900 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
8901 @option{--GCC="bar -x -y -z -t"}.
8902
8903 @item --GNATBIND=@var{binder_name}
8904 @cindex @option{--GNATBIND=binder_name} (@command{gnatmake})
8905 Program used for binding. The default is `@code{gnatbind}'. You need to
8906 use quotes around @var{binder_name} if @var{binder_name} contains spaces
8907 or other separator characters. As an example @option{--GNATBIND="bar -x
8908 -y"} will instruct @command{gnatmake} to use @code{bar -x -y} as your
8909 binder. Binder switches that are normally appended by @command{gnatmake}
8910 to `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
8911 A limitation of this syntax is that the name and path name of the executable
8912 itself must not include any embedded spaces.
8913
8914 @item --GNATLINK=@var{linker_name}
8915 @cindex @option{--GNATLINK=linker_name} (@command{gnatmake})
8916 Program used for linking. The default is `@command{gnatlink}'. You need to
8917 use quotes around @var{linker_name} if @var{linker_name} contains spaces
8918 or other separator characters. As an example @option{--GNATLINK="lan -x
8919 -y"} will instruct @command{gnatmake} to use @code{lan -x -y} as your
8920 linker. Linker switches that are normally appended by @command{gnatmake} to
8921 `@command{gnatlink}' are now appended to the end of @code{lan -x -y}.
8922 A limitation of this syntax is that the name and path name of the executable
8923 itself must not include any embedded spaces.
8924
8925 @end ifclear
8926
8927 @item ^-a^/ALL_FILES^
8928 @cindex @option{^-a^/ALL_FILES^} (@command{gnatmake})
8929 Consider all files in the make process, even the GNAT internal system
8930 files (for example, the predefined Ada library files), as well as any
8931 locked files. Locked files are files whose ALI file is write-protected.
8932 By default,
8933 @command{gnatmake} does not check these files,
8934 because the assumption is that the GNAT internal files are properly up
8935 to date, and also that any write protected ALI files have been properly
8936 installed. Note that if there is an installation problem, such that one
8937 of these files is not up to date, it will be properly caught by the
8938 binder.
8939 You may have to specify this switch if you are working on GNAT
8940 itself. The switch @option{^-a^/ALL_FILES^} is also useful
8941 in conjunction with @option{^-f^/FORCE_COMPILE^}
8942 if you need to recompile an entire application,
8943 including run-time files, using special configuration pragmas,
8944 such as a @code{Normalize_Scalars} pragma.
8945
8946 By default
8947 @code{gnatmake ^-a^/ALL_FILES^} compiles all GNAT
8948 internal files with
8949 @ifclear vms
8950 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
8951 @end ifclear
8952 @ifset vms
8953 the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} switch.
8954 @end ifset
8955
8956 @item ^-b^/ACTIONS=BIND^
8957 @cindex @option{^-b^/ACTIONS=BIND^} (@command{gnatmake})
8958 Bind only. Can be combined with @option{^-c^/ACTIONS=COMPILE^} to do
8959 compilation and binding, but no link.
8960 Can be combined with @option{^-l^/ACTIONS=LINK^}
8961 to do binding and linking. When not combined with
8962 @option{^-c^/ACTIONS=COMPILE^}
8963 all the units in the closure of the main program must have been previously
8964 compiled and must be up to date. The root unit specified by @var{file_name}
8965 may be given without extension, with the source extension or, if no GNAT
8966 Project File is specified, with the ALI file extension.
8967
8968 @item ^-c^/ACTIONS=COMPILE^
8969 @cindex @option{^-c^/ACTIONS=COMPILE^} (@command{gnatmake})
8970 Compile only. Do not perform binding, except when @option{^-b^/ACTIONS=BIND^}
8971 is also specified. Do not perform linking, except if both
8972 @option{^-b^/ACTIONS=BIND^} and
8973 @option{^-l^/ACTIONS=LINK^} are also specified.
8974 If the root unit specified by @var{file_name} is not a main unit, this is the
8975 default. Otherwise @command{gnatmake} will attempt binding and linking
8976 unless all objects are up to date and the executable is more recent than
8977 the objects.
8978
8979 @item ^-C^/MAPPING^
8980 @cindex @option{^-C^/MAPPING^} (@command{gnatmake})
8981 Use a temporary mapping file. A mapping file is a way to communicate to the
8982 compiler two mappings: from unit names to file names (without any directory
8983 information) and from file names to path names (with full directory
8984 information). These mappings are used by the compiler to short-circuit the path
8985 search. When @command{gnatmake} is invoked with this switch, it will create
8986 a temporary mapping file, initially populated by the project manager,
8987 if @option{^-P^/PROJECT_FILE^} is used, otherwise initially empty.
8988 Each invocation of the compiler will add the newly accessed sources to the
8989 mapping file. This will improve the source search during the next invocation
8990 of the compiler.
8991
8992 @item ^-C=^/USE_MAPPING_FILE=^@var{file}
8993 @cindex @option{^-C=^/USE_MAPPING^} (@command{gnatmake})
8994 Use a specific mapping file. The file, specified as a path name (absolute or
8995 relative) by this switch, should already exist, otherwise the switch is
8996 ineffective. The specified mapping file will be communicated to the compiler.
8997 This switch is not compatible with a project file
8998 (^-P^/PROJECT_FILE=^@var{file}) or with multiple compiling processes
8999 (^-j^/PROCESSES=^nnn, when nnn is greater than 1).
9000
9001 @item ^-d^/DISPLAY_PROGRESS^
9002 @cindex @option{^-d^/DISPLAY_PROGRESS^} (@command{gnatmake})
9003 Display progress for each source, up to date or not, as a single line
9004
9005 @smallexample
9006 completed x out of y (zz%)
9007 @end smallexample
9008
9009 If the file needs to be compiled this is displayed after the invocation of
9010 the compiler. These lines are displayed even in quiet output mode.
9011
9012 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
9013 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@command{gnatmake})
9014 Put all object files and ALI file in directory @var{dir}.
9015 If the @option{^-D^/DIRECTORY_OBJECTS^} switch is not used, all object files
9016 and ALI files go in the current working directory.
9017
9018 This switch cannot be used when using a project file.
9019
9020 @ifclear vms
9021 @item -eL
9022 @cindex @option{-eL} (@command{gnatmake})
9023 Follow all symbolic links when processing project files.
9024 @end ifclear
9025
9026 @item ^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^
9027 @cindex @option{^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^} (@command{gnatmake})
9028 Output the commands for the compiler, the binder and the linker
9029 on ^standard output^SYS$OUTPUT^,
9030 instead of ^standard error^SYS$ERROR^.
9031
9032 @item ^-f^/FORCE_COMPILE^
9033 @cindex @option{^-f^/FORCE_COMPILE^} (@command{gnatmake})
9034 Force recompilations. Recompile all sources, even though some object
9035 files may be up to date, but don't recompile predefined or GNAT internal
9036 files or locked files (files with a write-protected ALI file),
9037 unless the @option{^-a^/ALL_FILES^} switch is also specified.
9038
9039 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
9040 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@command{gnatmake})
9041 When using project files, if some errors or warnings are detected during
9042 parsing and verbose mode is not in effect (no use of switch
9043 ^-v^/VERBOSE^), then error lines start with the full path name of the project
9044 file, rather than its simple file name.
9045
9046 @item ^-g^/DEBUG^
9047 @cindex @option{^-g^/DEBUG^} (@command{gnatmake})
9048 Enable debugging. This switch is simply passed to the compiler and to the
9049 linker.
9050
9051 @item ^-i^/IN_PLACE^
9052 @cindex @option{^-i^/IN_PLACE^} (@command{gnatmake})
9053 In normal mode, @command{gnatmake} compiles all object files and ALI files
9054 into the current directory. If the @option{^-i^/IN_PLACE^} switch is used,
9055 then instead object files and ALI files that already exist are overwritten
9056 in place. This means that once a large project is organized into separate
9057 directories in the desired manner, then @command{gnatmake} will automatically
9058 maintain and update this organization. If no ALI files are found on the
9059 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
9060 the new object and ALI files are created in the
9061 directory containing the source being compiled. If another organization
9062 is desired, where objects and sources are kept in different directories,
9063 a useful technique is to create dummy ALI files in the desired directories.
9064 When detecting such a dummy file, @command{gnatmake} will be forced to
9065 recompile the corresponding source file, and it will be put the resulting
9066 object and ALI files in the directory where it found the dummy file.
9067
9068 @item ^-j^/PROCESSES=^@var{n}
9069 @cindex @option{^-j^/PROCESSES^} (@command{gnatmake})
9070 @cindex Parallel make
9071 Use @var{n} processes to carry out the (re)compilations. On a
9072 multiprocessor machine compilations will occur in parallel. In the
9073 event of compilation errors, messages from various compilations might
9074 get interspersed (but @command{gnatmake} will give you the full ordered
9075 list of failing compiles at the end). If this is problematic, rerun
9076 the make process with n set to 1 to get a clean list of messages.
9077
9078 @item ^-k^/CONTINUE_ON_ERROR^
9079 @cindex @option{^-k^/CONTINUE_ON_ERROR^} (@command{gnatmake})
9080 Keep going. Continue as much as possible after a compilation error. To
9081 ease the programmer's task in case of compilation errors, the list of
9082 sources for which the compile fails is given when @command{gnatmake}
9083 terminates.
9084
9085 If @command{gnatmake} is invoked with several @file{file_names} and with this
9086 switch, if there are compilation errors when building an executable,
9087 @command{gnatmake} will not attempt to build the following executables.
9088
9089 @item ^-l^/ACTIONS=LINK^
9090 @cindex @option{^-l^/ACTIONS=LINK^} (@command{gnatmake})
9091 Link only. Can be combined with @option{^-b^/ACTIONS=BIND^} to binding
9092 and linking. Linking will not be performed if combined with
9093 @option{^-c^/ACTIONS=COMPILE^}
9094 but not with @option{^-b^/ACTIONS=BIND^}.
9095 When not combined with @option{^-b^/ACTIONS=BIND^}
9096 all the units in the closure of the main program must have been previously
9097 compiled and must be up to date, and the main program needs to have been bound.
9098 The root unit specified by @var{file_name}
9099 may be given without extension, with the source extension or, if no GNAT
9100 Project File is specified, with the ALI file extension.
9101
9102 @item ^-m^/MINIMAL_RECOMPILATION^
9103 @cindex @option{^-m^/MINIMAL_RECOMPILATION^} (@command{gnatmake})
9104 Specify that the minimum necessary amount of recompilations
9105 be performed. In this mode @command{gnatmake} ignores time
9106 stamp differences when the only
9107 modifications to a source file consist in adding/removing comments,
9108 empty lines, spaces or tabs. This means that if you have changed the
9109 comments in a source file or have simply reformatted it, using this
9110 switch will tell @command{gnatmake} not to recompile files that depend on it
9111 (provided other sources on which these files depend have undergone no
9112 semantic modifications). Note that the debugging information may be
9113 out of date with respect to the sources if the @option{-m} switch causes
9114 a compilation to be switched, so the use of this switch represents a
9115 trade-off between compilation time and accurate debugging information.
9116
9117 @item ^-M^/DEPENDENCIES_LIST^
9118 @cindex Dependencies, producing list
9119 @cindex @option{^-M^/DEPENDENCIES_LIST^} (@command{gnatmake})
9120 Check if all objects are up to date. If they are, output the object
9121 dependences to @file{stdout} in a form that can be directly exploited in
9122 a @file{Makefile}. By default, each source file is prefixed with its
9123 (relative or absolute) directory name. This name is whatever you
9124 specified in the various @option{^-aI^/SOURCE_SEARCH^}
9125 and @option{^-I^/SEARCH^} switches. If you use
9126 @code{gnatmake ^-M^/DEPENDENCIES_LIST^}
9127 @option{^-q^/QUIET^}
9128 (see below), only the source file names,
9129 without relative paths, are output. If you just specify the
9130 @option{^-M^/DEPENDENCIES_LIST^}
9131 switch, dependencies of the GNAT internal system files are omitted. This
9132 is typically what you want. If you also specify
9133 the @option{^-a^/ALL_FILES^} switch,
9134 dependencies of the GNAT internal files are also listed. Note that
9135 dependencies of the objects in external Ada libraries (see switch
9136 @option{^-aL^/SKIP_MISSING=^}@var{dir} in the following list)
9137 are never reported.
9138
9139 @item ^-n^/DO_OBJECT_CHECK^
9140 @cindex @option{^-n^/DO_OBJECT_CHECK^} (@command{gnatmake})
9141 Don't compile, bind, or link. Checks if all objects are up to date.
9142 If they are not, the full name of the first file that needs to be
9143 recompiled is printed.
9144 Repeated use of this option, followed by compiling the indicated source
9145 file, will eventually result in recompiling all required units.
9146
9147 @item ^-o ^/EXECUTABLE=^@var{exec_name}
9148 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatmake})
9149 Output executable name. The name of the final executable program will be
9150 @var{exec_name}. If the @option{^-o^/EXECUTABLE^} switch is omitted the default
9151 name for the executable will be the name of the input file in appropriate form
9152 for an executable file on the host system.
9153
9154 This switch cannot be used when invoking @command{gnatmake} with several
9155 @file{file_names}.
9156
9157 @item ^-p or --create-missing-dirs^/CREATE_MISSING_DIRS^
9158 @cindex @option{^-p^/CREATE_MISSING_DIRS^} (@command{gnatmake})
9159 When using project files (^-P^/PROJECT_FILE=^@var{project}), create
9160 automatically missing object directories, library directories and exec
9161 directories.
9162
9163 @item ^-P^/PROJECT_FILE=^@var{project}
9164 @cindex @option{^-P^/PROJECT_FILE^} (@command{gnatmake})
9165 Use project file @var{project}. Only one such switch can be used.
9166 @xref{gnatmake and Project Files}.
9167
9168 @item ^-q^/QUIET^
9169 @cindex @option{^-q^/QUIET^} (@command{gnatmake})
9170 Quiet. When this flag is not set, the commands carried out by
9171 @command{gnatmake} are displayed.
9172
9173 @item ^-s^/SWITCH_CHECK/^
9174 @cindex @option{^-s^/SWITCH_CHECK^} (@command{gnatmake})
9175 Recompile if compiler switches have changed since last compilation.
9176 All compiler switches but -I and -o are taken into account in the
9177 following way:
9178 orders between different ``first letter'' switches are ignored, but
9179 orders between same switches are taken into account. For example,
9180 @option{-O -O2} is different than @option{-O2 -O}, but @option{-g -O}
9181 is equivalent to @option{-O -g}.
9182
9183 This switch is recommended when Integrated Preprocessing is used.
9184
9185 @item ^-u^/UNIQUE^
9186 @cindex @option{^-u^/UNIQUE^} (@command{gnatmake})
9187 Unique. Recompile at most the main files. It implies -c. Combined with
9188 -f, it is equivalent to calling the compiler directly. Note that using
9189 ^-u^/UNIQUE^ with a project file and no main has a special meaning
9190 (@pxref{Project Files and Main Subprograms}).
9191
9192 @item ^-U^/ALL_PROJECTS^
9193 @cindex @option{^-U^/ALL_PROJECTS^} (@command{gnatmake})
9194 When used without a project file or with one or several mains on the command
9195 line, is equivalent to ^-u^/UNIQUE^. When used with a project file and no main
9196 on the command line, all sources of all project files are checked and compiled
9197 if not up to date, and libraries are rebuilt, if necessary.
9198
9199 @item ^-v^/REASONS^
9200 @cindex @option{^-v^/REASONS^} (@command{gnatmake})
9201 Verbose. Display the reason for all recompilations @command{gnatmake}
9202 decides are necessary, with the highest verbosity level.
9203
9204 @item ^-vl^/LOW_VERBOSITY^
9205 @cindex @option{^-vl^/LOW_VERBOSITY^} (@command{gnatmake})
9206 Verbosity level Low. Display fewer lines than in verbosity Medium.
9207
9208 @item ^-vm^/MEDIUM_VERBOSITY^
9209 @cindex @option{^-vm^/MEDIUM_VERBOSITY^} (@command{gnatmake})
9210 Verbosity level Medium. Potentially display fewer lines than in verbosity High.
9211
9212 @item ^-vh^/HIGH_VERBOSITY^
9213 @cindex @option{^-vm^/HIGH_VERBOSITY^} (@command{gnatmake})
9214 Verbosity level High. Equivalent to ^-v^/REASONS^.
9215
9216 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
9217 Indicate the verbosity of the parsing of GNAT project files.
9218 @xref{Switches Related to Project Files}.
9219
9220 @item ^-x^/NON_PROJECT_UNIT_COMPILATION^
9221 @cindex @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} (@command{gnatmake})
9222 Indicate that sources that are not part of any Project File may be compiled.
9223 Normally, when using Project Files, only sources that are part of a Project
9224 File may be compile. When this switch is used, a source outside of all Project
9225 Files may be compiled. The ALI file and the object file will be put in the
9226 object directory of the main Project. The compilation switches used will only
9227 be those specified on the command line. Even when
9228 @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} is used, mains specified on the
9229 command line need to be sources of a project file.
9230
9231 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
9232 Indicate that external variable @var{name} has the value @var{value}.
9233 The Project Manager will use this value for occurrences of
9234 @code{external(name)} when parsing the project file.
9235 @xref{Switches Related to Project Files}.
9236
9237 @item ^-z^/NOMAIN^
9238 @cindex @option{^-z^/NOMAIN^} (@command{gnatmake})
9239 No main subprogram. Bind and link the program even if the unit name
9240 given on the command line is a package name. The resulting executable
9241 will execute the elaboration routines of the package and its closure,
9242 then the finalization routines.
9243
9244 @end table
9245
9246 @table @asis
9247 @item @command{gcc} @asis{switches}
9248 @ifclear vms
9249 Any uppercase or multi-character switch that is not a @command{gnatmake} switch
9250 is passed to @command{gcc} (e.g.@: @option{-O}, @option{-gnato,} etc.)
9251 @end ifclear
9252 @ifset vms
9253 Any qualifier that cannot be recognized as a qualifier for @code{GNAT MAKE}
9254 but is recognizable as a valid qualifier for @code{GNAT COMPILE} is
9255 automatically treated as a compiler switch, and passed on to all
9256 compilations that are carried out.
9257 @end ifset
9258 @end table
9259
9260 @noindent
9261 Source and library search path switches:
9262
9263 @table @option
9264 @c !sort!
9265 @item ^-aI^/SOURCE_SEARCH=^@var{dir}
9266 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatmake})
9267 When looking for source files also look in directory @var{dir}.
9268 The order in which source files search is undertaken is
9269 described in @ref{Search Paths and the Run-Time Library (RTL)}.
9270
9271 @item ^-aL^/SKIP_MISSING=^@var{dir}
9272 @cindex @option{^-aL^/SKIP_MISSING^} (@command{gnatmake})
9273 Consider @var{dir} as being an externally provided Ada library.
9274 Instructs @command{gnatmake} to skip compilation units whose @file{.ALI}
9275 files have been located in directory @var{dir}. This allows you to have
9276 missing bodies for the units in @var{dir} and to ignore out of date bodies
9277 for the same units. You still need to specify
9278 the location of the specs for these units by using the switches
9279 @option{^-aI^/SOURCE_SEARCH=^@var{dir}}
9280 or @option{^-I^/SEARCH=^@var{dir}}.
9281 Note: this switch is provided for compatibility with previous versions
9282 of @command{gnatmake}. The easier method of causing standard libraries
9283 to be excluded from consideration is to write-protect the corresponding
9284 ALI files.
9285
9286 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
9287 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatmake})
9288 When searching for library and object files, look in directory
9289 @var{dir}. The order in which library files are searched is described in
9290 @ref{Search Paths for gnatbind}.
9291
9292 @item ^-A^/CONDITIONAL_SOURCE_SEARCH=^@var{dir}
9293 @cindex Search paths, for @command{gnatmake}
9294 @cindex @option{^-A^/CONDITIONAL_SOURCE_SEARCH^} (@command{gnatmake})
9295 Equivalent to @option{^-aL^/SKIP_MISSING=^@var{dir}
9296 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9297
9298 @item ^-I^/SEARCH=^@var{dir}
9299 @cindex @option{^-I^/SEARCH^} (@command{gnatmake})
9300 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}
9301 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9302
9303 @item ^-I-^/NOCURRENT_DIRECTORY^
9304 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatmake})
9305 @cindex Source files, suppressing search
9306 Do not look for source files in the directory containing the source
9307 file named in the command line.
9308 Do not look for ALI or object files in the directory
9309 where @command{gnatmake} was invoked.
9310
9311 @item ^-L^/LIBRARY_SEARCH=^@var{dir}
9312 @cindex @option{^-L^/LIBRARY_SEARCH^} (@command{gnatmake})
9313 @cindex Linker libraries
9314 Add directory @var{dir} to the list of directories in which the linker
9315 will search for libraries. This is equivalent to
9316 @option{-largs ^-L^/LIBRARY_SEARCH=^}@var{dir}.
9317 @ifclear vms
9318 Furthermore, under Windows, the sources pointed to by the libraries path
9319 set in the registry are not searched for.
9320 @end ifclear
9321
9322 @item -nostdinc
9323 @cindex @option{-nostdinc} (@command{gnatmake})
9324 Do not look for source files in the system default directory.
9325
9326 @item -nostdlib
9327 @cindex @option{-nostdlib} (@command{gnatmake})
9328 Do not look for library files in the system default directory.
9329
9330 @item --RTS=@var{rts-path}
9331 @cindex @option{--RTS} (@command{gnatmake})
9332 Specifies the default location of the runtime library. GNAT looks for the
9333 runtime
9334 in the following directories, and stops as soon as a valid runtime is found
9335 (@file{adainclude} or @file{ada_source_path}, and @file{adalib} or
9336 @file{ada_object_path} present):
9337
9338 @itemize @bullet
9339 @item <current directory>/$rts_path
9340
9341 @item <default-search-dir>/$rts_path
9342
9343 @item <default-search-dir>/rts-$rts_path
9344 @end itemize
9345
9346 @noindent
9347 The selected path is handled like a normal RTS path.
9348
9349 @end table
9350
9351 @node Mode Switches for gnatmake
9352 @section Mode Switches for @command{gnatmake}
9353
9354 @noindent
9355 The mode switches (referred to as @code{mode_switches}) allow the
9356 inclusion of switches that are to be passed to the compiler itself, the
9357 binder or the linker. The effect of a mode switch is to cause all
9358 subsequent switches up to the end of the switch list, or up to the next
9359 mode switch, to be interpreted as switches to be passed on to the
9360 designated component of GNAT.
9361
9362 @table @option
9363 @c !sort!
9364 @item -cargs @var{switches}
9365 @cindex @option{-cargs} (@command{gnatmake})
9366 Compiler switches. Here @var{switches} is a list of switches
9367 that are valid switches for @command{gcc}. They will be passed on to
9368 all compile steps performed by @command{gnatmake}.
9369
9370 @item -bargs @var{switches}
9371 @cindex @option{-bargs} (@command{gnatmake})
9372 Binder switches. Here @var{switches} is a list of switches
9373 that are valid switches for @code{gnatbind}. They will be passed on to
9374 all bind steps performed by @command{gnatmake}.
9375
9376 @item -largs @var{switches}
9377 @cindex @option{-largs} (@command{gnatmake})
9378 Linker switches. Here @var{switches} is a list of switches
9379 that are valid switches for @command{gnatlink}. They will be passed on to
9380 all link steps performed by @command{gnatmake}.
9381
9382 @item -margs @var{switches}
9383 @cindex @option{-margs} (@command{gnatmake})
9384 Make switches. The switches are directly interpreted by @command{gnatmake},
9385 regardless of any previous occurrence of @option{-cargs}, @option{-bargs}
9386 or @option{-largs}.
9387 @end table
9388
9389 @node Notes on the Command Line
9390 @section Notes on the Command Line
9391
9392 @noindent
9393 This section contains some additional useful notes on the operation
9394 of the @command{gnatmake} command.
9395
9396 @itemize @bullet
9397 @item
9398 @cindex Recompilation, by @command{gnatmake}
9399 If @command{gnatmake} finds no ALI files, it recompiles the main program
9400 and all other units required by the main program.
9401 This means that @command{gnatmake}
9402 can be used for the initial compile, as well as during subsequent steps of
9403 the development cycle.
9404
9405 @item
9406 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
9407 is a subunit or body of a generic unit, @command{gnatmake} recompiles
9408 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
9409 warning.
9410
9411 @item
9412 In @command{gnatmake} the switch @option{^-I^/SEARCH^}
9413 is used to specify both source and
9414 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
9415 instead if you just want to specify
9416 source paths only and @option{^-aO^/OBJECT_SEARCH^}
9417 if you want to specify library paths
9418 only.
9419
9420 @item
9421 @command{gnatmake} will ignore any files whose ALI file is write-protected.
9422 This may conveniently be used to exclude standard libraries from
9423 consideration and in particular it means that the use of the
9424 @option{^-f^/FORCE_COMPILE^} switch will not recompile these files
9425 unless @option{^-a^/ALL_FILES^} is also specified.
9426
9427 @item
9428 @command{gnatmake} has been designed to make the use of Ada libraries
9429 particularly convenient. Assume you have an Ada library organized
9430 as follows: @i{^obj-dir^[OBJ_DIR]^} contains the objects and ALI files for
9431 of your Ada compilation units,
9432 whereas @i{^include-dir^[INCLUDE_DIR]^} contains the
9433 specs of these units, but no bodies. Then to compile a unit
9434 stored in @code{main.adb}, which uses this Ada library you would just type
9435
9436 @smallexample
9437 @ifclear vms
9438 $ gnatmake -aI@var{include-dir}  -aL@var{obj-dir}  main
9439 @end ifclear
9440 @ifset vms
9441 $ gnatmake /SOURCE_SEARCH=@i{[INCLUDE_DIR]}
9442            /SKIP_MISSING=@i{[OBJ_DIR]} main
9443 @end ifset
9444 @end smallexample
9445
9446 @item
9447 Using @command{gnatmake} along with the
9448 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}
9449 switch provides a mechanism for avoiding unnecessary recompilations. Using
9450 this switch,
9451 you can update the comments/format of your
9452 source files without having to recompile everything. Note, however, that
9453 adding or deleting lines in a source files may render its debugging
9454 info obsolete. If the file in question is a spec, the impact is rather
9455 limited, as that debugging info will only be useful during the
9456 elaboration phase of your program. For bodies the impact can be more
9457 significant. In all events, your debugger will warn you if a source file
9458 is more recent than the corresponding object, and alert you to the fact
9459 that the debugging information may be out of date.
9460 @end itemize
9461
9462 @node How gnatmake Works
9463 @section How @command{gnatmake} Works
9464
9465 @noindent
9466 Generally @command{gnatmake} automatically performs all necessary
9467 recompilations and you don't need to worry about how it works. However,
9468 it may be useful to have some basic understanding of the @command{gnatmake}
9469 approach and in particular to understand how it uses the results of
9470 previous compilations without incorrectly depending on them.
9471
9472 First a definition: an object file is considered @dfn{up to date} if the
9473 corresponding ALI file exists and if all the source files listed in the
9474 dependency section of this ALI file have time stamps matching those in
9475 the ALI file. This means that neither the source file itself nor any
9476 files that it depends on have been modified, and hence there is no need
9477 to recompile this file.
9478
9479 @command{gnatmake} works by first checking if the specified main unit is up
9480 to date. If so, no compilations are required for the main unit. If not,
9481 @command{gnatmake} compiles the main program to build a new ALI file that
9482 reflects the latest sources. Then the ALI file of the main unit is
9483 examined to find all the source files on which the main program depends,
9484 and @command{gnatmake} recursively applies the above procedure on all these
9485 files.
9486
9487 This process ensures that @command{gnatmake} only trusts the dependencies
9488 in an existing ALI file if they are known to be correct. Otherwise it
9489 always recompiles to determine a new, guaranteed accurate set of
9490 dependencies. As a result the program is compiled ``upside down'' from what may
9491 be more familiar as the required order of compilation in some other Ada
9492 systems. In particular, clients are compiled before the units on which
9493 they depend. The ability of GNAT to compile in any order is critical in
9494 allowing an order of compilation to be chosen that guarantees that
9495 @command{gnatmake} will recompute a correct set of new dependencies if
9496 necessary.
9497
9498 When invoking @command{gnatmake} with several @var{file_names}, if a unit is
9499 imported by several of the executables, it will be recompiled at most once.
9500
9501 Note: when using non-standard naming conventions
9502 (@pxref{Using Other File Names}), changing through a configuration pragmas
9503 file the version of a source and invoking @command{gnatmake} to recompile may
9504 have no effect, if the previous version of the source is still accessible
9505 by @command{gnatmake}. It may be necessary to use the switch
9506 ^-f^/FORCE_COMPILE^.
9507
9508 @node Examples of gnatmake Usage
9509 @section Examples of @command{gnatmake} Usage
9510
9511 @table @code
9512 @item gnatmake hello.adb
9513 Compile all files necessary to bind and link the main program
9514 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
9515 resulting object files to generate an executable file @file{^hello^HELLO.EXE^}.
9516
9517 @item gnatmake main1 main2 main3
9518 Compile all files necessary to bind and link the main programs
9519 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
9520 (containing unit @code{Main2}) and @file{main3.adb}
9521 (containing unit @code{Main3}) and bind and link the resulting object files
9522 to generate three executable files @file{^main1^MAIN1.EXE^},
9523 @file{^main2^MAIN2.EXE^}
9524 and @file{^main3^MAIN3.EXE^}.
9525
9526 @ifclear vms
9527 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
9528 @end ifclear
9529
9530 @ifset vms
9531 @item gnatmake Main_Unit /QUIET
9532 /COMPILER_QUALIFIERS /OPTIMIZE=ALL
9533 /BINDER_QUALIFIERS /ORDER_OF_ELABORATION
9534 @end ifset
9535 Compile all files necessary to bind and link the main program unit
9536 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
9537 be done with optimization level 2 and the order of elaboration will be
9538 listed by the binder. @command{gnatmake} will operate in quiet mode, not
9539 displaying commands it is executing.
9540 @end table
9541
9542 @c *************************
9543 @node Improving Performance
9544 @chapter Improving Performance
9545 @cindex Improving performance
9546
9547 @noindent
9548 This chapter presents several topics related to program performance.
9549 It first describes some of the tradeoffs that need to be considered
9550 and some of the techniques for making your program run faster.
9551 It then documents the @command{gnatelim} tool and unused subprogram/data
9552 elimination feature, which can reduce the size of program executables.
9553
9554 Note: to invoke @command{gnatelim} with a project file, use the @code{gnat}
9555 driver (see @ref{The GNAT Driver and Project Files}).
9556
9557 @ifnottex
9558 @menu
9559 * Performance Considerations::
9560 * Text_IO Suggestions::
9561 * Reducing Size of Ada Executables with gnatelim::
9562 * Reducing Size of Executables with unused subprogram/data elimination::
9563 @end menu
9564 @end ifnottex
9565
9566 @c *****************************
9567 @node Performance Considerations
9568 @section Performance Considerations
9569
9570 @noindent
9571 The GNAT system provides a number of options that allow a trade-off
9572 between
9573
9574 @itemize @bullet
9575 @item
9576 performance of the generated code
9577
9578 @item
9579 speed of compilation
9580
9581 @item
9582 minimization of dependences and recompilation
9583
9584 @item
9585 the degree of run-time checking.
9586 @end itemize
9587
9588 @noindent
9589 The defaults (if no options are selected) aim at improving the speed
9590 of compilation and minimizing dependences, at the expense of performance
9591 of the generated code:
9592
9593 @itemize @bullet
9594 @item
9595 no optimization
9596
9597 @item
9598 no inlining of subprogram calls
9599
9600 @item
9601 all run-time checks enabled except overflow and elaboration checks
9602 @end itemize
9603
9604 @noindent
9605 These options are suitable for most program development purposes. This
9606 chapter describes how you can modify these choices, and also provides
9607 some guidelines on debugging optimized code.
9608
9609 @menu
9610 * Controlling Run-Time Checks::
9611 * Use of Restrictions::
9612 * Optimization Levels::
9613 * Debugging Optimized Code::
9614 * Inlining of Subprograms::
9615 * Other Optimization Switches::
9616 * Optimization and Strict Aliasing::
9617
9618 @ifset vms
9619 * Coverage Analysis::
9620 @end ifset
9621 @end menu
9622
9623 @node Controlling Run-Time Checks
9624 @subsection Controlling Run-Time Checks
9625
9626 @noindent
9627 By default, GNAT generates all run-time checks, except integer overflow
9628 checks, stack overflow checks, and checks for access before elaboration on
9629 subprogram calls. The latter are not required in default mode, because all
9630 necessary checking is done at compile time.
9631 @cindex @option{-gnatp} (@command{gcc})
9632 @cindex @option{-gnato} (@command{gcc})
9633 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
9634 be modified. @xref{Run-Time Checks}.
9635
9636 Our experience is that the default is suitable for most development
9637 purposes.
9638
9639 We treat integer overflow specially because these
9640 are quite expensive and in our experience are not as important as other
9641 run-time checks in the development process. Note that division by zero
9642 is not considered an overflow check, and divide by zero checks are
9643 generated where required by default.
9644
9645 Elaboration checks are off by default, and also not needed by default, since
9646 GNAT uses a static elaboration analysis approach that avoids the need for
9647 run-time checking. This manual contains a full chapter discussing the issue
9648 of elaboration checks, and if the default is not satisfactory for your use,
9649 you should read this chapter.
9650
9651 For validity checks, the minimal checks required by the Ada Reference
9652 Manual (for case statements and assignments to array elements) are on
9653 by default. These can be suppressed by use of the @option{-gnatVn} switch.
9654 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
9655 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
9656 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
9657 are also suppressed entirely if @option{-gnatp} is used.
9658
9659 @cindex Overflow checks
9660 @cindex Checks, overflow
9661 @findex Suppress
9662 @findex Unsuppress
9663 @cindex pragma Suppress
9664 @cindex pragma Unsuppress
9665 Note that the setting of the switches controls the default setting of
9666 the checks. They may be modified using either @code{pragma Suppress} (to
9667 remove checks) or @code{pragma Unsuppress} (to add back suppressed
9668 checks) in the program source.
9669
9670 @node Use of Restrictions
9671 @subsection Use of Restrictions
9672
9673 @noindent
9674 The use of pragma Restrictions allows you to control which features are
9675 permitted in your program. Apart from the obvious point that if you avoid
9676 relatively expensive features like finalization (enforceable by the use
9677 of pragma Restrictions (No_Finalization), the use of this pragma does not
9678 affect the generated code in most cases.
9679
9680 One notable exception to this rule is that the possibility of task abort
9681 results in some distributed overhead, particularly if finalization or
9682 exception handlers are used. The reason is that certain sections of code
9683 have to be marked as non-abortable.
9684
9685 If you use neither the @code{abort} statement, nor asynchronous transfer
9686 of control (@code{select @dots{} then abort}), then this distributed overhead
9687 is removed, which may have a general positive effect in improving
9688 overall performance.  Especially code involving frequent use of tasking
9689 constructs and controlled types will show much improved performance.
9690 The relevant restrictions pragmas are
9691
9692 @smallexample @c ada
9693    pragma Restrictions (No_Abort_Statements);
9694    pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
9695 @end smallexample
9696
9697 @noindent
9698 It is recommended that these restriction pragmas be used if possible. Note
9699 that this also means that you can write code without worrying about the
9700 possibility of an immediate abort at any point.
9701
9702 @node Optimization Levels
9703 @subsection Optimization Levels
9704 @cindex @option{^-O^/OPTIMIZE^} (@command{gcc})
9705
9706 @noindent
9707 Without any optimization ^option,^qualifier,^
9708 the compiler's goal is to reduce the cost of
9709 compilation and to make debugging produce the expected results.
9710 Statements are independent: if you stop the program with a breakpoint between
9711 statements, you can then assign a new value to any variable or change
9712 the program counter to any other statement in the subprogram and get exactly
9713 the results you would expect from the source code.
9714
9715 Turning on optimization makes the compiler attempt to improve the
9716 performance and/or code size at the expense of compilation time and
9717 possibly the ability to debug the program.
9718
9719 If you use multiple
9720 ^-O options, with or without level numbers,^/OPTIMIZE qualifiers,^
9721 the last such option is the one that is effective.
9722
9723 @noindent
9724 The default is optimization off. This results in the fastest compile
9725 times, but GNAT makes absolutely no attempt to optimize, and the
9726 generated programs are considerably larger and slower than when
9727 optimization is enabled. You can use the
9728 @ifclear vms
9729 @option{-O} switch (the permitted forms are @option{-O0}, @option{-O1}
9730 @option{-O2}, @option{-O3}, and @option{-Os})
9731 @end ifclear
9732 @ifset vms
9733 @code{OPTIMIZE} qualifier
9734 @end ifset
9735 to @command{gcc} to control the optimization level:
9736
9737 @table @option
9738 @item ^-O0^/OPTIMIZE=NONE^
9739 No optimization (the default);
9740 generates unoptimized code but has
9741 the fastest compilation time.
9742
9743 Note that many other compilers do fairly extensive optimization
9744 even if ``no optimization'' is specified. With gcc, it is
9745 very unusual to use ^-O0^/OPTIMIZE=NONE^ for production if
9746 execution time is of any concern, since ^-O0^/OPTIMIZE=NONE^
9747 really does mean no optimization at all. This difference between
9748 gcc and other compilers should be kept in mind when doing
9749 performance comparisons.
9750
9751 @item ^-O1^/OPTIMIZE=SOME^
9752 Moderate optimization;
9753 optimizes reasonably well but does not
9754 degrade compilation time significantly.
9755
9756 @item ^-O2^/OPTIMIZE=ALL^
9757 @ifset vms
9758 @itemx /OPTIMIZE=DEVELOPMENT
9759 @end ifset
9760 Full optimization;
9761 generates highly optimized code and has
9762 the slowest compilation time.
9763
9764 @item ^-O3^/OPTIMIZE=INLINING^
9765 Full optimization as in @option{-O2},
9766 and also attempts automatic inlining of small
9767 subprograms within a unit (@pxref{Inlining of Subprograms}).
9768
9769 @item ^-Os^/OPTIMIZE=SPACE^
9770 Optimize space usage of resulting program.
9771 @end table
9772
9773 @noindent
9774 Higher optimization levels perform more global transformations on the
9775 program and apply more expensive analysis algorithms in order to generate
9776 faster and more compact code. The price in compilation time, and the
9777 resulting improvement in execution time,
9778 both depend on the particular application and the hardware environment.
9779 You should experiment to find the best level for your application.
9780
9781 Since the precise set of optimizations done at each level will vary from
9782 release to release (and sometime from target to target), it is best to think
9783 of the optimization settings in general terms.
9784 @xref{Optimize Options,, Options That Control Optimization, gcc, Using
9785 the GNU Compiler Collection (GCC)}, for details about
9786 ^the @option{-O} settings and a number of @option{-f} options that^how to^
9787 individually enable or disable specific optimizations.
9788
9789 Unlike some other compilation systems, ^@command{gcc}^GNAT^ has
9790 been tested extensively at all optimization levels. There are some bugs
9791 which appear only with optimization turned on, but there have also been
9792 bugs which show up only in @emph{unoptimized} code. Selecting a lower
9793 level of optimization does not improve the reliability of the code
9794 generator, which in practice is highly reliable at all optimization
9795 levels.
9796
9797 Note regarding the use of @option{-O3}: The use of this optimization level
9798 is generally discouraged with GNAT, since it often results in larger
9799 executables which run more slowly. See further discussion of this point
9800 in @ref{Inlining of Subprograms}.
9801
9802 @node Debugging Optimized Code
9803 @subsection Debugging Optimized Code
9804 @cindex Debugging optimized code
9805 @cindex Optimization and debugging
9806
9807 @noindent
9808 Although it is possible to do a reasonable amount of debugging at
9809 @ifclear vms
9810 nonzero optimization levels,
9811 the higher the level the more likely that
9812 @end ifclear
9813 @ifset vms
9814 @option{/OPTIMIZE} settings other than @code{NONE},
9815 such settings will make it more likely that
9816 @end ifset
9817 source-level constructs will have been eliminated by optimization.
9818 For example, if a loop is strength-reduced, the loop
9819 control variable may be completely eliminated and thus cannot be
9820 displayed in the debugger.
9821 This can only happen at @option{-O2} or @option{-O3}.
9822 Explicit temporary variables that you code might be eliminated at
9823 ^level^setting^ @option{-O1} or higher.
9824
9825 The use of the @option{^-g^/DEBUG^} switch,
9826 @cindex @option{^-g^/DEBUG^} (@command{gcc})
9827 which is needed for source-level debugging,
9828 affects the size of the program executable on disk,
9829 and indeed the debugging information can be quite large.
9830 However, it has no effect on the generated code (and thus does not
9831 degrade performance)
9832
9833 Since the compiler generates debugging tables for a compilation unit before
9834 it performs optimizations, the optimizing transformations may invalidate some
9835 of the debugging data.  You therefore need to anticipate certain
9836 anomalous situations that may arise while debugging optimized code.
9837 These are the most common cases:
9838
9839 @enumerate
9840 @item
9841 @i{The ``hopping Program Counter'':}  Repeated @code{step} or @code{next}
9842 commands show
9843 the PC bouncing back and forth in the code.  This may result from any of
9844 the following optimizations:
9845
9846 @itemize @bullet
9847 @item
9848 @i{Common subexpression elimination:} using a single instance of code for a
9849 quantity that the source computes several times.  As a result you
9850 may not be able to stop on what looks like a statement.
9851
9852 @item
9853 @i{Invariant code motion:} moving an expression that does not change within a
9854 loop, to the beginning of the loop.
9855
9856 @item
9857 @i{Instruction scheduling:} moving instructions so as to
9858 overlap loads and stores (typically) with other code, or in
9859 general to move computations of values closer to their uses. Often
9860 this causes you to pass an assignment statement without the assignment
9861 happening and then later bounce back to the statement when the
9862 value is actually needed.  Placing a breakpoint on a line of code
9863 and then stepping over it may, therefore, not always cause all the
9864 expected side-effects.
9865 @end itemize
9866
9867 @item
9868 @i{The ``big leap'':} More commonly known as @emph{cross-jumping}, in which
9869 two identical pieces of code are merged and the program counter suddenly
9870 jumps to a statement that is not supposed to be executed, simply because
9871 it (and the code following) translates to the same thing as the code
9872 that @emph{was} supposed to be executed.  This effect is typically seen in
9873 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
9874 a @code{break} in a C @code{^switch^switch^} statement.
9875
9876 @item
9877 @i{The ``roving variable'':} The symptom is an unexpected value in a variable.
9878 There are various reasons for this effect:
9879
9880 @itemize @bullet
9881 @item
9882 In a subprogram prologue, a parameter may not yet have been moved to its
9883 ``home''.
9884
9885 @item
9886 A variable may be dead, and its register re-used.  This is
9887 probably the most common cause.
9888
9889 @item
9890 As mentioned above, the assignment of a value to a variable may
9891 have been moved.
9892
9893 @item
9894 A variable may be eliminated entirely by value propagation or
9895 other means.  In this case, GCC may incorrectly generate debugging
9896 information for the variable
9897 @end itemize
9898
9899 @noindent
9900 In general, when an unexpected value appears for a local variable or parameter
9901 you should first ascertain if that value was actually computed by
9902 your program, as opposed to being incorrectly reported by the debugger.
9903 Record fields or
9904 array elements in an object designated by an access value
9905 are generally less of a problem, once you have ascertained that the access
9906 value is sensible.
9907 Typically, this means checking variables in the preceding code and in the
9908 calling subprogram to verify that the value observed is explainable from other
9909 values (one must apply the procedure recursively to those
9910 other values); or re-running the code and stopping a little earlier
9911 (perhaps before the call) and stepping to better see how the variable obtained
9912 the value in question; or continuing to step @emph{from} the point of the
9913 strange value to see if code motion had simply moved the variable's
9914 assignments later.
9915 @end enumerate
9916
9917 @noindent
9918 In light of such anomalies, a recommended technique is to use @option{-O0}
9919 early in the software development cycle, when extensive debugging capabilities
9920 are most needed, and then move to @option{-O1} and later @option{-O2} as
9921 the debugger becomes less critical.
9922 Whether to use the @option{^-g^/DEBUG^} switch in the release version is
9923 a release management issue.
9924 @ifclear vms
9925 Note that if you use @option{-g} you can then use the @command{strip} program
9926 on the resulting executable,
9927 which removes both debugging information and global symbols.
9928 @end ifclear
9929
9930 @node Inlining of Subprograms
9931 @subsection Inlining of Subprograms
9932
9933 @noindent
9934 A call to a subprogram in the current unit is inlined if all the
9935 following conditions are met:
9936
9937 @itemize @bullet
9938 @item
9939 The optimization level is at least @option{-O1}.
9940
9941 @item
9942 The called subprogram is suitable for inlining: It must be small enough
9943 and not contain something that @command{gcc} cannot support in inlined
9944 subprograms.
9945
9946 @item
9947 @cindex pragma Inline
9948 @findex Inline
9949 Either @code{pragma Inline} applies to the subprogram, or it is local
9950 to the unit and called once from within it, or it is small and automatic
9951 inlining (optimization level @option{-O3}) is specified.
9952 @end itemize
9953
9954 @noindent
9955 Calls to subprograms in @code{with}'ed units are normally not inlined.
9956 To achieve actual inlining (that is, replacement of the call by the code
9957 in the body of the subprogram), the following conditions must all be true.
9958
9959 @itemize @bullet
9960 @item
9961 The optimization level is at least @option{-O1}.
9962
9963 @item
9964 The called subprogram is suitable for inlining: It must be small enough
9965 and not contain something that @command{gcc} cannot support in inlined
9966 subprograms.
9967
9968 @item
9969 The call appears in a body (not in a package spec).
9970
9971 @item
9972 There is a @code{pragma Inline} for the subprogram.
9973
9974 @item
9975 @cindex @option{-gnatn} (@command{gcc})
9976 The @option{^-gnatn^/INLINE^} switch
9977 is used in the @command{gcc} command line
9978 @end itemize
9979
9980 Even if all these conditions are met, it may not be possible for
9981 the compiler to inline the call, due to the length of the body,
9982 or features in the body that make it impossible for the compiler
9983 to do the inlining.
9984
9985 Note that specifying the @option{-gnatn} switch causes additional
9986 compilation dependencies. Consider the following:
9987
9988 @smallexample @c ada
9989 @cartouche
9990 package R is
9991    procedure Q;
9992    pragma Inline (Q);
9993 end R;
9994 package body R is
9995    @dots{}
9996 end R;
9997
9998 with R;
9999 procedure Main is
10000 begin
10001    @dots{}
10002    R.Q;
10003 end Main;
10004 @end cartouche
10005 @end smallexample
10006
10007 @noindent
10008 With the default behavior (no @option{-gnatn} switch specified), the
10009 compilation of the @code{Main} procedure depends only on its own source,
10010 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
10011 means that editing the body of @code{R} does not require recompiling
10012 @code{Main}.
10013
10014 On the other hand, the call @code{R.Q} is not inlined under these
10015 circumstances. If the @option{-gnatn} switch is present when @code{Main}
10016 is compiled, the call will be inlined if the body of @code{Q} is small
10017 enough, but now @code{Main} depends on the body of @code{R} in
10018 @file{r.adb} as well as on the spec. This means that if this body is edited,
10019 the main program must be recompiled. Note that this extra dependency
10020 occurs whether or not the call is in fact inlined by @command{gcc}.
10021
10022 The use of front end inlining with @option{-gnatN} generates similar
10023 additional dependencies.
10024
10025 @cindex @option{^-fno-inline^/INLINE=SUPPRESS^} (@command{gcc})
10026 Note: The @option{^-fno-inline^/INLINE=SUPPRESS^} switch
10027 can be used to prevent
10028 all inlining. This switch overrides all other conditions and ensures
10029 that no inlining occurs. The extra dependences resulting from
10030 @option{-gnatn} will still be active, even if
10031 this switch is used to suppress the resulting inlining actions.
10032
10033 @cindex @option{-fno-inline-functions} (@command{gcc})
10034 Note: The @option{-fno-inline-functions} switch can be used to prevent
10035 automatic inlining of small subprograms if @option{-O3} is used.
10036
10037 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
10038 Note: The @option{-fno-inline-functions-called-once} switch
10039 can be used to prevent inlining of subprograms local to the unit
10040 and called once from within it if @option{-O1} is used.
10041
10042 Note regarding the use of @option{-O3}: There is no difference in inlining
10043 behavior between @option{-O2} and @option{-O3} for subprograms with an explicit
10044 pragma @code{Inline} assuming the use of @option{-gnatn}
10045 or @option{-gnatN} (the switches that activate inlining). If you have used
10046 pragma @code{Inline} in appropriate cases, then it is usually much better
10047 to use @option{-O2} and @option{-gnatn} and avoid the use of @option{-O3} which
10048 in this case only has the effect of inlining subprograms you did not
10049 think should be inlined. We often find that the use of @option{-O3} slows
10050 down code by performing excessive inlining, leading to increased instruction
10051 cache pressure from the increased code size. So the bottom line here is
10052 that you should not automatically assume that @option{-O3} is better than
10053 @option{-O2}, and indeed you should use @option{-O3} only if tests show that
10054 it actually improves performance.
10055
10056 @node Other Optimization Switches
10057 @subsection Other Optimization Switches
10058 @cindex Optimization Switches
10059
10060 Since @code{GNAT} uses the @command{gcc} back end, all the specialized
10061 @command{gcc} optimization switches are potentially usable. These switches
10062 have not been extensively tested with GNAT but can generally be expected
10063 to work. Examples of switches in this category are
10064 @option{-funroll-loops} and
10065 the various target-specific @option{-m} options (in particular, it has been
10066 observed that @option{-march=pentium4} can significantly improve performance
10067 on appropriate machines). For full details of these switches, see
10068 @ref{Submodel Options,, Hardware Models and Configurations, gcc, Using
10069 the GNU Compiler Collection (GCC)}.
10070
10071 @node Optimization and Strict Aliasing
10072 @subsection Optimization and Strict Aliasing
10073 @cindex Aliasing
10074 @cindex Strict Aliasing
10075 @cindex No_Strict_Aliasing
10076
10077 @noindent
10078 The strong typing capabilities of Ada allow an optimizer to generate
10079 efficient code in situations where other languages would be forced to
10080 make worst case assumptions preventing such optimizations. Consider
10081 the following example:
10082
10083 @smallexample @c ada
10084 @cartouche
10085 procedure R is
10086    type Int1 is new Integer;
10087    type Int2 is new Integer;
10088    type Int1A is access Int1;
10089    type Int2A is access Int2;
10090    Int1V : Int1A;
10091    Int2V : Int2A;
10092    @dots{}
10093
10094 begin
10095    @dots{}
10096    for J in Data'Range loop
10097       if Data (J) = Int1V.all then
10098          Int2V.all := Int2V.all + 1;
10099       end if;
10100    end loop;
10101    @dots{}
10102 end R;
10103 @end cartouche
10104 @end smallexample
10105
10106 @noindent
10107 In this example, since the variable @code{Int1V} can only access objects
10108 of type @code{Int1}, and @code{Int2V} can only access objects of type
10109 @code{Int2}, there is no possibility that the assignment to
10110 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
10111 the compiler optimizer can "know" that the value @code{Int1V.all} is constant
10112 for all iterations of the loop and avoid the extra memory reference
10113 required to dereference it each time through the loop.
10114
10115 This kind of optimization, called strict aliasing analysis, is
10116 triggered by specifying an optimization level of @option{-O2} or
10117 higher and allows @code{GNAT} to generate more efficient code
10118 when access values are involved.
10119
10120 However, although this optimization is always correct in terms of
10121 the formal semantics of the Ada Reference Manual, difficulties can
10122 arise if features like @code{Unchecked_Conversion} are used to break
10123 the typing system. Consider the following complete program example:
10124
10125 @smallexample @c ada
10126 @cartouche
10127 package p1 is
10128    type int1 is new integer;
10129    type int2 is new integer;
10130    type a1 is access int1;
10131    type a2 is access int2;
10132 end p1;
10133
10134 with p1; use p1;
10135 package p2 is
10136    function to_a2 (Input : a1) return a2;
10137 end p2;
10138
10139 with Unchecked_Conversion;
10140 package body p2 is
10141    function to_a2 (Input : a1) return a2 is
10142       function to_a2u is
10143         new Unchecked_Conversion (a1, a2);
10144    begin
10145       return to_a2u (Input);
10146    end to_a2;
10147 end p2;
10148
10149 with p2; use p2;
10150 with p1; use p1;
10151 with Text_IO; use Text_IO;
10152 procedure m is
10153    v1 : a1 := new int1;
10154    v2 : a2 := to_a2 (v1);
10155 begin
10156    v1.all := 1;
10157    v2.all := 0;
10158    put_line (int1'image (v1.all));
10159 end;
10160 @end cartouche
10161 @end smallexample
10162
10163 @noindent
10164 This program prints out 0 in @option{-O0} or @option{-O1}
10165 mode, but it prints out 1 in @option{-O2} mode. That's
10166 because in strict aliasing mode, the compiler can and
10167 does assume that the assignment to @code{v2.all} could not
10168 affect the value of @code{v1.all}, since different types
10169 are involved.
10170
10171 This behavior is not a case of non-conformance with the standard, since
10172 the Ada RM specifies that an unchecked conversion where the resulting
10173 bit pattern is not a correct value of the target type can result in an
10174 abnormal value and attempting to reference an abnormal value makes the
10175 execution of a program erroneous.  That's the case here since the result
10176 does not point to an object of type @code{int2}.  This means that the
10177 effect is entirely unpredictable.
10178
10179 However, although that explanation may satisfy a language
10180 lawyer, in practice an applications programmer expects an
10181 unchecked conversion involving pointers to create true
10182 aliases and the behavior of printing 1 seems plain wrong.
10183 In this case, the strict aliasing optimization is unwelcome.
10184
10185 Indeed the compiler recognizes this possibility, and the
10186 unchecked conversion generates a warning:
10187
10188 @smallexample
10189 p2.adb:5:07: warning: possible aliasing problem with type "a2"
10190 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
10191 p2.adb:5:07: warning:  or use "pragma No_Strict_Aliasing (a2);"
10192 @end smallexample
10193
10194 @noindent
10195 Unfortunately the problem is recognized when compiling the body of
10196 package @code{p2}, but the actual "bad" code is generated while
10197 compiling the body of @code{m} and this latter compilation does not see
10198 the suspicious @code{Unchecked_Conversion}.
10199
10200 As implied by the warning message, there are approaches you can use to
10201 avoid the unwanted strict aliasing optimization in a case like this.
10202
10203 One possibility is to simply avoid the use of @option{-O2}, but
10204 that is a bit drastic, since it throws away a number of useful
10205 optimizations that do not involve strict aliasing assumptions.
10206
10207 A less drastic approach is to compile the program using the
10208 option @option{-fno-strict-aliasing}. Actually it is only the
10209 unit containing the dereferencing of the suspicious pointer
10210 that needs to be compiled. So in this case, if we compile
10211 unit @code{m} with this switch, then we get the expected
10212 value of zero printed. Analyzing which units might need
10213 the switch can be painful, so a more reasonable approach
10214 is to compile the entire program with options @option{-O2}
10215 and @option{-fno-strict-aliasing}. If the performance is
10216 satisfactory with this combination of options, then the
10217 advantage is that the entire issue of possible "wrong"
10218 optimization due to strict aliasing is avoided.
10219
10220 To avoid the use of compiler switches, the configuration
10221 pragma @code{No_Strict_Aliasing} with no parameters may be
10222 used to specify that for all access types, the strict
10223 aliasing optimization should be suppressed.
10224
10225 However, these approaches are still overkill, in that they causes
10226 all manipulations of all access values to be deoptimized. A more
10227 refined approach is to concentrate attention on the specific
10228 access type identified as problematic.
10229
10230 First, if a careful analysis of uses of the pointer shows
10231 that there are no possible problematic references, then
10232 the warning can be suppressed by bracketing the
10233 instantiation of @code{Unchecked_Conversion} to turn
10234 the warning off:
10235
10236 @smallexample @c ada
10237    pragma Warnings (Off);
10238    function to_a2u is
10239      new Unchecked_Conversion (a1, a2);
10240    pragma Warnings (On);
10241 @end smallexample
10242
10243 @noindent
10244 Of course that approach is not appropriate for this particular
10245 example, since indeed there is a problematic reference. In this
10246 case we can take one of two other approaches.
10247
10248 The first possibility is to move the instantiation of unchecked
10249 conversion to the unit in which the type is declared. In
10250 this example, we would move the instantiation of
10251 @code{Unchecked_Conversion} from the body of package
10252 @code{p2} to the spec of package @code{p1}. Now the
10253 warning disappears. That's because any use of the
10254 access type knows there is a suspicious unchecked
10255 conversion, and the strict aliasing optimization
10256 is automatically suppressed for the type.
10257
10258 If it is not practical to move the unchecked conversion to the same unit
10259 in which the destination access type is declared (perhaps because the
10260 source type is not visible in that unit), you may use pragma
10261 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
10262 same declarative sequence as the declaration of the access type:
10263
10264 @smallexample @c ada
10265    type a2 is access int2;
10266    pragma No_Strict_Aliasing (a2);
10267 @end smallexample
10268
10269 @noindent
10270 Here again, the compiler now knows that the strict aliasing optimization
10271 should be suppressed for any reference to type @code{a2} and the
10272 expected behavior is obtained.
10273
10274 Finally, note that although the compiler can generate warnings for
10275 simple cases of unchecked conversions, there are tricker and more
10276 indirect ways of creating type incorrect aliases which the compiler
10277 cannot detect. Examples are the use of address overlays and unchecked
10278 conversions involving composite types containing access types as
10279 components. In such cases, no warnings are generated, but there can
10280 still be aliasing problems. One safe coding practice is to forbid the
10281 use of address clauses for type overlaying, and to allow unchecked
10282 conversion only for primitive types. This is not really a significant
10283 restriction since any possible desired effect can be achieved by
10284 unchecked conversion of access values.
10285
10286 @ifset vms
10287 @node Coverage Analysis
10288 @subsection Coverage Analysis
10289
10290 @noindent
10291 GNAT supports the HP Performance Coverage Analyzer (PCA), which allows
10292 the user to determine the distribution of execution time across a program,
10293 @pxref{Profiling} for details of usage.
10294 @end ifset
10295
10296
10297 @node Text_IO Suggestions
10298 @section @code{Text_IO} Suggestions
10299 @cindex @code{Text_IO} and performance
10300
10301 @noindent
10302 The @code{Ada.Text_IO} package has fairly high overheads due in part to
10303 the requirement of maintaining page and line counts. If performance
10304 is critical, a recommendation is to use @code{Stream_IO} instead of
10305 @code{Text_IO} for volume output, since this package has less overhead.
10306
10307 If @code{Text_IO} must be used, note that by default output to the standard
10308 output and standard error files is unbuffered (this provides better
10309 behavior when output statements are used for debugging, or if the
10310 progress of a program is observed by tracking the output, e.g. by
10311 using the Unix @command{tail -f} command to watch redirected output.
10312
10313 If you are generating large volumes of output with @code{Text_IO} and
10314 performance is an important factor, use a designated file instead
10315 of the standard output file, or change the standard output file to
10316 be buffered using @code{Interfaces.C_Streams.setvbuf}.
10317
10318
10319
10320 @node Reducing Size of Ada Executables with gnatelim
10321 @section Reducing Size of Ada Executables with @code{gnatelim}
10322 @findex gnatelim
10323
10324 @noindent
10325 This section describes @command{gnatelim}, a tool which detects unused
10326 subprograms and helps the compiler to create a smaller executable for your
10327 program.
10328
10329 @menu
10330 * About gnatelim::
10331 * Running gnatelim::
10332 * Correcting the List of Eliminate Pragmas::
10333 * Making Your Executables Smaller::
10334 * Summary of the gnatelim Usage Cycle::
10335 @end menu
10336
10337 @node About gnatelim
10338 @subsection About @code{gnatelim}
10339
10340 @noindent
10341 When a program shares a set of Ada
10342 packages with other programs, it may happen that this program uses
10343 only a fraction of the subprograms defined in these packages. The code
10344 created for these unused subprograms increases the size of the executable.
10345
10346 @code{gnatelim} tracks unused subprograms in an Ada program and
10347 outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the
10348 subprograms that are declared but never called. By placing the list of
10349 @code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and
10350 recompiling your program, you may decrease the size of its executable,
10351 because the compiler will not generate the code for 'eliminated' subprograms.
10352 @xref{Pragma Eliminate,,, gnat_rm, GNAT Reference Manual}, for more
10353 information about this pragma.
10354
10355 @code{gnatelim} needs as its input data the name of the main subprogram
10356 and a bind file for a main subprogram.
10357
10358 To create a bind file for @code{gnatelim}, run @code{gnatbind} for
10359 the main subprogram. @code{gnatelim} can work with both Ada and C
10360 bind files; when both are present, it uses the Ada bind file.
10361 The following commands will build the program and create the bind file:
10362
10363 @smallexample
10364 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
10365 $ gnatbind main_prog
10366 @end smallexample
10367
10368 Note that @code{gnatelim} needs neither object nor ALI files.
10369
10370 @node Running gnatelim
10371 @subsection Running @code{gnatelim}
10372
10373 @noindent
10374 @code{gnatelim} has the following command-line interface:
10375
10376 @smallexample
10377 $ gnatelim @ovar{options} name
10378 @end smallexample
10379
10380 @noindent
10381 @code{name} should be a name of a source file that contains the main subprogram
10382 of a program (partition).
10383
10384 @code{gnatelim} has the following switches:
10385
10386 @table @option
10387 @c !sort!
10388 @item ^-q^/QUIET^
10389 @cindex @option{^-q^/QUIET^} (@command{gnatelim})
10390 Quiet mode: by default @code{gnatelim} outputs to the standard error
10391 stream the number of program units left to be processed. This option turns
10392 this trace off.
10393
10394 @item ^-v^/VERBOSE^
10395 @cindex @option{^-v^/VERBOSE^} (@command{gnatelim})
10396 Verbose mode: @code{gnatelim} version information is printed as Ada
10397 comments to the standard output stream. Also, in addition to the number of
10398 program units left @code{gnatelim} will output the name of the current unit
10399 being processed.
10400
10401 @item ^-a^/ALL^
10402 @cindex @option{^-a^/ALL^} (@command{gnatelim})
10403 Also look for subprograms from the GNAT run time that can be eliminated. Note
10404 that when @file{gnat.adc} is produced using this switch, the entire program
10405 must be recompiled with switch @option{^-a^/ALL_FILES^} to @command{gnatmake}.
10406
10407 @item ^-I^/INCLUDE_DIRS=^@var{dir}
10408 @cindex @option{^-I^/INCLUDE_DIRS^} (@command{gnatelim})
10409 When looking for source files also look in directory @var{dir}. Specifying
10410 @option{^-I-^/INCLUDE_DIRS=-^} instructs @code{gnatelim} not to look for
10411 sources in the current directory.
10412
10413 @item ^-b^/BIND_FILE=^@var{bind_file}
10414 @cindex @option{^-b^/BIND_FILE^} (@command{gnatelim})
10415 Specifies @var{bind_file} as the bind file to process. If not set, the name
10416 of the bind file is computed from the full expanded Ada name
10417 of a main subprogram.
10418
10419 @item ^-C^/CONFIG_FILE=^@var{config_file}
10420 @cindex @option{^-C^/CONFIG_FILE^} (@command{gnatelim})
10421 Specifies a file @var{config_file} that contains configuration pragmas. The
10422 file must be specified with full path.
10423
10424 @item ^--GCC^/COMPILER^=@var{compiler_name}
10425 @cindex @option{^-GCC^/COMPILER^} (@command{gnatelim})
10426 Instructs @code{gnatelim} to use specific @command{gcc} compiler instead of one
10427 available on the path.
10428
10429 @item ^--GNATMAKE^/GNATMAKE^=@var{gnatmake_name}
10430 @cindex @option{^--GNATMAKE^/GNATMAKE^} (@command{gnatelim})
10431 Instructs @code{gnatelim} to use specific @command{gnatmake} instead of one
10432 available on the path.
10433 @end table
10434
10435 @noindent
10436 @code{gnatelim} sends its output to the standard output stream, and all the
10437 tracing and debug information is sent to the standard error stream.
10438 In order to produce a proper GNAT configuration file
10439 @file{gnat.adc}, redirection must be used:
10440
10441 @smallexample
10442 @ifset vms
10443 $ PIPE GNAT ELIM MAIN_PROG.ADB > GNAT.ADC
10444 @end ifset
10445 @ifclear vms
10446 $ gnatelim main_prog.adb > gnat.adc
10447 @end ifclear
10448 @end smallexample
10449
10450 @ifclear vms
10451 @noindent
10452 or
10453
10454 @smallexample
10455 $ gnatelim main_prog.adb >> gnat.adc
10456 @end smallexample
10457
10458 @noindent
10459 in order to append the @code{gnatelim} output to the existing contents of
10460 @file{gnat.adc}.
10461 @end ifclear
10462
10463 @node Correcting the List of Eliminate Pragmas
10464 @subsection Correcting the List of Eliminate Pragmas
10465
10466 @noindent
10467 In some rare cases @code{gnatelim} may try to eliminate
10468 subprograms that are actually called in the program. In this case, the
10469 compiler will generate an error message of the form:
10470
10471 @smallexample
10472 file.adb:106:07: cannot call eliminated subprogram "My_Prog"
10473 @end smallexample
10474
10475 @noindent
10476 You will need to manually remove the wrong @code{Eliminate} pragmas from
10477 the @file{gnat.adc} file. You should recompile your program
10478 from scratch after that, because you need a consistent @file{gnat.adc} file
10479 during the entire compilation.
10480
10481 @node Making Your Executables Smaller
10482 @subsection Making Your Executables Smaller
10483
10484 @noindent
10485 In order to get a smaller executable for your program you now have to
10486 recompile the program completely with the new @file{gnat.adc} file
10487 created by @code{gnatelim} in your current directory:
10488
10489 @smallexample
10490 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
10491 @end smallexample
10492
10493 @noindent
10494 (Use the @option{^-f^/FORCE_COMPILE^} option for @command{gnatmake} to
10495 recompile everything
10496 with the set of pragmas @code{Eliminate} that you have obtained with
10497 @command{gnatelim}).
10498
10499 Be aware that the set of @code{Eliminate} pragmas is specific to each
10500 program. It is not recommended to merge sets of @code{Eliminate}
10501 pragmas created for different programs in one @file{gnat.adc} file.
10502
10503 @node Summary of the gnatelim Usage Cycle
10504 @subsection Summary of the gnatelim Usage Cycle
10505
10506 @noindent
10507 Here is a quick summary of the steps to be taken in order to reduce
10508 the size of your executables with @code{gnatelim}. You may use
10509 other GNAT options to control the optimization level,
10510 to produce the debugging information, to set search path, etc.
10511
10512 @enumerate
10513 @item
10514 Produce a bind file
10515
10516 @smallexample
10517 $ gnatmake ^-c main_prog^/ACTIONS=COMPILE MAIN_PROG^
10518 $ gnatbind main_prog
10519 @end smallexample
10520
10521 @item
10522 Generate a list of @code{Eliminate} pragmas
10523 @smallexample
10524 @ifset vms
10525 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
10526 @end ifset
10527 @ifclear vms
10528 $ gnatelim main_prog >@r{[}>@r{]} gnat.adc
10529 @end ifclear
10530 @end smallexample
10531
10532 @item
10533 Recompile the application
10534
10535 @smallexample
10536 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
10537 @end smallexample
10538
10539 @end enumerate
10540
10541 @node Reducing Size of Executables with unused subprogram/data elimination
10542 @section Reducing Size of Executables with Unused Subprogram/Data Elimination
10543 @findex unused subprogram/data elimination
10544
10545 @noindent
10546 This section describes how you can eliminate unused subprograms and data from
10547 your executable just by setting options at compilation time.
10548
10549 @menu
10550 * About unused subprogram/data elimination::
10551 * Compilation options::
10552 * Example of unused subprogram/data elimination::
10553 @end menu
10554
10555 @node About unused subprogram/data elimination
10556 @subsection About unused subprogram/data elimination
10557
10558 @noindent
10559 By default, an executable contains all code and data of its composing objects
10560 (directly linked or coming from statically linked libraries), even data or code
10561 never used by this executable.
10562
10563 This feature will allow you to eliminate such unused code from your
10564 executable, making it smaller (in disk and in memory).
10565
10566 This functionality is available on all Linux platforms except for the IA-64
10567 architecture and on all cross platforms using the ELF binary file format.
10568 In both cases GNU binutils version 2.16 or later are required to enable it.
10569
10570 @node Compilation options
10571 @subsection Compilation options
10572
10573 @noindent
10574 The operation of eliminating the unused code and data from the final executable
10575 is directly performed by the linker.
10576
10577 In order to do this, it has to work with objects compiled with the
10578 following options:
10579 @option{-ffunction-sections} @option{-fdata-sections}.
10580 @cindex @option{-ffunction-sections} (@command{gcc})
10581 @cindex @option{-fdata-sections} (@command{gcc})
10582 These options are usable with C and Ada files.
10583 They will place respectively each
10584 function or data in a separate section in the resulting object file.
10585
10586 Once the objects and static libraries are created with these options, the
10587 linker can perform the dead code elimination. You can do this by setting
10588 the @option{-Wl,--gc-sections} option to gcc command or in the
10589 @option{-largs} section of @command{gnatmake}. This will perform a
10590 garbage collection of code and data never referenced.
10591
10592 If the linker performs a partial link (@option{-r} ld linker option), then you
10593 will need to provide one or several entry point using the
10594 @option{-e} / @option{--entry} ld option.
10595
10596 Note that objects compiled without the @option{-ffunction-sections} and
10597 @option{-fdata-sections} options can still be linked with the executable.
10598 However, no dead code elimination will be performed on those objects (they will
10599 be linked as is).
10600
10601 The GNAT static library is now compiled with -ffunction-sections and
10602 -fdata-sections on some platforms. This allows you to eliminate the unused code
10603 and data of the GNAT library from your executable.
10604
10605 @node Example of unused subprogram/data elimination
10606 @subsection Example of unused subprogram/data elimination
10607
10608 @noindent
10609 Here is a simple example:
10610
10611 @smallexample @c ada
10612 with Aux;
10613
10614 procedure Test is
10615 begin
10616    Aux.Used (10);
10617 end Test;
10618
10619 package Aux is
10620    Used_Data   : Integer;
10621    Unused_Data : Integer;
10622
10623    procedure Used   (Data : Integer);
10624    procedure Unused (Data : Integer);
10625 end Aux;
10626
10627 package body Aux is
10628    procedure Used (Data : Integer) is
10629    begin
10630       Used_Data := Data;
10631    end Used;
10632
10633    procedure Unused (Data : Integer) is
10634    begin
10635       Unused_Data := Data;
10636    end Unused;
10637 end Aux;
10638 @end smallexample
10639
10640 @noindent
10641 @code{Unused} and @code{Unused_Data} are never referenced in this code
10642 excerpt, and hence they may be safely removed from the final executable.
10643
10644 @smallexample
10645 $ gnatmake test
10646
10647 $ nm test | grep used
10648 020015f0 T aux__unused
10649 02005d88 B aux__unused_data
10650 020015cc T aux__used
10651 02005d84 B aux__used_data
10652
10653 $ gnatmake test -cargs -fdata-sections -ffunction-sections \
10654      -largs -Wl,--gc-sections
10655
10656 $ nm test | grep used
10657 02005350 T aux__used
10658 0201ffe0 B aux__used_data
10659 @end smallexample
10660
10661 @noindent
10662 It can be observed that the procedure @code{Unused} and the object
10663 @code{Unused_Data} are removed by the linker when using the
10664 appropriate options.
10665
10666 @c ********************************
10667 @node Renaming Files Using gnatchop
10668 @chapter Renaming Files Using @code{gnatchop}
10669 @findex gnatchop
10670
10671 @noindent
10672 This chapter discusses how to handle files with multiple units by using
10673 the @code{gnatchop} utility. This utility is also useful in renaming
10674 files to meet the standard GNAT default file naming conventions.
10675
10676 @menu
10677 * Handling Files with Multiple Units::
10678 * Operating gnatchop in Compilation Mode::
10679 * Command Line for gnatchop::
10680 * Switches for gnatchop::
10681 * Examples of gnatchop Usage::
10682 @end menu
10683
10684 @node Handling Files with Multiple Units
10685 @section Handling Files with Multiple Units
10686
10687 @noindent
10688 The basic compilation model of GNAT requires that a file submitted to the
10689 compiler have only one unit and there be a strict correspondence
10690 between the file name and the unit name.
10691
10692 The @code{gnatchop} utility allows both of these rules to be relaxed,
10693 allowing GNAT to process files which contain multiple compilation units
10694 and files with arbitrary file names. @code{gnatchop}
10695 reads the specified file and generates one or more output files,
10696 containing one unit per file. The unit and the file name correspond,
10697 as required by GNAT.
10698
10699 If you want to permanently restructure a set of ``foreign'' files so that
10700 they match the GNAT rules, and do the remaining development using the
10701 GNAT structure, you can simply use @command{gnatchop} once, generate the
10702 new set of files and work with them from that point on.
10703
10704 Alternatively, if you want to keep your files in the ``foreign'' format,
10705 perhaps to maintain compatibility with some other Ada compilation
10706 system, you can set up a procedure where you use @command{gnatchop} each
10707 time you compile, regarding the source files that it writes as temporary
10708 files that you throw away.
10709
10710 Note that if your file containing multiple units starts with a byte order
10711 mark (BOM) specifying UTF-8 encoding, then the files generated by gnatchop
10712 will each start with a copy of this BOM, meaning that they can be compiled
10713 automatically in UTF-8 mode without needing to specify an explicit encoding.
10714
10715 @node Operating gnatchop in Compilation Mode
10716 @section Operating gnatchop in Compilation Mode
10717
10718 @noindent
10719 The basic function of @code{gnatchop} is to take a file with multiple units
10720 and split it into separate files. The boundary between files is reasonably
10721 clear, except for the issue of comments and pragmas. In default mode, the
10722 rule is that any pragmas between units belong to the previous unit, except
10723 that configuration pragmas always belong to the following unit. Any comments
10724 belong to the following unit. These rules
10725 almost always result in the right choice of
10726 the split point without needing to mark it explicitly and most users will
10727 find this default to be what they want. In this default mode it is incorrect to
10728 submit a file containing only configuration pragmas, or one that ends in
10729 configuration pragmas, to @code{gnatchop}.
10730
10731 However, using a special option to activate ``compilation mode'',
10732 @code{gnatchop}
10733 can perform another function, which is to provide exactly the semantics
10734 required by the RM for handling of configuration pragmas in a compilation.
10735 In the absence of configuration pragmas (at the main file level), this
10736 option has no effect, but it causes such configuration pragmas to be handled
10737 in a quite different manner.
10738
10739 First, in compilation mode, if @code{gnatchop} is given a file that consists of
10740 only configuration pragmas, then this file is appended to the
10741 @file{gnat.adc} file in the current directory. This behavior provides
10742 the required behavior described in the RM for the actions to be taken
10743 on submitting such a file to the compiler, namely that these pragmas
10744 should apply to all subsequent compilations in the same compilation
10745 environment. Using GNAT, the current directory, possibly containing a
10746 @file{gnat.adc} file is the representation
10747 of a compilation environment. For more information on the
10748 @file{gnat.adc} file, see @ref{Handling of Configuration Pragmas}.
10749
10750 Second, in compilation mode, if @code{gnatchop}
10751 is given a file that starts with
10752 configuration pragmas, and contains one or more units, then these
10753 configuration pragmas are prepended to each of the chopped files. This
10754 behavior provides the required behavior described in the RM for the
10755 actions to be taken on compiling such a file, namely that the pragmas
10756 apply to all units in the compilation, but not to subsequently compiled
10757 units.
10758
10759 Finally, if configuration pragmas appear between units, they are appended
10760 to the previous unit. This results in the previous unit being illegal,
10761 since the compiler does not accept configuration pragmas that follow
10762 a unit. This provides the required RM behavior that forbids configuration
10763 pragmas other than those preceding the first compilation unit of a
10764 compilation.
10765
10766 For most purposes, @code{gnatchop} will be used in default mode. The
10767 compilation mode described above is used only if you need exactly
10768 accurate behavior with respect to compilations, and you have files
10769 that contain multiple units and configuration pragmas. In this
10770 circumstance the use of @code{gnatchop} with the compilation mode
10771 switch provides the required behavior, and is for example the mode
10772 in which GNAT processes the ACVC tests.
10773
10774 @node Command Line for gnatchop
10775 @section Command Line for @code{gnatchop}
10776
10777 @noindent
10778 The @code{gnatchop} command has the form:
10779
10780 @smallexample
10781 $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
10782       @ovar{directory}
10783 @end smallexample
10784
10785 @noindent
10786 The only required argument is the file name of the file to be chopped.
10787 There are no restrictions on the form of this file name. The file itself
10788 contains one or more Ada units, in normal GNAT format, concatenated
10789 together. As shown, more than one file may be presented to be chopped.
10790
10791 When run in default mode, @code{gnatchop} generates one output file in
10792 the current directory for each unit in each of the files.
10793
10794 @var{directory}, if specified, gives the name of the directory to which
10795 the output files will be written. If it is not specified, all files are
10796 written to the current directory.
10797
10798 For example, given a
10799 file called @file{hellofiles} containing
10800
10801 @smallexample @c ada
10802 @group
10803 @cartouche
10804 procedure hello;
10805
10806 with Text_IO; use Text_IO;
10807 procedure hello is
10808 begin
10809    Put_Line ("Hello");
10810 end hello;
10811 @end cartouche
10812 @end group
10813 @end smallexample
10814
10815 @noindent
10816 the command
10817
10818 @smallexample
10819 $ gnatchop ^hellofiles^HELLOFILES.^
10820 @end smallexample
10821
10822 @noindent
10823 generates two files in the current directory, one called
10824 @file{hello.ads} containing the single line that is the procedure spec,
10825 and the other called @file{hello.adb} containing the remaining text. The
10826 original file is not affected. The generated files can be compiled in
10827 the normal manner.
10828
10829 @noindent
10830 When gnatchop is invoked on a file that is empty or that contains only empty
10831 lines and/or comments, gnatchop will not fail, but will not produce any
10832 new sources.
10833
10834 For example, given a
10835 file called @file{toto.txt} containing
10836
10837 @smallexample @c ada
10838 @group
10839 @cartouche
10840 --  Just a comment
10841 @end cartouche
10842 @end group
10843 @end smallexample
10844
10845 @noindent
10846 the command
10847
10848 @smallexample
10849 $ gnatchop ^toto.txt^TOT.TXT^
10850 @end smallexample
10851
10852 @noindent
10853 will not produce any new file and will result in the following warnings:
10854
10855 @smallexample
10856 toto.txt:1:01: warning: empty file, contains no compilation units
10857 no compilation units found
10858 no source files written
10859 @end smallexample
10860
10861 @node Switches for gnatchop
10862 @section Switches for @code{gnatchop}
10863
10864 @noindent
10865 @command{gnatchop} recognizes the following switches:
10866
10867 @table @option
10868 @c !sort!
10869
10870 @item --version
10871 @cindex @option{--version} @command{gnatchop}
10872 Display Copyright and version, then exit disregarding all other options.
10873
10874 @item --help
10875 @cindex @option{--help} @command{gnatchop}
10876 If @option{--version} was not used, display usage, then exit disregarding
10877 all other options.
10878
10879 @item ^-c^/COMPILATION^
10880 @cindex @option{^-c^/COMPILATION^} (@code{gnatchop})
10881 Causes @code{gnatchop} to operate in compilation mode, in which
10882 configuration pragmas are handled according to strict RM rules. See
10883 previous section for a full description of this mode.
10884
10885 @ifclear vms
10886 @item -gnat@var{xxx}
10887 This passes the given @option{-gnat@var{xxx}} switch to @code{gnat} which is
10888 used to parse the given file. Not all @var{xxx} options make sense,
10889 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
10890 process a source file that uses Latin-2 coding for identifiers.
10891 @end ifclear
10892
10893 @item ^-h^/HELP^
10894 Causes @code{gnatchop} to generate a brief help summary to the standard
10895 output file showing usage information.
10896
10897 @item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^
10898 @cindex @option{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop})
10899 Limit generated file names to the specified number @code{mm}
10900 of characters.
10901 This is useful if the
10902 resulting set of files is required to be interoperable with systems
10903 which limit the length of file names.
10904 @ifset vms
10905 If no value is given, or
10906 if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given,
10907 a default of 39, suitable for OpenVMS Alpha
10908 Systems, is assumed
10909 @end ifset
10910 @ifclear vms
10911 No space is allowed between the @option{-k} and the numeric value. The numeric
10912 value may be omitted in which case a default of @option{-k8},
10913 suitable for use
10914 with DOS-like file systems, is used. If no @option{-k} switch
10915 is present then
10916 there is no limit on the length of file names.
10917 @end ifclear
10918
10919 @item ^-p^/PRESERVE^
10920 @cindex @option{^-p^/PRESERVE^} (@code{gnatchop})
10921 Causes the file ^modification^creation^ time stamp of the input file to be
10922 preserved and used for the time stamp of the output file(s). This may be
10923 useful for preserving coherency of time stamps in an environment where
10924 @code{gnatchop} is used as part of a standard build process.
10925
10926 @item ^-q^/QUIET^
10927 @cindex @option{^-q^/QUIET^} (@code{gnatchop})
10928 Causes output of informational messages indicating the set of generated
10929 files to be suppressed. Warnings and error messages are unaffected.
10930
10931 @item ^-r^/REFERENCE^
10932 @cindex @option{^-r^/REFERENCE^} (@code{gnatchop})
10933 @findex Source_Reference
10934 Generate @code{Source_Reference} pragmas. Use this switch if the output
10935 files are regarded as temporary and development is to be done in terms
10936 of the original unchopped file. This switch causes
10937 @code{Source_Reference} pragmas to be inserted into each of the
10938 generated files to refers back to the original file name and line number.
10939 The result is that all error messages refer back to the original
10940 unchopped file.
10941 In addition, the debugging information placed into the object file (when
10942 the @option{^-g^/DEBUG^} switch of @command{gcc} or @command{gnatmake} is
10943 specified)
10944 also refers back to this original file so that tools like profilers and
10945 debuggers will give information in terms of the original unchopped file.
10946
10947 If the original file to be chopped itself contains
10948 a @code{Source_Reference}
10949 pragma referencing a third file, then gnatchop respects
10950 this pragma, and the generated @code{Source_Reference} pragmas
10951 in the chopped file refer to the original file, with appropriate
10952 line numbers. This is particularly useful when @code{gnatchop}
10953 is used in conjunction with @code{gnatprep} to compile files that
10954 contain preprocessing statements and multiple units.
10955
10956 @item ^-v^/VERBOSE^
10957 @cindex @option{^-v^/VERBOSE^} (@code{gnatchop})
10958 Causes @code{gnatchop} to operate in verbose mode. The version
10959 number and copyright notice are output, as well as exact copies of
10960 the gnat1 commands spawned to obtain the chop control information.
10961
10962 @item ^-w^/OVERWRITE^
10963 @cindex @option{^-w^/OVERWRITE^} (@code{gnatchop})
10964 Overwrite existing file names. Normally @code{gnatchop} regards it as a
10965 fatal error if there is already a file with the same name as a
10966 file it would otherwise output, in other words if the files to be
10967 chopped contain duplicated units. This switch bypasses this
10968 check, and causes all but the last instance of such duplicated
10969 units to be skipped.
10970
10971 @ifclear vms
10972 @item --GCC=@var{xxxx}
10973 @cindex @option{--GCC=} (@code{gnatchop})
10974 Specify the path of the GNAT parser to be used. When this switch is used,
10975 no attempt is made to add the prefix to the GNAT parser executable.
10976 @end ifclear
10977 @end table
10978
10979 @node Examples of gnatchop Usage
10980 @section Examples of @code{gnatchop} Usage
10981
10982 @table @code
10983 @ifset vms
10984 @item gnatchop /OVERWRITE HELLO_S.ADA [PRERELEASE.FILES]
10985 @end ifset
10986 @ifclear vms
10987 @item gnatchop -w hello_s.ada prerelease/files
10988 @end ifclear
10989
10990 Chops the source file @file{hello_s.ada}. The output files will be
10991 placed in the directory @file{^prerelease/files^[PRERELEASE.FILES]^},
10992 overwriting any
10993 files with matching names in that directory (no files in the current
10994 directory are modified).
10995
10996 @item gnatchop ^archive^ARCHIVE.^
10997 Chops the source file @file{^archive^ARCHIVE.^}
10998 into the current directory. One
10999 useful application of @code{gnatchop} is in sending sets of sources
11000 around, for example in email messages. The required sources are simply
11001 concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^
11002 command), and then
11003 @command{gnatchop} is used at the other end to reconstitute the original
11004 file names.
11005
11006 @item gnatchop file1 file2 file3 direc
11007 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
11008 the resulting files in the directory @file{direc}. Note that if any units
11009 occur more than once anywhere within this set of files, an error message
11010 is generated, and no files are written. To override this check, use the
11011 @option{^-w^/OVERWRITE^} switch,
11012 in which case the last occurrence in the last file will
11013 be the one that is output, and earlier duplicate occurrences for a given
11014 unit will be skipped.
11015 @end table
11016
11017 @node Configuration Pragmas
11018 @chapter Configuration Pragmas
11019 @cindex Configuration pragmas
11020 @cindex Pragmas, configuration
11021
11022 @noindent
11023 Configuration pragmas include those pragmas described as
11024 such in the Ada Reference Manual, as well as
11025 implementation-dependent pragmas that are configuration pragmas.
11026 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
11027 for details on these additional GNAT-specific configuration pragmas.
11028 Most notably, the pragma @code{Source_File_Name}, which allows
11029 specifying non-default names for source files, is a configuration
11030 pragma. The following is a complete list of configuration pragmas
11031 recognized by GNAT:
11032
11033 @smallexample
11034    Ada_83
11035    Ada_95
11036    Ada_05
11037    Ada_2005
11038    Assertion_Policy
11039    C_Pass_By_Copy
11040    Check_Name
11041    Check_Policy
11042    Compile_Time_Error
11043    Compile_Time_Warning
11044    Compiler_Unit
11045    Component_Alignment
11046    Debug_Policy
11047    Detect_Blocking
11048    Discard_Names
11049    Elaboration_Checks
11050    Eliminate
11051    Extend_System
11052    External_Name_Casing
11053    Fast_Math
11054    Favor_Top_Level
11055    Float_Representation
11056    Implicit_Packing
11057    Initialize_Scalars
11058    Interrupt_State
11059    License
11060    Locking_Policy
11061    Long_Float
11062    No_Run_Time
11063    No_Strict_Aliasing
11064    Normalize_Scalars
11065    Optimize_Alignment
11066    Persistent_BSS
11067    Polling
11068    Priority_Specific_Dispatching
11069    Profile
11070    Profile_Warnings
11071    Propagate_Exceptions
11072    Queuing_Policy
11073    Ravenscar
11074    Restricted_Run_Time
11075    Restrictions
11076    Restrictions_Warnings
11077    Reviewable
11078    Source_File_Name
11079    Source_File_Name_Project
11080    Style_Checks
11081    Suppress
11082    Suppress_Exception_Locations
11083    Task_Dispatching_Policy
11084    Universal_Data
11085    Unsuppress
11086    Use_VADS_Size
11087    Validity_Checks
11088    Warnings
11089    Wide_Character_Encoding
11090
11091 @end smallexample
11092
11093 @menu
11094 * Handling of Configuration Pragmas::
11095 * The Configuration Pragmas Files::
11096 @end menu
11097
11098 @node Handling of Configuration Pragmas
11099 @section Handling of Configuration Pragmas
11100
11101 Configuration pragmas may either appear at the start of a compilation
11102 unit, in which case they apply only to that unit, or they may apply to
11103 all compilations performed in a given compilation environment.
11104
11105 GNAT also provides the @code{gnatchop} utility to provide an automatic
11106 way to handle configuration pragmas following the semantics for
11107 compilations (that is, files with multiple units), described in the RM.
11108 See @ref{Operating gnatchop in Compilation Mode} for details.
11109 However, for most purposes, it will be more convenient to edit the
11110 @file{gnat.adc} file that contains configuration pragmas directly,
11111 as described in the following section.
11112
11113 @node The Configuration Pragmas Files
11114 @section The Configuration Pragmas Files
11115 @cindex @file{gnat.adc}
11116
11117 @noindent
11118 In GNAT a compilation environment is defined by the current
11119 directory at the time that a compile command is given. This current
11120 directory is searched for a file whose name is @file{gnat.adc}. If
11121 this file is present, it is expected to contain one or more
11122 configuration pragmas that will be applied to the current compilation.
11123 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
11124 considered.
11125
11126 Configuration pragmas may be entered into the @file{gnat.adc} file
11127 either by running @code{gnatchop} on a source file that consists only of
11128 configuration pragmas, or more conveniently  by
11129 direct editing of the @file{gnat.adc} file, which is a standard format
11130 source file.
11131
11132 In addition to @file{gnat.adc}, additional files containing configuration
11133 pragmas may be applied to the current compilation using the switch
11134 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
11135 contains only configuration pragmas. These configuration pragmas are
11136 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
11137 is present and switch @option{-gnatA} is not used).
11138
11139 It is allowed to specify several switches @option{-gnatec}, all of which
11140 will be taken into account.
11141
11142 If you are using project file, a separate mechanism is provided using
11143 project attributes, see @ref{Specifying Configuration Pragmas} for more
11144 details.
11145
11146 @ifset vms
11147 Of special interest to GNAT OpenVMS Alpha is the following
11148 configuration pragma:
11149
11150 @smallexample @c ada
11151 @cartouche
11152 pragma Extend_System (Aux_DEC);
11153 @end cartouche
11154 @end smallexample
11155
11156 @noindent
11157 In the presence of this pragma, GNAT adds to the definition of the
11158 predefined package SYSTEM all the additional types and subprograms that are
11159 defined in HP Ada. See @ref{Compatibility with HP Ada} for details.
11160 @end ifset
11161
11162 @node Handling Arbitrary File Naming Conventions Using gnatname
11163 @chapter Handling Arbitrary File Naming Conventions Using @code{gnatname}
11164 @cindex Arbitrary File Naming Conventions
11165
11166 @menu
11167 * Arbitrary File Naming Conventions::
11168 * Running gnatname::
11169 * Switches for gnatname::
11170 * Examples of gnatname Usage::
11171 @end menu
11172
11173 @node Arbitrary File Naming Conventions
11174 @section Arbitrary File Naming Conventions
11175
11176 @noindent
11177 The GNAT compiler must be able to know the source file name of a compilation
11178 unit.  When using the standard GNAT default file naming conventions
11179 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
11180 does not need additional information.
11181
11182 @noindent
11183 When the source file names do not follow the standard GNAT default file naming
11184 conventions, the GNAT compiler must be given additional information through
11185 a configuration pragmas file (@pxref{Configuration Pragmas})
11186 or a project file.
11187 When the non-standard file naming conventions are well-defined,
11188 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
11189 (@pxref{Alternative File Naming Schemes}) may be sufficient. However,
11190 if the file naming conventions are irregular or arbitrary, a number
11191 of pragma @code{Source_File_Name} for individual compilation units
11192 must be defined.
11193 To help maintain the correspondence between compilation unit names and
11194 source file names within the compiler,
11195 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
11196 set of files.
11197
11198 @node Running gnatname
11199 @section Running @code{gnatname}
11200
11201 @noindent
11202 The usual form of the @code{gnatname} command is
11203
11204 @smallexample
11205 $ gnatname @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}
11206       @r{[}--and @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}@r{]}
11207 @end smallexample
11208
11209 @noindent
11210 All of the arguments are optional. If invoked without any argument,
11211 @code{gnatname} will display its usage.
11212
11213 @noindent
11214 When used with at least one naming pattern, @code{gnatname} will attempt to
11215 find all the compilation units in files that follow at least one of the
11216 naming patterns. To find these compilation units,
11217 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
11218 regular files.
11219
11220 @noindent
11221 One or several Naming Patterns may be given as arguments to @code{gnatname}.
11222 Each Naming Pattern is enclosed between double quotes.
11223 A Naming Pattern is a regular expression similar to the wildcard patterns
11224 used in file names by the Unix shells or the DOS prompt.
11225
11226 @noindent
11227 @code{gnatname} may be called with several sections of directories/patterns.
11228 Sections are separated by switch @code{--and}. In each section, there must be
11229 at least one pattern. If no directory is specified in a section, the current
11230 directory (or the project directory is @code{-P} is used) is implied.
11231 The options other that the directory switches and the patterns apply globally
11232 even if they are in different sections.
11233
11234 @noindent
11235 Examples of Naming Patterns are
11236
11237 @smallexample
11238    "*.[12].ada"
11239    "*.ad[sb]*"
11240    "body_*"    "spec_*"
11241 @end smallexample
11242
11243 @noindent
11244 For a more complete description of the syntax of Naming Patterns,
11245 see the second kind of regular expressions described in @file{g-regexp.ads}
11246 (the ``Glob'' regular expressions).
11247
11248 @noindent
11249 When invoked with no switch @code{-P}, @code{gnatname} will create a
11250 configuration pragmas file @file{gnat.adc} in the current working directory,
11251 with pragmas @code{Source_File_Name} for each file that contains a valid Ada
11252 unit.
11253
11254 @node Switches for gnatname
11255 @section Switches for @code{gnatname}
11256
11257 @noindent
11258 Switches for @code{gnatname} must precede any specified Naming Pattern.
11259
11260 @noindent
11261 You may specify any of the following switches to @code{gnatname}:
11262
11263 @table @option
11264 @c !sort!
11265
11266 @item --version
11267 @cindex @option{--version} @command{gnatname}
11268 Display Copyright and version, then exit disregarding all other options.
11269
11270 @item --help
11271 @cindex @option{--help} @command{gnatname}
11272 If @option{--version} was not used, display usage, then exit disregarding
11273 all other options.
11274
11275 @item --and
11276 Start another section of directories/patterns.
11277
11278 @item ^-c^/CONFIG_FILE=^@file{file}
11279 @cindex @option{^-c^/CONFIG_FILE^} (@code{gnatname})
11280 Create a configuration pragmas file @file{file} (instead of the default
11281 @file{gnat.adc}).
11282 @ifclear vms
11283 There may be zero, one or more space between @option{-c} and
11284 @file{file}.
11285 @end ifclear
11286 @file{file} may include directory information. @file{file} must be
11287 writable. There may be only one switch @option{^-c^/CONFIG_FILE^}.
11288 When a switch @option{^-c^/CONFIG_FILE^} is
11289 specified, no switch @option{^-P^/PROJECT_FILE^} may be specified (see below).
11290
11291 @item ^-d^/SOURCE_DIRS=^@file{dir}
11292 @cindex @option{^-d^/SOURCE_DIRS^} (@code{gnatname})
11293 Look for source files in directory @file{dir}. There may be zero, one or more
11294 spaces between @option{^-d^/SOURCE_DIRS=^} and @file{dir}.
11295 When a switch @option{^-d^/SOURCE_DIRS^}
11296 is specified, the current working directory will not be searched for source
11297 files, unless it is explicitly specified with a @option{^-d^/SOURCE_DIRS^}
11298 or @option{^-D^/DIR_FILES^} switch.
11299 Several switches @option{^-d^/SOURCE_DIRS^} may be specified.
11300 If @file{dir} is a relative path, it is relative to the directory of
11301 the configuration pragmas file specified with switch
11302 @option{^-c^/CONFIG_FILE^},
11303 or to the directory of the project file specified with switch
11304 @option{^-P^/PROJECT_FILE^} or,
11305 if neither switch @option{^-c^/CONFIG_FILE^}
11306 nor switch @option{^-P^/PROJECT_FILE^} are specified, it is relative to the
11307 current working directory. The directory
11308 specified with switch @option{^-d^/SOURCE_DIRS^} must exist and be readable.
11309
11310 @item ^-D^/DIRS_FILE=^@file{file}
11311 @cindex @option{^-D^/DIRS_FILE^} (@code{gnatname})
11312 Look for source files in all directories listed in text file @file{file}.
11313 There may be zero, one or more spaces between @option{^-D^/DIRS_FILE=^}
11314 and @file{file}.
11315 @file{file} must be an existing, readable text file.
11316 Each nonempty line in @file{file} must be a directory.
11317 Specifying switch @option{^-D^/DIRS_FILE^} is equivalent to specifying as many
11318 switches @option{^-d^/SOURCE_DIRS^} as there are nonempty lines in
11319 @file{file}.
11320
11321 @item ^-f^/FOREIGN_PATTERN=^@file{pattern}
11322 @cindex @option{^-f^/FOREIGN_PATTERN^} (@code{gnatname})
11323 Foreign patterns. Using this switch, it is possible to add sources of languages
11324 other than Ada to the list of sources of a project file.
11325 It is only useful if a ^-P^/PROJECT_FILE^ switch is used.
11326 For example,
11327 @smallexample
11328 gnatname ^-Pprj -f"*.c"^/PROJECT_FILE=PRJ /FOREIGN_PATTERN=*.C^ "*.ada"
11329 @end smallexample
11330 @noindent
11331 will look for Ada units in all files with the @file{.ada} extension,
11332 and will add to the list of file for project @file{prj.gpr} the C files
11333 with extension @file{.^c^C^}.
11334
11335 @item ^-h^/HELP^
11336 @cindex @option{^-h^/HELP^} (@code{gnatname})
11337 Output usage (help) information. The output is written to @file{stdout}.
11338
11339 @item ^-P^/PROJECT_FILE=^@file{proj}
11340 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatname})
11341 Create or update project file @file{proj}. There may be zero, one or more space
11342 between @option{-P} and @file{proj}. @file{proj} may include directory
11343 information. @file{proj} must be writable.
11344 There may be only one switch @option{^-P^/PROJECT_FILE^}.
11345 When a switch @option{^-P^/PROJECT_FILE^} is specified,
11346 no switch @option{^-c^/CONFIG_FILE^} may be specified.
11347
11348 @item ^-v^/VERBOSE^
11349 @cindex @option{^-v^/VERBOSE^} (@code{gnatname})
11350 Verbose mode. Output detailed explanation of behavior to @file{stdout}.
11351 This includes name of the file written, the name of the directories to search
11352 and, for each file in those directories whose name matches at least one of
11353 the Naming Patterns, an indication of whether the file contains a unit,
11354 and if so the name of the unit.
11355
11356 @item ^-v -v^/VERBOSE /VERBOSE^
11357 @cindex @option{^-v -v^/VERBOSE /VERBOSE^} (@code{gnatname})
11358 Very Verbose mode. In addition to the output produced in verbose mode,
11359 for each file in the searched directories whose name matches none of
11360 the Naming Patterns, an indication is given that there is no match.
11361
11362 @item ^-x^/EXCLUDED_PATTERN=^@file{pattern}
11363 @cindex @option{^-x^/EXCLUDED_PATTERN^} (@code{gnatname})
11364 Excluded patterns. Using this switch, it is possible to exclude some files
11365 that would match the name patterns. For example,
11366 @smallexample
11367 gnatname ^-x "*_nt.ada"^/EXCLUDED_PATTERN=*_nt.ada^ "*.ada"
11368 @end smallexample
11369 @noindent
11370 will look for Ada units in all files with the @file{.ada} extension,
11371 except those whose names end with @file{_nt.ada}.
11372
11373 @end table
11374
11375 @node Examples of gnatname Usage
11376 @section Examples of @code{gnatname} Usage
11377
11378 @ifset vms
11379 @smallexample
11380 $ gnatname /CONFIG_FILE=[HOME.ME]NAMES.ADC /SOURCE_DIRS=SOURCES "[a-z]*.ada*"
11381 @end smallexample
11382 @end ifset
11383
11384 @ifclear vms
11385 @smallexample
11386 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
11387 @end smallexample
11388 @end ifclear
11389
11390 @noindent
11391 In this example, the directory @file{^/home/me^[HOME.ME]^} must already exist
11392 and be writable. In addition, the directory
11393 @file{^/home/me/sources^[HOME.ME.SOURCES]^} (specified by
11394 @option{^-d sources^/SOURCE_DIRS=SOURCES^}) must exist and be readable.
11395
11396 @ifclear vms
11397 Note the optional spaces after @option{-c} and @option{-d}.
11398 @end ifclear
11399
11400 @smallexample
11401 @ifclear vms
11402 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
11403   -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
11404 @end ifclear
11405 @ifset vms
11406 $ gnatname  /PROJECT_FILE=[HOME.ME]PROJ
11407   /EXCLUDED_PATTERN=*_nt_body.ada
11408   /SOURCE_DIRS=(SOURCES,[SOURCES.PLUS])
11409   /DIRS_FILE=COMMON_DIRS.TXT "body_*" "spec_*"
11410 @end ifset
11411 @end smallexample
11412
11413 Note that several switches @option{^-d^/SOURCE_DIRS^} may be used,
11414 even in conjunction with one or several switches
11415 @option{^-D^/DIRS_FILE^}. Several Naming Patterns and one excluded pattern
11416 are used in this example.
11417
11418 @c *****************************************
11419 @c * G N A T  P r o j e c t  M a n a g e r *
11420 @c *****************************************
11421 @node GNAT Project Manager
11422 @chapter GNAT Project Manager
11423
11424 @menu
11425 * Introduction::
11426 * Examples of Project Files::
11427 * Project File Syntax::
11428 * Objects and Sources in Project Files::
11429 * Importing Projects::
11430 * Project Extension::
11431 * Project Hierarchy Extension::
11432 * External References in Project Files::
11433 * Packages in Project Files::
11434 * Variables from Imported Projects::
11435 * Naming Schemes::
11436 * Library Projects::
11437 * Stand-alone Library Projects::
11438 * Switches Related to Project Files::
11439 * Tools Supporting Project Files::
11440 * An Extended Example::
11441 * Project File Complete Syntax::
11442 @end menu
11443
11444 @c ****************
11445 @c * Introduction *
11446 @c ****************
11447
11448 @node Introduction
11449 @section Introduction
11450
11451 @noindent
11452 This chapter describes GNAT's @emph{Project Manager}, a facility that allows
11453 you to manage complex builds involving a number of source files, directories,
11454 and compilation options for different system configurations. In particular,
11455 project files allow you to specify:
11456 @itemize @bullet
11457 @item
11458 The directory or set of directories containing the source files, and/or the
11459 names of the specific source files themselves
11460 @item
11461 The directory in which the compiler's output
11462 (@file{ALI} files, object files, tree files) is to be placed
11463 @item
11464 The directory in which the executable programs is to be placed
11465 @item
11466 ^Switch^Switch^ settings for any of the project-enabled tools
11467 (@command{gnatmake}, compiler, binder, linker, @code{gnatls}, @code{gnatxref},
11468 @code{gnatfind}); you can apply these settings either globally or to individual
11469 compilation units.
11470 @item
11471 The source files containing the main subprogram(s) to be built
11472 @item
11473 The source programming language(s) (currently Ada and/or C)
11474 @item
11475 Source file naming conventions; you can specify these either globally or for
11476 individual compilation units
11477 @end itemize
11478
11479 @menu
11480 * Project Files::
11481 @end menu
11482
11483 @node Project Files
11484 @subsection Project Files
11485
11486 @noindent
11487 Project files are written in a syntax close to that of Ada, using  familiar
11488 notions such as packages, context clauses, declarations, default values,
11489 assignments, and inheritance. Finally, project files can be built
11490 hierarchically from other project files, simplifying complex system
11491 integration and project reuse.
11492
11493 A @dfn{project} is a specific set of values for various compilation properties.
11494 The settings for a given project are described by means of
11495 a @dfn{project file}, which is a text file written in an Ada-like syntax.
11496 Property values in project files are either strings or lists of strings.
11497 Properties that are not explicitly set receive default values.  A project
11498 file may interrogate the values of @dfn{external variables} (user-defined
11499 command-line switches or environment variables), and it may specify property
11500 settings conditionally, based on the value of such variables.
11501
11502 In simple cases, a project's source files depend only on other source files
11503 in the same project, or on the predefined libraries.  (@emph{Dependence} is
11504 used in
11505 the Ada technical sense; as in one Ada unit @code{with}ing another.)  However,
11506 the Project Manager also allows more sophisticated arrangements,
11507 where the source files in one project depend on source files in other
11508 projects:
11509 @itemize @bullet
11510 @item
11511 One project can @emph{import} other projects containing needed source files.
11512 @item
11513 You can organize GNAT projects in a hierarchy: a @emph{child} project
11514 can extend a @emph{parent} project, inheriting the parent's source files and
11515 optionally overriding any of them with alternative versions
11516 @end itemize
11517
11518 @noindent
11519 More generally, the Project Manager lets you structure large development
11520 efforts into hierarchical subsystems, where build decisions are delegated
11521 to the subsystem level, and thus different compilation environments
11522 (^switch^switch^ settings) used for different subsystems.
11523
11524 The Project Manager is invoked through the
11525 @option{^-P^/PROJECT_FILE=^@emph{projectfile}}
11526 switch to @command{gnatmake} or to the @command{^gnat^GNAT^} front driver.
11527 @ifclear vms
11528 There may be zero, one or more spaces between @option{-P} and
11529 @option{@emph{projectfile}}.
11530 @end ifclear
11531 If you want to define (on the command line) an external variable that is
11532 queried by the project file, you must use the
11533 @option{^-X^/EXTERNAL_REFERENCE=^@emph{vbl}=@emph{value}} switch.
11534 The Project Manager parses and interprets the project file, and drives the
11535 invoked tool based on the project settings.
11536
11537 The Project Manager supports a wide range of development strategies,
11538 for systems of all sizes.  Here are some typical practices that are
11539 easily handled:
11540 @itemize @bullet
11541 @item
11542 Using a common set of source files, but generating object files in different
11543 directories via different ^switch^switch^ settings
11544 @item
11545 Using a mostly-shared set of source files, but with different versions of
11546 some unit or units
11547 @end itemize
11548
11549 @noindent
11550 The destination of an executable can be controlled inside a project file
11551 using the @option{^-o^-o^}
11552 ^switch^switch^.
11553 In the absence of such a ^switch^switch^ either inside
11554 the project file or on the command line, any executable files generated by
11555 @command{gnatmake} are placed in the directory @code{Exec_Dir} specified
11556 in the project file. If no @code{Exec_Dir} is specified, they will be placed
11557 in the object directory of the project.
11558
11559 You can use project files to achieve some of the effects of a source
11560 versioning system (for example, defining separate projects for
11561 the different sets of sources that comprise different releases) but the
11562 Project Manager is independent of any source configuration management tools
11563 that might be used by the developers.
11564
11565 The next section introduces the main features of GNAT's project facility
11566 through a sequence of examples; subsequent sections will present the syntax
11567 and semantics in more detail. A more formal description of the project
11568 facility appears in @ref{Project File Reference,,, gnat_rm, GNAT
11569 Reference Manual}.
11570
11571 @c *****************************
11572 @c * Examples of Project Files *
11573 @c *****************************
11574
11575 @node Examples of Project Files
11576 @section Examples of Project Files
11577 @noindent
11578 This section illustrates some of the typical uses of project files and
11579 explains their basic structure and behavior.
11580
11581 @menu
11582 * Common Sources with Different ^Switches^Switches^ and Directories::
11583 * Using External Variables::
11584 * Importing Other Projects::
11585 * Extending a Project::
11586 @end menu
11587
11588 @node Common Sources with Different ^Switches^Switches^ and Directories
11589 @subsection Common Sources with Different ^Switches^Switches^ and Directories
11590
11591 @menu
11592 * Source Files::
11593 * Specifying the Object Directory::
11594 * Specifying the Exec Directory::
11595 * Project File Packages::
11596 * Specifying ^Switch^Switch^ Settings::
11597 * Main Subprograms::
11598 * Executable File Names::
11599 * Source File Naming Conventions::
11600 * Source Language(s)::
11601 @end menu
11602
11603 @noindent
11604 Suppose that the Ada source files @file{pack.ads}, @file{pack.adb}, and
11605 @file{proc.adb} are in the @file{/common} directory.  The file
11606 @file{proc.adb} contains an Ada main subprogram @code{Proc} that @code{with}s
11607 package @code{Pack}.  We want to compile these source files under two sets
11608 of ^switches^switches^:
11609 @itemize @bullet
11610 @item
11611 When debugging, we want to pass the @option{-g} switch to @command{gnatmake},
11612 and the @option{^-gnata^-gnata^},
11613 @option{^-gnato^-gnato^},
11614 and @option{^-gnatE^-gnatE^} switches to the
11615 compiler; the compiler's output is to appear in @file{/common/debug}
11616 @item
11617 When preparing a release version, we want to pass the @option{^-O2^O2^} switch
11618 to the compiler; the compiler's output is to appear in @file{/common/release}
11619 @end itemize
11620
11621 @noindent
11622 The GNAT project files shown below, respectively @file{debug.gpr} and
11623 @file{release.gpr} in the @file{/common} directory, achieve these effects.
11624
11625 Schematically:
11626 @smallexample
11627 @group
11628 ^/common^[COMMON]^
11629   debug.gpr
11630   release.gpr
11631   pack.ads
11632   pack.adb
11633   proc.adb
11634 @end group
11635 @group
11636 ^/common/debug^[COMMON.DEBUG]^
11637   proc.ali, proc.o
11638   pack.ali, pack.o
11639 @end group
11640 @group
11641 ^/common/release^[COMMON.RELEASE]^
11642   proc.ali, proc.o
11643   pack.ali, pack.o
11644 @end group
11645 @end smallexample
11646 Here are the corresponding project files:
11647
11648 @smallexample @c projectfile
11649 @group
11650 project Debug is
11651   for Object_Dir use "debug";
11652   for Main use ("proc");
11653
11654   package Builder is
11655     for ^Default_Switches^Default_Switches^ ("Ada")
11656         use ("^-g^-g^");
11657     for Executable ("proc.adb") use "proc1";
11658   end Builder;
11659 @end group
11660
11661 @group
11662   package Compiler is
11663     for ^Default_Switches^Default_Switches^ ("Ada")
11664        use ("-fstack-check",
11665             "^-gnata^-gnata^",
11666             "^-gnato^-gnato^",
11667             "^-gnatE^-gnatE^");
11668   end Compiler;
11669 end Debug;
11670 @end group
11671 @end smallexample
11672
11673 @smallexample @c projectfile
11674 @group
11675 project Release is
11676   for Object_Dir use "release";
11677   for Exec_Dir use ".";
11678   for Main use ("proc");
11679
11680   package Compiler is
11681     for ^Default_Switches^Default_Switches^ ("Ada")
11682         use ("^-O2^-O2^");
11683   end Compiler;
11684 end Release;
11685 @end group
11686 @end smallexample
11687
11688 @noindent
11689 The name of the project defined by @file{debug.gpr} is @code{"Debug"} (case
11690 insensitive), and analogously the project defined by @file{release.gpr} is
11691 @code{"Release"}.  For consistency the file should have the same name as the
11692 project, and the project file's extension should be @code{"gpr"}. These
11693 conventions are not required, but a warning is issued if they are not followed.
11694
11695 If the current directory is @file{^/temp^[TEMP]^}, then the command
11696 @smallexample
11697 gnatmake ^-P/common/debug.gpr^/PROJECT_FILE=[COMMON]DEBUG^
11698 @end smallexample
11699
11700 @noindent
11701 generates object and ALI files in @file{^/common/debug^[COMMON.DEBUG]^},
11702 as well as the @code{^proc1^PROC1.EXE^} executable,
11703 using the ^switch^switch^ settings defined in the project file.
11704
11705 Likewise, the command
11706 @smallexample
11707 gnatmake ^-P/common/release.gpr^/PROJECT_FILE=[COMMON]RELEASE^
11708 @end smallexample
11709
11710 @noindent
11711 generates object and ALI files in @file{^/common/release^[COMMON.RELEASE]^},
11712 and the @code{^proc^PROC.EXE^}
11713 executable in @file{^/common^[COMMON]^},
11714 using the ^switch^switch^ settings from the project file.
11715
11716 @node Source Files
11717 @unnumberedsubsubsec Source Files
11718
11719 @noindent
11720 If a project file does not explicitly specify a set of source directories or
11721 a set of source files, then by default the project's source files are the
11722 Ada source files in the project file directory.  Thus @file{pack.ads},
11723 @file{pack.adb}, and @file{proc.adb} are the source files for both projects.
11724
11725 @node Specifying the Object Directory
11726 @unnumberedsubsubsec Specifying the Object Directory
11727
11728 @noindent
11729 Several project properties are modeled by Ada-style @emph{attributes};
11730 a property is defined by supplying the equivalent of an Ada attribute
11731 definition clause in the project file.
11732 A project's object directory is another such a property; the corresponding
11733 attribute is @code{Object_Dir}, and its value is also a string expression,
11734 specified either as absolute or relative. In the later case,
11735 it is relative to the project file directory. Thus the compiler's
11736 output is directed to @file{^/common/debug^[COMMON.DEBUG]^}
11737 (for the @code{Debug} project)
11738 and to @file{^/common/release^[COMMON.RELEASE]^}
11739 (for the @code{Release} project).
11740 If @code{Object_Dir} is not specified, then the default is the project file
11741 directory itself.
11742
11743 @node Specifying the Exec Directory
11744 @unnumberedsubsubsec Specifying the Exec Directory
11745
11746 @noindent
11747 A project's exec directory is another property; the corresponding
11748 attribute is @code{Exec_Dir}, and its value is also a string expression,
11749 either specified as relative or absolute. If @code{Exec_Dir} is not specified,
11750 then the default is the object directory (which may also be the project file
11751 directory if attribute @code{Object_Dir} is not specified). Thus the executable
11752 is placed in @file{^/common/debug^[COMMON.DEBUG]^}
11753 for the @code{Debug} project (attribute @code{Exec_Dir} not specified)
11754 and in @file{^/common^[COMMON]^} for the @code{Release} project.
11755
11756 @node Project File Packages
11757 @unnumberedsubsubsec Project File Packages
11758
11759 @noindent
11760 A GNAT tool that is integrated with the Project Manager is modeled by a
11761 corresponding package in the project file. In the example above,
11762 The @code{Debug} project defines the packages @code{Builder}
11763 (for @command{gnatmake}) and @code{Compiler};
11764 the @code{Release} project defines only the @code{Compiler} package.
11765
11766 The Ada-like package syntax is not to be taken literally.  Although packages in
11767 project files bear a surface resemblance to packages in Ada source code, the
11768 notation is simply a way to convey a grouping of properties for a named
11769 entity.  Indeed, the package names permitted in project files are restricted
11770 to a predefined set, corresponding to the project-aware tools, and the contents
11771 of packages are limited to a small set of constructs.
11772 The packages in the example above contain attribute definitions.
11773
11774 @node Specifying ^Switch^Switch^ Settings
11775 @unnumberedsubsubsec Specifying ^Switch^Switch^ Settings
11776
11777 @noindent
11778 ^Switch^Switch^ settings for a project-aware tool can be specified through
11779 attributes in the package that corresponds to the tool.
11780 The example above illustrates one of the relevant attributes,
11781 @code{^Default_Switches^Default_Switches^}, which is defined in packages
11782 in both project files.
11783 Unlike simple attributes like @code{Source_Dirs},
11784 @code{^Default_Switches^Default_Switches^} is
11785 known as an @emph{associative array}.  When you define this attribute, you must
11786 supply an ``index'' (a literal string), and the effect of the attribute
11787 definition is to set the value of the array at the specified index.
11788 For the @code{^Default_Switches^Default_Switches^} attribute,
11789 the index is a programming language (in our case, Ada),
11790 and the value specified (after @code{use}) must be a list
11791 of string expressions.
11792
11793 The attributes permitted in project files are restricted to a predefined set.
11794 Some may appear at project level, others in packages.
11795 For any attribute that is an associative array, the index must always be a
11796 literal string, but the restrictions on this string (e.g., a file name or a
11797 language name) depend on the individual attribute.
11798 Also depending on the attribute, its specified value will need to be either a
11799 string or a string list.
11800
11801 In the @code{Debug} project, we set the switches for two tools,
11802 @command{gnatmake} and the compiler, and thus we include the two corresponding
11803 packages; each package defines the @code{^Default_Switches^Default_Switches^}
11804 attribute with index @code{"Ada"}.
11805 Note that the package corresponding to
11806 @command{gnatmake} is named @code{Builder}.  The @code{Release} project is
11807 similar, but only includes the @code{Compiler} package.
11808
11809 In project @code{Debug} above, the ^switches^switches^ starting with
11810 @option{-gnat} that are specified in package @code{Compiler}
11811 could have been placed in package @code{Builder}, since @command{gnatmake}
11812 transmits all such ^switches^switches^ to the compiler.
11813
11814 @node Main Subprograms
11815 @unnumberedsubsubsec Main Subprograms
11816
11817 @noindent
11818 One of the specifiable properties of a project is a list of files that contain
11819 main subprograms.  This property is captured in the @code{Main} attribute,
11820 whose value is a list of strings.  If a project defines the @code{Main}
11821 attribute, it is not necessary to identify the main subprogram(s) when
11822 invoking @command{gnatmake} (@pxref{gnatmake and Project Files}).
11823
11824 @node Executable File Names
11825 @unnumberedsubsubsec Executable File Names
11826
11827 @noindent
11828 By default, the executable file name corresponding to a main source is
11829 deduced from the main source file name. Through the attributes
11830 @code{Executable} and @code{Executable_Suffix} of package @code{Builder},
11831 it is possible to change this default.
11832 In project @code{Debug} above, the executable file name
11833 for main source @file{^proc.adb^PROC.ADB^} is
11834 @file{^proc1^PROC1.EXE^}.
11835 Attribute @code{Executable_Suffix}, when specified, may change the suffix
11836 of the executable files, when no attribute @code{Executable} applies:
11837 its value replace the platform-specific executable suffix.
11838 Attributes @code{Executable} and @code{Executable_Suffix} are the only ways to
11839 specify a non-default executable file name when several mains are built at once
11840 in a single @command{gnatmake} command.
11841
11842 @node Source File Naming Conventions
11843 @unnumberedsubsubsec Source File Naming Conventions
11844
11845 @noindent
11846 Since the project files above do not specify any source file naming
11847 conventions, the GNAT defaults are used.  The mechanism for defining source
11848 file naming conventions -- a package named @code{Naming} --
11849 is described below (@pxref{Naming Schemes}).
11850
11851 @node Source Language(s)
11852 @unnumberedsubsubsec Source Language(s)
11853
11854 @noindent
11855 Since the project files do not specify a @code{Languages} attribute, by
11856 default the GNAT tools assume that the language of the project file is Ada.
11857 More generally, a project can comprise source files
11858 in Ada, C, and/or other languages.
11859
11860 @node Using External Variables
11861 @subsection Using External Variables
11862
11863 @noindent
11864 Instead of supplying different project files for debug and release, we can
11865 define a single project file that queries an external variable (set either
11866 on the command line or via an ^environment variable^logical name^) in order to
11867 conditionally define the appropriate settings.  Again, assume that the
11868 source files @file{pack.ads}, @file{pack.adb}, and @file{proc.adb} are
11869 located in directory @file{^/common^[COMMON]^}.  The following project file,
11870 @file{build.gpr}, queries the external variable named @code{STYLE} and
11871 defines an object directory and ^switch^switch^ settings based on whether
11872 the value is @code{"deb"} (debug) or @code{"rel"} (release), and where
11873 the default is @code{"deb"}.
11874
11875 @smallexample @c projectfile
11876 @group
11877 project Build is
11878   for Main use ("proc");
11879
11880   type Style_Type is ("deb", "rel");
11881   Style : Style_Type := external ("STYLE", "deb");
11882
11883   case Style is
11884     when "deb" =>
11885       for Object_Dir use "debug";
11886
11887     when "rel" =>
11888       for Object_Dir use "release";
11889       for Exec_Dir use ".";
11890   end case;
11891 @end group
11892
11893 @group
11894   package Builder is
11895
11896     case Style is
11897       when "deb" =>
11898         for ^Default_Switches^Default_Switches^ ("Ada")
11899             use ("^-g^-g^");
11900         for Executable ("proc") use "proc1";
11901       when others =>
11902         null;
11903     end case;
11904
11905   end Builder;
11906 @end group
11907
11908 @group
11909   package Compiler is
11910
11911     case Style is
11912       when "deb" =>
11913         for ^Default_Switches^Default_Switches^ ("Ada")
11914             use ("^-gnata^-gnata^",
11915                  "^-gnato^-gnato^",
11916                  "^-gnatE^-gnatE^");
11917
11918       when "rel" =>
11919         for ^Default_Switches^Default_Switches^ ("Ada")
11920             use ("^-O2^-O2^");
11921     end case;
11922
11923   end Compiler;
11924
11925 end Build;
11926 @end group
11927 @end smallexample
11928
11929 @noindent
11930 @code{Style_Type} is an example of a @emph{string type}, which is the project
11931 file analog of an Ada enumeration type but whose components are string literals
11932 rather than identifiers.  @code{Style} is declared as a variable of this type.
11933
11934 The form @code{external("STYLE", "deb")} is known as an
11935 @emph{external reference}; its first argument is the name of an
11936 @emph{external variable}, and the second argument is a default value to be
11937 used if the external variable doesn't exist.  You can define an external
11938 variable on the command line via the @option{^-X^/EXTERNAL_REFERENCE^} switch,
11939 or you can use ^an environment variable^a logical name^
11940 as an external variable.
11941
11942 Each @code{case} construct is expanded by the Project Manager based on the
11943 value of @code{Style}. Thus the command
11944 @ifclear vms
11945 @smallexample
11946 gnatmake -P/common/build.gpr -XSTYLE=deb
11947 @end smallexample
11948 @end ifclear
11949
11950 @ifset vms
11951 @smallexample
11952 gnatmake /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=deb
11953 @end smallexample
11954 @end ifset
11955
11956 @noindent
11957 is equivalent to the @command{gnatmake} invocation using the project file
11958 @file{debug.gpr} in the earlier example.  So is the command
11959 @smallexample
11960 gnatmake ^-P/common/build.gpr^/PROJECT_FILE=[COMMON]BUILD.GPR^
11961 @end smallexample
11962
11963 @noindent
11964 since @code{"deb"} is the default for @code{STYLE}.
11965
11966 Analogously,
11967
11968 @ifclear vms
11969 @smallexample
11970 gnatmake -P/common/build.gpr -XSTYLE=rel
11971 @end smallexample
11972 @end ifclear
11973
11974 @ifset vms
11975 @smallexample
11976 GNAT MAKE /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=rel
11977 @end smallexample
11978 @end ifset
11979
11980 @noindent
11981 is equivalent to the @command{gnatmake} invocation using the project file
11982 @file{release.gpr} in the earlier example.
11983
11984 @node Importing Other Projects
11985 @subsection Importing Other Projects
11986 @cindex @code{ADA_PROJECT_PATH}
11987
11988 @noindent
11989 A compilation unit in a source file in one project may depend on compilation
11990 units in source files in other projects.  To compile this unit under
11991 control of a project file, the
11992 dependent project must @emph{import} the projects containing the needed source
11993 files.
11994 This effect is obtained using syntax similar to an Ada @code{with} clause,
11995 but where @code{with}ed entities are strings that denote project files.
11996
11997 As an example, suppose that the two projects @code{GUI_Proj} and
11998 @code{Comm_Proj} are defined in the project files @file{gui_proj.gpr} and
11999 @file{comm_proj.gpr} in directories @file{^/gui^[GUI]^}
12000 and @file{^/comm^[COMM]^}, respectively.
12001 Suppose that the source files for @code{GUI_Proj} are
12002 @file{gui.ads} and @file{gui.adb}, and that the source files for
12003 @code{Comm_Proj} are @file{comm.ads} and @file{comm.adb}, where each set of
12004 files is located in its respective project file directory.  Schematically:
12005
12006 @smallexample
12007 @group
12008 ^/gui^[GUI]^
12009   gui_proj.gpr
12010   gui.ads
12011   gui.adb
12012 @end group
12013
12014 @group
12015 ^/comm^[COMM]^
12016   comm_proj.gpr
12017   comm.ads
12018   comm.adb
12019 @end group
12020 @end smallexample
12021
12022 @noindent
12023 We want to develop an application in directory @file{^/app^[APP]^} that
12024 @code{with} the packages @code{GUI} and @code{Comm}, using the properties of
12025 the corresponding project files (e.g.@: the ^switch^switch^ settings
12026 and object directory).
12027 Skeletal code for a main procedure might be something like the following:
12028
12029 @smallexample @c ada
12030 @group
12031 with GUI, Comm;
12032 procedure App_Main is
12033    @dots{}
12034 begin
12035    @dots{}
12036 end App_Main;
12037 @end group
12038 @end smallexample
12039
12040 @noindent
12041 Here is a project file, @file{app_proj.gpr}, that achieves the desired
12042 effect:
12043
12044 @smallexample @c projectfile
12045 @group
12046 with "/gui/gui_proj", "/comm/comm_proj";
12047 project App_Proj is
12048    for Main use ("app_main");
12049 end App_Proj;
12050 @end group
12051 @end smallexample
12052
12053 @noindent
12054 Building an executable is achieved through the command:
12055 @smallexample
12056 gnatmake ^-P/app/app_proj^/PROJECT_FILE=[APP]APP_PROJ^
12057 @end smallexample
12058 @noindent
12059 which will generate the @code{^app_main^APP_MAIN.EXE^} executable
12060 in the directory where @file{app_proj.gpr} resides.
12061
12062 If an imported project file uses the standard extension (@code{^gpr^GPR^}) then
12063 (as illustrated above) the @code{with} clause can omit the extension.
12064
12065 Our example specified an absolute path for each imported project file.
12066 Alternatively, the directory name of an imported object can be omitted
12067 if either
12068 @itemize @bullet
12069 @item
12070 The imported project file is in the same directory as the importing project
12071 file, or
12072 @item
12073 You have defined ^an environment variable^a logical name^
12074 that includes the directory containing
12075 the needed project file. The syntax of @code{ADA_PROJECT_PATH} is the same as
12076 the syntax of @code{ADA_INCLUDE_PATH} and @code{ADA_OBJECTS_PATH}: a list of
12077 directory names separated by colons (semicolons on Windows).
12078 @end itemize
12079
12080 @noindent
12081 Thus, if we define @code{ADA_PROJECT_PATH} to include @file{^/gui^[GUI]^} and
12082 @file{^/comm^[COMM]^}, then our project file @file{app_proj.gpr} can be written
12083 as follows:
12084
12085 @smallexample @c projectfile
12086 @group
12087 with "gui_proj", "comm_proj";
12088 project App_Proj is
12089    for Main use ("app_main");
12090 end App_Proj;
12091 @end group
12092 @end smallexample
12093
12094 @noindent
12095 Importing other projects can create ambiguities.
12096 For example, the same unit might be present in different imported projects, or
12097 it might be present in both the importing project and in an imported project.
12098 Both of these conditions are errors.  Note that in the current version of
12099 the Project Manager, it is illegal to have an ambiguous unit even if the
12100 unit is never referenced by the importing project.  This restriction may be
12101 relaxed in a future release.
12102
12103 @node Extending a Project
12104 @subsection Extending a Project
12105
12106 @noindent
12107 In large software systems it is common to have multiple
12108 implementations of a common interface; in Ada terms, multiple versions of a
12109 package body for the same spec.  For example, one implementation
12110 might be safe for use in tasking programs, while another might only be used
12111 in sequential applications.  This can be modeled in GNAT using the concept
12112 of @emph{project extension}.  If one project (the ``child'') @emph{extends}
12113 another project (the ``parent'') then by default all source files of the
12114 parent project are inherited by the child, but the child project can
12115 override any of the parent's source files with new versions, and can also
12116 add new files.  This facility is the project analog of a type extension in
12117 Object-Oriented Programming.  Project hierarchies are permitted (a child
12118 project may be the parent of yet another project), and a project that
12119 inherits one project can also import other projects.
12120
12121 As an example, suppose that directory @file{^/seq^[SEQ]^} contains the project
12122 file @file{seq_proj.gpr} as well as the source files @file{pack.ads},
12123 @file{pack.adb}, and @file{proc.adb}:
12124
12125 @smallexample
12126 @group
12127 ^/seq^[SEQ]^
12128   pack.ads
12129   pack.adb
12130   proc.adb
12131   seq_proj.gpr
12132 @end group
12133 @end smallexample
12134
12135 @noindent
12136 Note that the project file can simply be empty (that is, no attribute or
12137 package is defined):
12138
12139 @smallexample @c projectfile
12140 @group
12141 project Seq_Proj is
12142 end Seq_Proj;
12143 @end group
12144 @end smallexample
12145
12146 @noindent
12147 implying that its source files are all the Ada source files in the project
12148 directory.
12149
12150 Suppose we want to supply an alternate version of @file{pack.adb}, in
12151 directory @file{^/tasking^[TASKING]^}, but use the existing versions of
12152 @file{pack.ads} and @file{proc.adb}.  We can define a project
12153 @code{Tasking_Proj} that inherits @code{Seq_Proj}:
12154
12155 @smallexample
12156 @group
12157 ^/tasking^[TASKING]^
12158   pack.adb
12159   tasking_proj.gpr
12160 @end group
12161
12162 @group
12163 project Tasking_Proj extends "/seq/seq_proj" is
12164 end Tasking_Proj;
12165 @end group
12166 @end smallexample
12167
12168 @noindent
12169 The version of @file{pack.adb} used in a build depends on which project file
12170 is specified.
12171
12172 Note that we could have obtained the desired behavior using project import
12173 rather than project inheritance; a @code{base} project would contain the
12174 sources for @file{pack.ads} and @file{proc.adb}, a sequential project would
12175 import @code{base} and add @file{pack.adb}, and likewise a tasking project
12176 would import @code{base} and add a different version of @file{pack.adb}.  The
12177 choice depends on whether other sources in the original project need to be
12178 overridden.  If they do, then project extension is necessary, otherwise,
12179 importing is sufficient.
12180
12181 @noindent
12182 In a project file that extends another project file, it is possible to
12183 indicate that an inherited source is not part of the sources of the extending
12184 project. This is necessary sometimes when a package spec has been overloaded
12185 and no longer requires a body: in this case, it is necessary to indicate that
12186 the inherited body is not part of the sources of the project, otherwise there
12187 will be a compilation error when compiling the spec.
12188
12189 For that purpose, the attribute @code{Excluded_Source_Files} is used.
12190 Its value is a string list: a list of file names. It is also possible to use
12191 attribute @code{Excluded_Source_List_File}. Its value is a single string:
12192 the file name of a text file containing a list of file names, one per line.
12193
12194 @smallexample @c @projectfile
12195 project B extends "a" is
12196    for Source_Files use ("pkg.ads");
12197    --  New spec of Pkg does not need a completion
12198    for Excluded_Source_Files use ("pkg.adb");
12199 end B;
12200 @end smallexample
12201
12202 Attribute @code{Excluded_Source_Files} may also be used to check if a source
12203 is still needed: if it is possible to build using @command{gnatmake} when such
12204 a source is put in attribute @code{Excluded_Source_Files} of a project P, then
12205 it is possible to remove the source completely from a system that includes
12206 project P.
12207
12208 @c ***********************
12209 @c * Project File Syntax *
12210 @c ***********************
12211
12212 @node Project File Syntax
12213 @section Project File Syntax
12214
12215 @menu
12216 * Basic Syntax::
12217 * Qualified Projects::
12218 * Packages::
12219 * Expressions::
12220 * String Types::
12221 * Variables::
12222 * Attributes::
12223 * Associative Array Attributes::
12224 * case Constructions::
12225 @end menu
12226
12227 @noindent
12228 This section describes the structure of project files.
12229
12230 A project may be an @emph{independent project}, entirely defined by a single
12231 project file. Any Ada source file in an independent project depends only
12232 on the predefined library and other Ada source files in the same project.
12233
12234 @noindent
12235 A project may also @dfn{depend on} other projects, in either or both of
12236 the following ways:
12237 @itemize @bullet
12238 @item It may import any number of projects
12239 @item It may extend at most one other project
12240 @end itemize
12241
12242 @noindent
12243 The dependence relation is a directed acyclic graph (the subgraph reflecting
12244 the ``extends'' relation is a tree).
12245
12246 A project's @dfn{immediate sources} are the source files directly defined by
12247 that project, either implicitly by residing in the project file's directory,
12248 or explicitly through any of the source-related attributes described below.
12249 More generally, a project @var{proj}'s @dfn{sources} are the immediate sources
12250 of @var{proj} together with the immediate sources (unless overridden) of any
12251 project on which @var{proj} depends (either directly or indirectly).
12252
12253 @node Basic Syntax
12254 @subsection Basic Syntax
12255
12256 @noindent
12257 As seen in the earlier examples, project files have an Ada-like syntax.
12258 The minimal project file is:
12259 @smallexample @c projectfile
12260 @group
12261 project Empty is
12262
12263 end Empty;
12264 @end group
12265 @end smallexample
12266
12267 @noindent
12268 The identifier @code{Empty} is the name of the project.
12269 This project name must be present after the reserved
12270 word @code{end} at the end of the project file, followed by a semi-colon.
12271
12272 Any name in a project file, such as the project name or a variable name,
12273 has the same syntax as an Ada identifier.
12274
12275 The reserved words of project files are the Ada 95 reserved words plus
12276 @code{extends}, @code{external}, and @code{project}.  Note that the only Ada
12277 reserved words currently used in project file syntax are:
12278
12279 @itemize @bullet
12280 @item
12281 @code{all}
12282 @item
12283 @code{at}
12284 @item
12285 @code{case}
12286 @item
12287 @code{end}
12288 @item
12289 @code{for}
12290 @item
12291 @code{is}
12292 @item
12293 @code{limited}
12294 @item
12295 @code{null}
12296 @item
12297 @code{others}
12298 @item
12299 @code{package}
12300 @item
12301 @code{renames}
12302 @item
12303 @code{type}
12304 @item
12305 @code{use}
12306 @item
12307 @code{when}
12308 @item
12309 @code{with}
12310 @end itemize
12311
12312 @noindent
12313 Comments in project files have the same syntax as in Ada, two consecutive
12314 hyphens through the end of the line.
12315
12316 @node Qualified Projects
12317 @subsection Qualified Projects
12318
12319 @noindent
12320 Before the reserved @code{project}, there may be one or two "qualifiers", that
12321 is identifiers or other reserved words, to qualify the project.
12322
12323 The current list of qualifiers is:
12324
12325 @itemize @bullet
12326 @item
12327 @code{abstract}: qualify a project with no sources. An abstract project must
12328 have a declaration specifying that there are no sources in the project, and,
12329 if it extends another project, the project it extends must also be a qualified
12330 abstract project.
12331
12332 @item
12333 @code{standard}: a standard project is a non library project with sources.
12334
12335 @item
12336 @code{aggregate}: for future extension
12337
12338 @item
12339 @code{aggregate library}: for future extension
12340
12341 @item
12342 @code{library}: a library project must declare both attributes
12343 @code{Library_Name} and @code{Library_Dir}.
12344
12345 @item
12346 @code{configuration}: a configuration project cannot be in a project tree.
12347 @end itemize
12348
12349 @node Packages
12350 @subsection Packages
12351
12352 @noindent
12353 A project file may contain @emph{packages}. The name of a package must be one
12354 of the identifiers from the following list. A package
12355 with a given name may only appear once in a project file. Package names are
12356 case insensitive. The following package names are legal:
12357
12358 @itemize @bullet
12359 @item
12360 @code{Naming}
12361 @item
12362 @code{Builder}
12363 @item
12364 @code{Compiler}
12365 @item
12366 @code{Binder}
12367 @item
12368 @code{Linker}
12369 @item
12370 @code{Finder}
12371 @item
12372 @code{Cross_Reference}
12373 @item
12374 @code{Eliminate}
12375 @item
12376 @code{Pretty_Printer}
12377 @item
12378 @code{Metrics}
12379 @item
12380 @code{gnatls}
12381 @item
12382 @code{gnatstub}
12383 @item
12384 @code{IDE}
12385 @item
12386 @code{Language_Processing}
12387 @end itemize
12388
12389 @noindent
12390 In its simplest form, a package may be empty:
12391
12392 @smallexample @c projectfile
12393 @group
12394 project Simple is
12395   package Builder is
12396   end Builder;
12397 end Simple;
12398 @end group
12399 @end smallexample
12400
12401 @noindent
12402 A package may contain @emph{attribute declarations},
12403 @emph{variable declarations} and @emph{case constructions}, as will be
12404 described below.
12405
12406 When there is ambiguity between a project name and a package name,
12407 the name always designates the project. To avoid possible confusion, it is
12408 always a good idea to avoid naming a project with one of the
12409 names allowed for packages or any name that starts with @code{gnat}.
12410
12411 @node Expressions
12412 @subsection Expressions
12413
12414 @noindent
12415 An @emph{expression} is either a @emph{string expression} or a
12416 @emph{string list expression}.
12417
12418 A @emph{string expression} is either a @emph{simple string expression} or a
12419 @emph{compound string expression}.
12420
12421 A @emph{simple string expression} is one of the following:
12422 @itemize @bullet
12423 @item A literal string; e.g.@: @code{"comm/my_proj.gpr"}
12424 @item A string-valued variable reference (@pxref{Variables})
12425 @item A string-valued attribute reference (@pxref{Attributes})
12426 @item An external reference (@pxref{External References in Project Files})
12427 @end itemize
12428
12429 @noindent
12430 A @emph{compound string expression} is a concatenation of string expressions,
12431 using the operator @code{"&"}
12432 @smallexample
12433        Path & "/" & File_Name & ".ads"
12434 @end smallexample
12435
12436 @noindent
12437 A @emph{string list expression} is either a
12438 @emph{simple string list expression} or a
12439 @emph{compound string list expression}.
12440
12441 A @emph{simple string list expression} is one of the following:
12442 @itemize @bullet
12443 @item A parenthesized list of zero or more string expressions,
12444 separated by commas
12445 @smallexample
12446    File_Names := (File_Name, "gnat.adc", File_Name & ".orig");
12447    Empty_List := ();
12448 @end smallexample
12449 @item A string list-valued variable reference
12450 @item A string list-valued attribute reference
12451 @end itemize
12452
12453 @noindent
12454 A @emph{compound string list expression} is the concatenation (using
12455 @code{"&"}) of a simple string list expression and an expression.  Note that
12456 each term in a compound string list expression, except the first, may be
12457 either a string expression or a string list expression.
12458
12459 @smallexample @c projectfile
12460 @group
12461    File_Name_List := () & File_Name; --  One string in this list
12462    Extended_File_Name_List := File_Name_List & (File_Name & ".orig");
12463    --  Two strings
12464    Big_List := File_Name_List & Extended_File_Name_List;
12465    --  Concatenation of two string lists: three strings
12466    Illegal_List := "gnat.adc" & Extended_File_Name_List;
12467    --  Illegal: must start with a string list
12468 @end group
12469 @end smallexample
12470
12471 @node String Types
12472 @subsection String Types
12473
12474 @noindent
12475 A @emph{string type declaration} introduces a discrete set of string literals.
12476 If a string variable is declared to have this type, its value
12477 is restricted to the given set of literals.
12478
12479 Here is an example of a string type declaration:
12480
12481 @smallexample @c projectfile
12482    type OS is ("NT", "nt", "Unix", "GNU/Linux", "other OS");
12483 @end smallexample
12484
12485 @noindent
12486 Variables of a string type are called @emph{typed variables}; all other
12487 variables are called @emph{untyped variables}. Typed variables are
12488 particularly useful in @code{case} constructions, to support conditional
12489 attribute declarations.
12490 (@pxref{case Constructions}).
12491
12492 The string literals in the list are case sensitive and must all be different.
12493 They may include any graphic characters allowed in Ada, including spaces.
12494
12495 A string type may only be declared at the project level, not inside a package.
12496
12497 A string type may be referenced by its name if it has been declared in the same
12498 project file, or by an expanded name whose prefix is the name of the project
12499 in which it is declared.
12500
12501 @node Variables
12502 @subsection Variables
12503
12504 @noindent
12505 A variable may be declared at the project file level, or within a package.
12506 Here are some examples of variable declarations:
12507
12508 @smallexample @c projectfile
12509 @group
12510    This_OS : OS := external ("OS"); --  a typed variable declaration
12511    That_OS := "GNU/Linux";          --  an untyped variable declaration
12512 @end group
12513 @end smallexample
12514
12515 @noindent
12516 The syntax of a @emph{typed variable declaration} is identical to the Ada
12517 syntax for an object declaration. By contrast, the syntax of an untyped
12518 variable declaration is identical to an Ada assignment statement. In fact,
12519 variable declarations in project files have some of the characteristics of
12520 an assignment, in that successive declarations for the same variable are
12521 allowed. Untyped variable declarations do establish the expected kind of the
12522 variable (string or string list), and successive declarations for it must
12523 respect the initial kind.
12524
12525 @noindent
12526 A string variable declaration (typed or untyped) declares a variable
12527 whose value is a string. This variable may be used as a string expression.
12528 @smallexample @c projectfile
12529    File_Name       := "readme.txt";
12530    Saved_File_Name := File_Name & ".saved";
12531 @end smallexample
12532
12533 @noindent
12534 A string list variable declaration declares a variable whose value is a list
12535 of strings. The list may contain any number (zero or more) of strings.
12536
12537 @smallexample @c projectfile
12538    Empty_List := ();
12539    List_With_One_Element := ("^-gnaty^-gnaty^");
12540    List_With_Two_Elements := List_With_One_Element & "^-gnatg^-gnatg^";
12541    Long_List := ("main.ada", "pack1_.ada", "pack1.ada", "pack2_.ada"
12542                  "pack2.ada", "util_.ada", "util.ada");
12543 @end smallexample
12544
12545 @noindent
12546 The same typed variable may not be declared more than once at project level,
12547 and it may not be declared more than once in any package; it is in effect
12548 a constant.
12549
12550 The same untyped variable may be declared several times. Declarations are
12551 elaborated in the order in which they appear, so  the new value replaces
12552 the old one, and any subsequent reference to the variable uses the new value.
12553 However, as noted above, if a variable has been declared as a string, all
12554 subsequent
12555 declarations must give it a string value. Similarly, if a variable has
12556 been declared as a string list, all subsequent declarations
12557 must give it a string list value.
12558
12559 A @emph{variable reference} may take several forms:
12560
12561 @itemize @bullet
12562 @item The simple variable name, for a variable in the current package (if any)
12563 or in the current project
12564 @item An expanded name, whose prefix is a context name.
12565 @end itemize
12566
12567 @noindent
12568 A @emph{context} may be one of the following:
12569
12570 @itemize @bullet
12571 @item The name of an existing package in the current project
12572 @item The name of an imported project of the current project
12573 @item The name of an ancestor project (i.e., a project extended by the current
12574 project, either directly or indirectly)
12575 @item An expanded name whose prefix is an imported/parent project name, and
12576 whose selector is a package name in that project.
12577 @end itemize
12578
12579 @noindent
12580 A variable reference may be used in an expression.
12581
12582 @node Attributes
12583 @subsection Attributes
12584
12585 @noindent
12586 A project (and its packages) may have @emph{attributes} that define
12587 the project's properties.  Some attributes have values that are strings;
12588 others have values that are string lists.
12589
12590 There are two categories of attributes: @emph{simple attributes}
12591 and @emph{associative arrays} (@pxref{Associative Array Attributes}).
12592
12593 Legal project attribute names, and attribute names for each legal package are
12594 listed below. Attributes names are case-insensitive.
12595
12596 The following attributes are defined on projects (all are simple attributes):
12597
12598 @multitable @columnfractions .4 .3
12599 @item @emph{Attribute Name}
12600 @tab @emph{Value}
12601 @item @code{Source_Files}
12602 @tab string list
12603 @item @code{Source_Dirs}
12604 @tab string list
12605 @item @code{Source_List_File}
12606 @tab string
12607 @item @code{Object_Dir}
12608 @tab string
12609 @item @code{Exec_Dir}
12610 @tab string
12611 @item @code{Excluded_Source_Dirs}
12612 @tab string list
12613 @item @code{Excluded_Source_Files}
12614 @tab string list
12615 @item @code{Excluded_Source_List_File}
12616 @tab string
12617 @item @code{Languages}
12618 @tab string list
12619 @item @code{Main}
12620 @tab string list
12621 @item @code{Library_Dir}
12622 @tab string
12623 @item @code{Library_Name}
12624 @tab string
12625 @item @code{Library_Kind}
12626 @tab string
12627 @item @code{Library_Version}
12628 @tab string
12629 @item @code{Library_Interface}
12630 @tab string
12631 @item @code{Library_Auto_Init}
12632 @tab string
12633 @item @code{Library_Options}
12634 @tab string list
12635 @item @code{Library_Src_Dir}
12636 @tab string
12637 @item @code{Library_ALI_Dir}
12638 @tab string
12639 @item @code{Library_GCC}
12640 @tab string
12641 @item @code{Library_Symbol_File}
12642 @tab string
12643 @item @code{Library_Symbol_Policy}
12644 @tab string
12645 @item @code{Library_Reference_Symbol_File}
12646 @tab string
12647 @item @code{Externally_Built}
12648 @tab string
12649 @end multitable
12650
12651 @noindent
12652 The following attributes are defined for package  @code{Naming}
12653 (@pxref{Naming Schemes}):
12654
12655 @multitable @columnfractions .4 .2 .2 .2
12656 @item Attribute Name @tab Category @tab Index @tab Value
12657 @item @code{Spec_Suffix}
12658 @tab associative array
12659 @tab language name
12660 @tab string
12661 @item @code{Body_Suffix}
12662 @tab associative array
12663 @tab language name
12664 @tab string
12665 @item @code{Separate_Suffix}
12666 @tab simple attribute
12667 @tab n/a
12668 @tab string
12669 @item @code{Casing}
12670 @tab simple attribute
12671 @tab n/a
12672 @tab string
12673 @item @code{Dot_Replacement}
12674 @tab simple attribute
12675 @tab n/a
12676 @tab string
12677 @item @code{Spec}
12678 @tab associative array
12679 @tab Ada unit name
12680 @tab string
12681 @item @code{Body}
12682 @tab associative array
12683 @tab Ada unit name
12684 @tab string
12685 @item @code{Specification_Exceptions}
12686 @tab associative array
12687 @tab language name
12688 @tab string list
12689 @item @code{Implementation_Exceptions}
12690 @tab associative array
12691 @tab language name
12692 @tab string list
12693 @end multitable
12694
12695 @noindent
12696 The following attributes are defined for packages @code{Builder},
12697 @code{Compiler}, @code{Binder},
12698 @code{Linker}, @code{Cross_Reference}, and @code{Finder}
12699 (@pxref{^Switches^Switches^ and Project Files}).
12700
12701 @multitable @columnfractions .4 .2 .2 .2
12702 @item Attribute Name @tab Category @tab Index @tab Value
12703 @item @code{^Default_Switches^Default_Switches^}
12704 @tab associative array
12705 @tab language name
12706 @tab string list
12707 @item @code{^Switches^Switches^}
12708 @tab associative array
12709 @tab file name
12710 @tab string list
12711 @end multitable
12712
12713 @noindent
12714 In addition, package @code{Compiler} has a single string attribute
12715 @code{Local_Configuration_Pragmas} and package @code{Builder} has a single
12716 string attribute @code{Global_Configuration_Pragmas}.
12717
12718 @noindent
12719 Each simple attribute has a default value: the empty string (for string-valued
12720 attributes) and the empty list (for string list-valued attributes).
12721
12722 An attribute declaration defines a new value for an attribute.
12723
12724 Examples of simple attribute declarations:
12725
12726 @smallexample @c projectfile
12727    for Object_Dir use "objects";
12728    for Source_Dirs use ("units", "test/drivers");
12729 @end smallexample
12730
12731 @noindent
12732 The syntax of a @dfn{simple attribute declaration} is similar to that of an
12733 attribute definition clause in Ada.
12734
12735 Attributes references may be appear in expressions.
12736 The general form for such a reference is @code{<entity>'<attribute>}:
12737 Associative array attributes are functions. Associative
12738 array attribute references must have an argument that is a string literal.
12739
12740 Examples are:
12741
12742 @smallexample @c projectfile
12743   project'Object_Dir
12744   Naming'Dot_Replacement
12745   Imported_Project'Source_Dirs
12746   Imported_Project.Naming'Casing
12747   Builder'^Default_Switches^Default_Switches^("Ada")
12748 @end smallexample
12749
12750 @noindent
12751 The prefix of an attribute may be:
12752 @itemize @bullet
12753 @item @code{project} for an attribute of the current project
12754 @item The name of an existing package of the current project
12755 @item The name of an imported project
12756 @item The name of a parent project that is extended by the current project
12757 @item An expanded name whose prefix is imported/parent project name,
12758 and whose selector is a package name
12759 @end itemize
12760
12761 @noindent
12762 Example:
12763 @smallexample @c projectfile
12764 @group
12765    project Prj is
12766      for Source_Dirs use project'Source_Dirs & "units";
12767      for Source_Dirs use project'Source_Dirs & "test/drivers"
12768    end Prj;
12769 @end group
12770 @end smallexample
12771
12772 @noindent
12773 In the first attribute declaration, initially the attribute @code{Source_Dirs}
12774 has the default value: an empty string list. After this declaration,
12775 @code{Source_Dirs} is a string list of one element: @code{"units"}.
12776 After the second attribute declaration @code{Source_Dirs} is a string list of
12777 two elements: @code{"units"} and @code{"test/drivers"}.
12778
12779 Note: this example is for illustration only. In practice,
12780 the project file would contain only one attribute declaration:
12781
12782 @smallexample @c projectfile
12783    for Source_Dirs use ("units", "test/drivers");
12784 @end smallexample
12785
12786 @node Associative Array Attributes
12787 @subsection Associative Array Attributes
12788
12789 @noindent
12790 Some attributes are defined as @emph{associative arrays}. An associative
12791 array may be regarded as a function that takes a string as a parameter
12792 and delivers a string or string list value as its result.
12793
12794 Here are some examples of single associative array attribute associations:
12795
12796 @smallexample @c projectfile
12797    for Body ("main") use "Main.ada";
12798    for ^Switches^Switches^ ("main.ada")
12799        use ("^-v^-v^",
12800             "^-gnatv^-gnatv^");
12801    for ^Switches^Switches^ ("main.ada")
12802             use Builder'^Switches^Switches^ ("main.ada")
12803               & "^-g^-g^";
12804 @end smallexample
12805
12806 @noindent
12807 Like untyped variables and simple attributes, associative array attributes
12808 may be declared several times. Each declaration supplies a new value for the
12809 attribute, and replaces the previous setting.
12810
12811 @noindent
12812 An associative array attribute may be declared as a full associative array
12813 declaration, with the value of the same attribute in an imported or extended
12814 project.
12815
12816 @smallexample @c projectfile
12817    package Builder is
12818       for Default_Switches use Default.Builder'Default_Switches;
12819    end Builder;
12820 @end smallexample
12821
12822 @noindent
12823 In this example, @code{Default} must be either a project imported by the
12824 current project, or the project that the current project extends. If the
12825 attribute is in a package (in this case, in package @code{Builder}), the same
12826 package needs to be specified.
12827
12828 @noindent
12829 A full associative array declaration replaces any other declaration for the
12830 attribute, including other full associative array declaration. Single
12831 associative array associations may be declare after a full associative
12832 declaration, modifying the value for a single association of the attribute.
12833
12834 @node case Constructions
12835 @subsection @code{case} Constructions
12836
12837 @noindent
12838 A @code{case} construction is used in a project file to effect conditional
12839 behavior.
12840 Here is a typical example:
12841
12842 @smallexample @c projectfile
12843 @group
12844 project MyProj is
12845    type OS_Type is ("GNU/Linux", "Unix", "NT", "VMS");
12846
12847    OS : OS_Type := external ("OS", "GNU/Linux");
12848 @end group
12849
12850 @group
12851    package Compiler is
12852      case OS is
12853        when "GNU/Linux" | "Unix" =>
12854          for ^Default_Switches^Default_Switches^ ("Ada")
12855              use ("^-gnath^-gnath^");
12856        when "NT" =>
12857          for ^Default_Switches^Default_Switches^ ("Ada")
12858              use ("^-gnatP^-gnatP^");
12859        when others =>
12860      end case;
12861    end Compiler;
12862 end MyProj;
12863 @end group
12864 @end smallexample
12865
12866 @noindent
12867 The syntax of a @code{case} construction is based on the Ada case statement
12868 (although there is no @code{null} construction for empty alternatives).
12869
12870 The case expression must be a typed string variable.
12871 Each alternative comprises the reserved word @code{when}, either a list of
12872 literal strings separated by the @code{"|"} character or the reserved word
12873 @code{others},  and the @code{"=>"} token.
12874 Each literal string must belong to the string type that is the type of the
12875 case variable.
12876 An @code{others} alternative, if present, must occur last.
12877
12878 After each @code{=>}, there are zero or more constructions.  The only
12879 constructions allowed in a case construction are other case constructions,
12880 attribute declarations and variable declarations. String type declarations and
12881 package declarations are not allowed. Variable declarations are restricted to
12882 variables that have already been declared before the case construction.
12883
12884 The value of the case variable is often given by an external reference
12885 (@pxref{External References in Project Files}).
12886
12887 @c ****************************************
12888 @c * Objects and Sources in Project Files *
12889 @c ****************************************
12890
12891 @node Objects and Sources in Project Files
12892 @section Objects and Sources in Project Files
12893
12894 @menu
12895 * Object Directory::
12896 * Exec Directory::
12897 * Source Directories::
12898 * Source File Names::
12899 @end menu
12900
12901 @noindent
12902 Each project has exactly one object directory and one or more source
12903 directories. The source directories must contain at least one source file,
12904 unless  the project file explicitly specifies that no source files are present
12905 (@pxref{Source File Names}).
12906
12907 @node Object Directory
12908 @subsection Object Directory
12909
12910 @noindent
12911 The object directory for a project is the directory containing the compiler's
12912 output (such as @file{ALI} files and object files) for the project's immediate
12913 sources.
12914
12915 The object directory is given by the value of the attribute @code{Object_Dir}
12916 in the project file.
12917
12918 @smallexample @c projectfile
12919    for Object_Dir use "objects";
12920 @end smallexample
12921
12922 @noindent
12923 The attribute @code{Object_Dir} has a string value, the path name of the object
12924 directory. The path name may be absolute or relative to the directory of the
12925 project file. This directory must already exist, and be readable and writable.
12926
12927 By default, when the attribute @code{Object_Dir} is not given an explicit value
12928 or when its value is the empty string, the object directory is the same as the
12929 directory containing the project file.
12930
12931 @node Exec Directory
12932 @subsection Exec Directory
12933
12934 @noindent
12935 The exec directory for a project is the directory containing the executables
12936 for the project's main subprograms.
12937
12938 The exec directory is given by the value of the attribute @code{Exec_Dir}
12939 in the project file.
12940
12941 @smallexample @c projectfile
12942    for Exec_Dir use "executables";
12943 @end smallexample
12944
12945 @noindent
12946 The attribute @code{Exec_Dir} has a string value, the path name of the exec
12947 directory. The path name may be absolute or relative to the directory of the
12948 project file. This directory must already exist, and be writable.
12949
12950 By default, when the attribute @code{Exec_Dir} is not given an explicit value
12951 or when its value is the empty string, the exec directory is the same as the
12952 object directory of the project file.
12953
12954 @node Source Directories
12955 @subsection Source Directories
12956
12957 @noindent
12958 The source directories of a project are specified by the project file
12959 attribute @code{Source_Dirs}.
12960
12961 This attribute's value is a string list. If the attribute is not given an
12962 explicit value, then there is only one source directory, the one where the
12963 project file resides.
12964
12965 A @code{Source_Dirs} attribute that is explicitly defined to be the empty list,
12966 as in
12967
12968 @smallexample @c projectfile
12969     for Source_Dirs use ();
12970 @end smallexample
12971
12972 @noindent
12973 indicates that the project contains no source files.
12974
12975 Otherwise, each string in the string list designates one or more
12976 source directories.
12977
12978 @smallexample @c projectfile
12979    for Source_Dirs use ("sources", "test/drivers");
12980 @end smallexample
12981
12982 @noindent
12983 If a string in the list ends with @code{"/**"},  then the directory whose path
12984 name precedes the two asterisks, as well as all its subdirectories
12985 (recursively), are source directories.
12986
12987 @smallexample @c projectfile
12988    for Source_Dirs use ("/system/sources/**");
12989 @end smallexample
12990
12991 @noindent
12992 Here the directory @code{/system/sources} and all of its subdirectories
12993 (recursively) are source directories.
12994
12995 To specify that the source directories are the directory of the project file
12996 and all of its subdirectories, you can declare @code{Source_Dirs} as follows:
12997 @smallexample @c projectfile
12998    for Source_Dirs use ("./**");
12999 @end smallexample
13000
13001 @noindent
13002 Each of the source directories must exist and be readable.
13003
13004 @node Source File Names
13005 @subsection Source File Names
13006
13007 @noindent
13008 In a project that contains source files, their names may be specified by the
13009 attributes @code{Source_Files} (a string list) or @code{Source_List_File}
13010 (a string). Source file names never include any directory information.
13011
13012 If the attribute @code{Source_Files} is given an explicit value, then each
13013 element of the list is a source file name.
13014
13015 @smallexample @c projectfile
13016    for Source_Files use ("main.adb");
13017    for Source_Files use ("main.adb", "pack1.ads", "pack2.adb");
13018 @end smallexample
13019
13020 @noindent
13021 If the attribute @code{Source_Files} is not given an explicit value,
13022 but the attribute @code{Source_List_File} is given a string value,
13023 then the source file names are contained in the text file whose path name
13024 (absolute or relative to the directory of the project file) is the
13025 value of the attribute @code{Source_List_File}.
13026
13027 Each line in the file that is not empty or is not a comment
13028 contains a source file name.
13029
13030 @smallexample @c projectfile
13031    for Source_List_File use "source_list.txt";
13032 @end smallexample
13033
13034 @noindent
13035 By default, if neither the attribute @code{Source_Files} nor the attribute
13036 @code{Source_List_File} is given an explicit value, then each file in the
13037 source directories that conforms to the project's naming scheme
13038 (@pxref{Naming Schemes}) is an immediate source of the project.
13039
13040 A warning is issued if both attributes @code{Source_Files} and
13041 @code{Source_List_File} are given explicit values. In this case, the attribute
13042 @code{Source_Files} prevails.
13043
13044 Each source file name must be the name of one existing source file
13045 in one of the source directories.
13046
13047 A @code{Source_Files} attribute whose value is an empty list
13048 indicates that there are no source files in the project.
13049
13050 If the order of the source directories is known statically, that is if
13051 @code{"/**"} is not used in the string list @code{Source_Dirs}, then there may
13052 be several files with the same source file name. In this case, only the file
13053 in the first directory is considered as an immediate source of the project
13054 file. If the order of the source directories is not known statically, it is
13055 an error to have several files with the same source file name.
13056
13057 Projects can be specified to have no Ada source
13058 files: the value of (@code{Source_Dirs} or @code{Source_Files} may be an empty
13059 list, or the @code{"Ada"} may be absent from @code{Languages}:
13060
13061 @smallexample @c projectfile
13062    for Source_Dirs use ();
13063    for Source_Files use ();
13064    for Languages use ("C", "C++");
13065 @end smallexample
13066
13067 @noindent
13068 Otherwise, a project must contain at least one immediate source.
13069
13070 Projects with no source files are useful as template packages
13071 (@pxref{Packages in Project Files}) for other projects; in particular to
13072 define a package @code{Naming} (@pxref{Naming Schemes}).
13073
13074 @c ****************************
13075 @c * Importing Projects *
13076 @c ****************************
13077
13078 @node  Importing Projects
13079 @section Importing Projects
13080 @cindex @code{ADA_PROJECT_PATH}
13081
13082 @noindent
13083 An immediate source of a project P may depend on source files that
13084 are neither immediate sources of P nor in the predefined library.
13085 To get this effect, P must @emph{import} the projects that contain the needed
13086 source files.
13087
13088 @smallexample @c projectfile
13089 @group
13090   with "project1", "utilities.gpr";
13091   with "/namings/apex.gpr";
13092   project Main is
13093     @dots{}
13094 @end group
13095 @end smallexample
13096
13097 @noindent
13098 As can be seen in this example, the syntax for importing projects is similar
13099 to the syntax for importing compilation units in Ada. However, project files
13100 use literal strings instead of names, and the @code{with} clause identifies
13101 project files rather than packages.
13102
13103 Each literal string is the file name or path name (absolute or relative) of a
13104 project file. If a string corresponds to a file name, with no path or a
13105 relative path, then its location is determined by the @emph{project path}. The
13106 latter can be queried using @code{gnatls -v}. It contains:
13107
13108 @itemize @bullet
13109 @item
13110 In first position, the directory containing the current project file.
13111 @item
13112 In last position, the default project directory. This default project directory
13113 is part of the GNAT installation and is the standard place to install project
13114 files giving access to standard support libraries.
13115 @ifclear vms
13116 @ref{Installing a library}
13117 @end ifclear
13118
13119 @item
13120 In between, all the directories referenced in the
13121 ^environment variable^logical name^ @env{ADA_PROJECT_PATH} if it exists.
13122 @end itemize
13123
13124 @noindent
13125 If a relative pathname is used, as in
13126
13127 @smallexample @c projectfile
13128   with "tests/proj";
13129 @end smallexample
13130
13131 @noindent
13132 then the full path for the project is constructed by concatenating this
13133 relative path to those in the project path, in order, until a matching file is
13134 found. Any symbolic link will be fully resolved in the directory of the
13135 importing project file before the imported project file is examined.
13136
13137 If the @code{with}'ed project file name does not have an extension,
13138 the default is @file{^.gpr^.GPR^}. If a file with this extension is not found,
13139 then the file name as specified in the @code{with} clause (no extension) will
13140 be used. In the above example, if a file @code{project1.gpr} is found, then it
13141 will be used; otherwise, if a file @code{^project1^PROJECT1^} exists
13142 then it will be used; if neither file exists, this is an error.
13143
13144 A warning is issued if the name of the project file does not match the
13145 name of the project; this check is case insensitive.
13146
13147 Any source file that is an immediate source of the imported project can be
13148 used by the immediate sources of the importing project, transitively. Thus
13149 if @code{A} imports @code{B}, and @code{B} imports @code{C}, the immediate
13150 sources of @code{A} may depend on the immediate sources of @code{C}, even if
13151 @code{A} does not import @code{C} explicitly. However, this is not recommended,
13152 because if and when @code{B} ceases to import @code{C}, some sources in
13153 @code{A} will no longer compile.
13154
13155 A side effect of this capability is that normally cyclic dependencies are not
13156 permitted: if @code{A} imports @code{B} (directly or indirectly) then @code{B}
13157 is not allowed to import @code{A}. However, there are cases when cyclic
13158 dependencies would be beneficial. For these cases, another form of import
13159 between projects exists, the @code{limited with}: a project @code{A} that
13160 imports a project @code{B} with a straight @code{with} may also be imported,
13161 directly or indirectly, by @code{B} on the condition that imports from @code{B}
13162 to @code{A} include at least one @code{limited with}.
13163
13164 @smallexample @c 0projectfile
13165 with "../b/b.gpr";
13166 with "../c/c.gpr";
13167 project A is
13168 end A;
13169
13170 limited with "../a/a.gpr";
13171 project B is
13172 end B;
13173
13174 with "../d/d.gpr";
13175 project C is
13176 end C;
13177
13178 limited with "../a/a.gpr";
13179 project D is
13180 end D;
13181 @end smallexample
13182
13183 @noindent
13184 In the above legal example, there are two project cycles:
13185 @itemize @bullet
13186 @item A-> B-> A
13187 @item A -> C -> D -> A
13188 @end itemize
13189
13190 @noindent
13191 In each of these cycle there is one @code{limited with}: import of @code{A}
13192 from @code{B} and import of @code{A} from @code{D}.
13193
13194 The difference between straight @code{with} and @code{limited with} is that
13195 the name of a project imported with a @code{limited with} cannot be used in the
13196 project that imports it. In particular, its packages cannot be renamed and
13197 its variables cannot be referred to.
13198
13199 An exception to the above rules for @code{limited with} is that for the main
13200 project specified to @command{gnatmake} or to the @command{GNAT} driver a
13201 @code{limited with} is equivalent to a straight @code{with}. For example,
13202 in the example above, projects @code{B} and @code{D} could not be main
13203 projects for @command{gnatmake} or to the @command{GNAT} driver, because they
13204 each have a @code{limited with} that is the only one in a cycle of importing
13205 projects.
13206
13207 @c *********************
13208 @c * Project Extension *
13209 @c *********************
13210
13211 @node Project Extension
13212 @section Project Extension
13213
13214 @noindent
13215 During development of a large system, it is sometimes necessary to use
13216 modified versions of some of the source files, without changing the original
13217 sources. This can be achieved through the @emph{project extension} facility.
13218
13219 @smallexample @c projectfile
13220    project Modified_Utilities extends "/baseline/utilities.gpr" is @dots{}
13221 @end smallexample
13222
13223 @noindent
13224 A project extension declaration introduces an extending project
13225 (the @emph{child}) and a project being extended (the @emph{parent}).
13226
13227 By default, a child project inherits all the sources of its parent.
13228 However, inherited sources can be overridden: a unit in a parent is hidden
13229 by a unit of the same name in the child.
13230
13231 Inherited sources are considered to be sources (but not immediate sources)
13232 of the child project; see @ref{Project File Syntax}.
13233
13234 An inherited source file retains any switches specified in the parent project.
13235
13236 For example if the project @code{Utilities} contains the spec and the
13237 body of an Ada package @code{Util_IO}, then the project
13238 @code{Modified_Utilities} can contain a new body for package @code{Util_IO}.
13239 The original body of @code{Util_IO} will not be considered in program builds.
13240 However, the package spec will still be found in the project
13241 @code{Utilities}.
13242
13243 A child project can have only one parent, except when it is qualified as
13244 abstract. But it may import any number of other projects.
13245
13246 A project is not allowed to import directly or indirectly at the same time a
13247 child project and any of its ancestors.
13248
13249 @c *******************************
13250 @c * Project Hierarchy Extension *
13251 @c *******************************
13252
13253 @node Project Hierarchy Extension
13254 @section Project Hierarchy Extension
13255
13256 @noindent
13257 When extending a large system spanning multiple projects, it is often
13258 inconvenient to extend every project in the hierarchy that is impacted by a
13259 small change introduced. In such cases, it is possible to create a virtual
13260 extension of entire hierarchy using @code{extends all} relationship.
13261
13262 When the project is extended using @code{extends all} inheritance, all projects
13263 that are imported by it, both directly and indirectly, are considered virtually
13264 extended. That is, the Project Manager creates "virtual projects"
13265 that extend every project in the hierarchy; all these virtual projects have
13266 no sources of their own and have as object directory the object directory of
13267 the root of "extending all" project.
13268
13269 It is possible to explicitly extend one or more projects in the hierarchy
13270 in order to modify the sources. These extending projects must be imported by
13271 the "extending all" project, which will replace the corresponding virtual
13272 projects with the explicit ones.
13273
13274 When building such a project hierarchy extension, the Project Manager will
13275 ensure that both modified sources and sources in virtual extending projects
13276 that depend on them, are recompiled.
13277
13278 By means of example, consider the following hierarchy of projects.
13279
13280 @enumerate
13281 @item
13282 project A, containing package P1
13283 @item
13284 project B importing A and containing package P2 which depends on P1
13285 @item
13286 project C importing B and containing package P3 which depends on P2
13287 @end enumerate
13288
13289 @noindent
13290 We want to modify packages P1 and P3.
13291
13292 This project hierarchy will need to be extended as follows:
13293
13294 @enumerate
13295 @item
13296 Create project A1 that extends A, placing modified P1 there:
13297
13298 @smallexample @c 0projectfile
13299 project A1 extends "(@dots{})/A" is
13300 end A1;
13301 @end smallexample
13302
13303 @item
13304 Create project C1 that "extends all" C and imports A1, placing modified
13305 P3 there:
13306
13307 @smallexample @c 0projectfile
13308 with "(@dots{})/A1";
13309 project C1 extends all "(@dots{})/C" is
13310 end C1;
13311 @end smallexample
13312 @end enumerate
13313
13314 When you build project C1, your entire modified project space will be
13315 recompiled, including the virtual project B1 that has been impacted by the
13316 "extending all" inheritance of project C.
13317
13318 Note that if a Library Project in the hierarchy is virtually extended,
13319 the virtual project that extends the Library Project is not a Library Project.
13320
13321 @c ****************************************
13322 @c * External References in Project Files *
13323 @c ****************************************
13324
13325 @node  External References in Project Files
13326 @section External References in Project Files
13327
13328 @noindent
13329 A project file may contain references to external variables; such references
13330 are called @emph{external references}.
13331
13332 An external variable is either defined as part of the environment (an
13333 environment variable in Unix, for example) or else specified on the command
13334 line via the @option{^-X^/EXTERNAL_REFERENCE=^@emph{vbl}=@emph{value}} switch.
13335 If both, then the command line value is used.
13336
13337 The value of an external reference is obtained by means of the built-in
13338 function @code{external}, which returns a string value.
13339 This function has two forms:
13340 @itemize @bullet
13341 @item @code{external (external_variable_name)}
13342 @item @code{external (external_variable_name, default_value)}
13343 @end itemize
13344
13345 @noindent
13346 Each parameter must be a string literal.  For example:
13347
13348 @smallexample @c projectfile
13349    external ("USER")
13350    external ("OS", "GNU/Linux")
13351 @end smallexample
13352
13353 @noindent
13354 In the form with one parameter, the function returns the value of
13355 the external variable given as parameter. If this name is not present in the
13356 environment, the function returns an empty string.
13357
13358 In the form with two string parameters, the second argument is
13359 the value returned when the variable given as the first argument is not
13360 present in the environment. In the example above, if @code{"OS"} is not
13361 the name of ^an environment variable^a logical name^ and is not passed on
13362 the command line, then the returned value is @code{"GNU/Linux"}.
13363
13364 An external reference may be part of a string expression or of a string
13365 list expression, and can therefore appear in a variable declaration or
13366 an attribute declaration.
13367
13368 @smallexample @c projectfile
13369 @group
13370    type Mode_Type is ("Debug", "Release");
13371    Mode : Mode_Type := external ("MODE");
13372    case Mode is
13373      when "Debug" =>
13374         @dots{}
13375 @end group
13376 @end smallexample
13377
13378 @c *****************************
13379 @c * Packages in Project Files *
13380 @c *****************************
13381
13382 @node  Packages in Project Files
13383 @section Packages in Project Files
13384
13385 @noindent
13386 A @emph{package} defines the settings for project-aware tools within a
13387 project.
13388 For each such tool one can declare a package; the names for these
13389 packages are preset (@pxref{Packages}).
13390 A package may contain variable declarations, attribute declarations, and case
13391 constructions.
13392
13393 @smallexample @c projectfile
13394 @group
13395    project Proj is
13396       package Builder is  -- used by gnatmake
13397          for ^Default_Switches^Default_Switches^ ("Ada")
13398              use ("^-v^-v^",
13399                   "^-g^-g^");
13400       end Builder;
13401    end Proj;
13402 @end group
13403 @end smallexample
13404
13405 @noindent
13406 The syntax of package declarations mimics that of package in Ada.
13407
13408 Most of the packages have an attribute
13409 @code{^Default_Switches^Default_Switches^}.
13410 This attribute is an associative array, and its value is a string list.
13411 The index of the associative array is the name of a programming language (case
13412 insensitive). This attribute indicates the ^switch^switch^
13413 or ^switches^switches^ to be used
13414 with the corresponding tool.
13415
13416 Some packages also have another attribute, @code{^Switches^Switches^},
13417 an associative array whose value is a string list.
13418 The index is the name of a source file.
13419 This attribute indicates the ^switch^switch^
13420 or ^switches^switches^ to be used by the corresponding
13421 tool when dealing with this specific file.
13422
13423 Further information on these ^switch^switch^-related attributes is found in
13424 @ref{^Switches^Switches^ and Project Files}.
13425
13426 A package may be declared as a @emph{renaming} of another package; e.g., from
13427 the project file for an imported project.
13428
13429 @smallexample @c projectfile
13430 @group
13431   with "/global/apex.gpr";
13432   project Example is
13433     package Naming renames Apex.Naming;
13434     @dots{}
13435   end Example;
13436 @end group
13437 @end smallexample
13438
13439 @noindent
13440 Packages that are renamed in other project files often come from project files
13441 that have no sources: they are just used as templates. Any modification in the
13442 template will be reflected automatically in all the project files that rename
13443 a package from the template.
13444
13445 In addition to the tool-oriented packages, you can also declare a package
13446 named @code{Naming} to establish specialized source file naming conventions
13447 (@pxref{Naming Schemes}).
13448
13449 @c ************************************
13450 @c * Variables from Imported Projects *
13451 @c ************************************
13452
13453 @node Variables from Imported Projects
13454 @section Variables from Imported Projects
13455
13456 @noindent
13457 An attribute or variable defined in an imported or parent project can
13458 be used in expressions in the importing / extending project.
13459 Such an attribute or variable is denoted by an expanded name whose prefix
13460 is either the name of the project or the expanded name of a package within
13461 a project.
13462
13463 @smallexample @c projectfile
13464 @group
13465   with "imported";
13466   project Main extends "base" is
13467      Var1 := Imported.Var;
13468      Var2 := Base.Var & ".new";
13469 @end group
13470
13471 @group
13472      package Builder is
13473         for ^Default_Switches^Default_Switches^ ("Ada")
13474             use Imported.Builder'Ada_^Switches^Switches^ &
13475                 "^-gnatg^-gnatg^" &
13476                 "^-v^-v^";
13477      end Builder;
13478 @end group
13479
13480 @group
13481      package Compiler is
13482         for ^Default_Switches^Default_Switches^ ("Ada")
13483             use Base.Compiler'Ada_^Switches^Switches^;
13484      end Compiler;
13485   end Main;
13486 @end group
13487 @end smallexample
13488
13489 @noindent
13490 In this example:
13491
13492 @itemize @bullet
13493 @item
13494 The value of @code{Var1} is a copy of the variable @code{Var} defined
13495 in the project file @file{"imported.gpr"}
13496 @item
13497 the value of @code{Var2} is a copy of the value of variable @code{Var}
13498 defined in the project file @file{base.gpr}, concatenated with @code{".new"}
13499 @item
13500 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
13501 @code{Builder} is a string list that includes in its value a copy of the value
13502 of @code{Ada_^Switches^Switches^} defined in the @code{Builder} package
13503 in project file @file{imported.gpr} plus two new elements:
13504 @option{"^-gnatg^-gnatg^"}
13505 and @option{"^-v^-v^"};
13506 @item
13507 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
13508 @code{Compiler} is a copy of the variable @code{Ada_^Switches^Switches^}
13509 defined in the @code{Compiler} package in project file @file{base.gpr},
13510 the project being extended.
13511 @end itemize
13512
13513 @c ******************
13514 @c * Naming Schemes *
13515 @c ******************
13516
13517 @node  Naming Schemes
13518 @section Naming Schemes
13519
13520 @noindent
13521 Sometimes an Ada software system is ported from a foreign compilation
13522 environment to GNAT, and the file names do not use the default GNAT
13523 conventions. Instead of changing all the file names (which for a variety
13524 of reasons might not be possible), you can define the relevant file
13525 naming scheme in the @code{Naming} package in your project file.
13526
13527 @noindent
13528 Note that the use of pragmas described in
13529 @ref{Alternative File Naming Schemes} by mean of a configuration
13530 pragmas file is not supported when using project files. You must use
13531 the features described in this paragraph. You can however use specify
13532 other configuration pragmas (@pxref{Specifying Configuration Pragmas}).
13533
13534 @ifclear vms
13535 For example, the following
13536 package models the Apex file naming rules:
13537
13538 @smallexample @c projectfile
13539 @group
13540   package Naming is
13541     for Casing               use "lowercase";
13542     for Dot_Replacement      use ".";
13543     for Spec_Suffix ("Ada")  use ".1.ada";
13544     for Body_Suffix ("Ada")  use ".2.ada";
13545   end Naming;
13546 @end group
13547 @end smallexample
13548 @end ifclear
13549
13550 @ifset vms
13551 For example, the following package models the HP Ada file naming rules:
13552
13553 @smallexample @c projectfile
13554 @group
13555   package Naming is
13556     for Casing               use "lowercase";
13557     for Dot_Replacement      use "__";
13558     for Spec_Suffix ("Ada")  use "_.^ada^ada^";
13559     for Body_Suffix ("Ada")  use ".^ada^ada^";
13560   end Naming;
13561 @end group
13562 @end smallexample
13563
13564 @noindent
13565 (Note that @code{Casing} is @code{"lowercase"} because GNAT gets the file
13566 names in lower case)
13567 @end ifset
13568
13569 @noindent
13570 You can define the following attributes in package @code{Naming}:
13571
13572 @table @code
13573
13574 @item @code{Casing}
13575 This must be a string with one of the three values @code{"lowercase"},
13576 @code{"uppercase"} or @code{"mixedcase"}; these strings are case insensitive.
13577
13578 @noindent
13579 If @code{Casing} is not specified, then the default is @code{"lowercase"}.
13580
13581 @item @code{Dot_Replacement}
13582 This must be a string whose value satisfies the following conditions:
13583
13584 @itemize @bullet
13585 @item It must not be empty
13586 @item It cannot start or end with an alphanumeric character
13587 @item It cannot be a single underscore
13588 @item It cannot start with an underscore followed by an alphanumeric
13589 @item It cannot contain a dot @code{'.'} except if the entire string
13590 is @code{"."}
13591 @end itemize
13592
13593 @noindent
13594 If @code{Dot_Replacement} is not specified, then the default is @code{"-"}.
13595
13596 @item @code{Spec_Suffix}
13597 This is an associative array (indexed by the programming language name, case
13598 insensitive) whose value is a string that must satisfy the following
13599 conditions:
13600
13601 @itemize @bullet
13602 @item It must not be empty
13603 @item It must include at least one dot
13604 @end itemize
13605 @noindent
13606 If @code{Spec_Suffix ("Ada")} is not specified, then the default is
13607 @code{"^.ads^.ADS^"}.
13608
13609 @item @code{Body_Suffix}
13610 This is an associative array (indexed by the programming language name, case
13611 insensitive) whose value is a string that must satisfy the following
13612 conditions:
13613
13614 @itemize @bullet
13615 @item It must not be empty
13616 @item It must include at least one dot
13617 @item It cannot be the same as @code{Spec_Suffix ("Ada")}
13618 @end itemize
13619 @noindent
13620 If @code{Body_Suffix ("Ada")} and @code{Spec_Suffix ("Ada")} end with the
13621 same string, then a file name that ends with the longest of these two suffixes
13622 will be a body if the longest suffix is @code{Body_Suffix ("Ada")} or a spec
13623 if the longest suffix is @code{Spec_Suffix ("Ada")}.
13624
13625 If @code{Body_Suffix ("Ada")} is not specified, then the default is
13626 @code{"^.adb^.ADB^"}.
13627
13628 @item @code{Separate_Suffix}
13629 This must be a string whose value satisfies the same conditions as
13630 @code{Body_Suffix}. The same "longest suffix" rules apply.
13631
13632 @noindent
13633 If @code{Separate_Suffix ("Ada")} is not specified, then it defaults to same
13634 value as @code{Body_Suffix ("Ada")}.
13635
13636 @item @code{Spec}
13637 @noindent
13638 You can use the associative array attribute @code{Spec}  to define
13639 the source file name for an individual Ada compilation unit's spec. The array
13640 index must be a string literal that identifies the Ada unit (case insensitive).
13641 The value of this attribute must be a string that identifies the file that
13642 contains this unit's spec (case sensitive or insensitive depending on the
13643 operating system).
13644
13645 @smallexample @c projectfile
13646    for Spec ("MyPack.MyChild") use "mypack.mychild.spec";
13647 @end smallexample
13648
13649 @item @code{Body}
13650
13651 You can use the associative array attribute @code{Body} to
13652 define the source file name for an individual Ada compilation unit's body
13653 (possibly a subunit).  The array index must be a string literal that identifies
13654 the Ada unit (case insensitive).  The value of this attribute must be a string
13655 that identifies the file that contains this unit's body or subunit (case
13656 sensitive or insensitive depending on the operating system).
13657
13658 @smallexample @c projectfile
13659    for Body ("MyPack.MyChild") use "mypack.mychild.body";
13660 @end smallexample
13661 @end table
13662
13663 @c ********************
13664 @c * Library Projects *
13665 @c ********************
13666
13667 @node Library Projects
13668 @section Library Projects
13669
13670 @noindent
13671 @emph{Library projects} are projects whose object code is placed in a library.
13672 (Note that this facility is not yet supported on all platforms)
13673
13674 To create a library project, you need to define in its project file
13675 two project-level attributes: @code{Library_Name} and @code{Library_Dir}.
13676 Additionally, you may define other library-related attributes such as
13677 @code{Library_Kind}, @code{Library_Version}, @code{Library_Interface},
13678 @code{Library_Auto_Init}, @code{Library_Options} and @code{Library_GCC}.
13679
13680 The @code{Library_Name} attribute has a string value. There is no restriction
13681 on the name of a library. It is the responsibility of the developer to
13682 choose a name that will be accepted by the platform. It is recommended to
13683 choose names that could be Ada identifiers; such names are almost guaranteed
13684 to be acceptable on all platforms.
13685
13686 The @code{Library_Dir} attribute has a string value that designates the path
13687 (absolute or relative) of the directory where the library will reside.
13688 It must designate an existing directory, and this directory must be writable,
13689 different from the project's object directory and from any source directory
13690 in the project tree.
13691
13692 If both @code{Library_Name} and @code{Library_Dir} are specified and
13693 are legal, then the project file defines a library project.  The optional
13694 library-related attributes are checked only for such project files.
13695
13696 The @code{Library_Kind} attribute has a string value that must be one of the
13697 following (case insensitive): @code{"static"}, @code{"dynamic"} or
13698 @code{"relocatable"} (which is a synonym for @code{"dynamic"}). If this
13699 attribute is not specified, the library is a static library, that is
13700 an archive of object files that can be potentially linked into a
13701 static executable. Otherwise, the library may be dynamic or
13702 relocatable, that is a library that is loaded only at the start of execution.
13703
13704 If you need to build both a static and a dynamic library, you should use two
13705 different object directories, since in some cases some extra code needs to
13706 be generated for the latter. For such cases, it is recommended to either use
13707 two different project files, or a single one which uses external variables
13708 to indicate what kind of library should be build.
13709
13710 The @code{Library_ALI_Dir} attribute may be specified to indicate the
13711 directory where the ALI files of the library will be copied. When it is
13712 not specified, the ALI files are copied to the directory specified in
13713 attribute @code{Library_Dir}. The directory specified by @code{Library_ALI_Dir}
13714 must be writable and different from the project's object directory and from
13715 any source directory in the project tree.
13716
13717 The @code{Library_Version} attribute has a string value whose interpretation
13718 is platform dependent. It has no effect on VMS and Windows. On Unix, it is
13719 used only for dynamic/relocatable libraries as the internal name of the
13720 library (the @code{"soname"}). If the library file name (built from the
13721 @code{Library_Name}) is different from the @code{Library_Version}, then the
13722 library file will be a symbolic link to the actual file whose name will be
13723 @code{Library_Version}.
13724
13725 Example (on Unix):
13726
13727 @smallexample @c projectfile
13728 @group
13729 project Plib is
13730
13731    Version := "1";
13732
13733    for Library_Dir use "lib_dir";
13734    for Library_Name use "dummy";
13735    for Library_Kind use "relocatable";
13736    for Library_Version use "libdummy.so." & Version;
13737
13738 end Plib;
13739 @end group
13740 @end smallexample
13741
13742 @noindent
13743 Directory @file{lib_dir} will contain the internal library file whose name
13744 will be @file{libdummy.so.1}, and @file{libdummy.so} will be a symbolic link to
13745 @file{libdummy.so.1}.
13746
13747 When @command{gnatmake} detects that a project file
13748 is a library project file, it will check all immediate sources of the project
13749 and rebuild the library if any of the sources have been recompiled.
13750
13751 Standard project files can import library project files. In such cases,
13752 the libraries will only be rebuilt if some of its sources are recompiled
13753 because they are in the closure of some other source in an importing project.
13754 Sources of the library project files that are not in such a closure will
13755 not be checked, unless the full library is checked, because one of its sources
13756 needs to be recompiled.
13757
13758 For instance, assume the project file @code{A} imports the library project file
13759 @code{L}. The immediate sources of A are @file{a1.adb}, @file{a2.ads} and
13760 @file{a2.adb}. The immediate sources of L are @file{l1.ads}, @file{l1.adb},
13761 @file{l2.ads}, @file{l2.adb}.
13762
13763 If @file{l1.adb} has been modified, then the library associated with @code{L}
13764 will be rebuilt when compiling all the immediate sources of @code{A} only
13765 if @file{a1.ads}, @file{a2.ads} or @file{a2.adb} includes a statement
13766 @code{"with L1;"}.
13767
13768 To be sure that all the sources in the library associated with @code{L} are
13769 up to date, and that all the sources of project @code{A} are also up to date,
13770 the following two commands needs to be used:
13771
13772 @smallexample
13773 gnatmake -Pl.gpr
13774 gnatmake -Pa.gpr
13775 @end smallexample
13776
13777 When a library is built or rebuilt, an attempt is made first to delete all
13778 files in the library directory.
13779 All @file{ALI} files will also be copied from the object directory to the
13780 library directory. To build executables, @command{gnatmake} will use the
13781 library rather than the individual object files.
13782
13783 @ifclear vms
13784 It is also possible to create library project files for third-party libraries
13785 that are precompiled and cannot be compiled locally thanks to the
13786 @code{externally_built} attribute. (See @ref{Installing a library}).
13787 @end ifclear
13788
13789 @c *******************************
13790 @c * Stand-alone Library Projects *
13791 @c *******************************
13792
13793 @node Stand-alone Library Projects
13794 @section Stand-alone Library Projects
13795
13796 @noindent
13797 A Stand-alone Library is a library that contains the necessary code to
13798 elaborate the Ada units that are included in the library. A Stand-alone
13799 Library is suitable to be used in an executable when the main is not
13800 in Ada. However, Stand-alone Libraries may also be used with an Ada main
13801 subprogram.
13802
13803 A Stand-alone Library Project is a Library Project where the library is
13804 a Stand-alone Library.
13805
13806 To be a Stand-alone Library Project, in addition to the two attributes
13807 that make a project a Library Project (@code{Library_Name} and
13808 @code{Library_Dir}, see @ref{Library Projects}), the attribute
13809 @code{Library_Interface} must be defined.
13810
13811 @smallexample @c projectfile
13812 @group
13813    for Library_Dir use "lib_dir";
13814    for Library_Name use "dummy";
13815    for Library_Interface use ("int1", "int1.child");
13816 @end group
13817 @end smallexample
13818
13819 Attribute @code{Library_Interface} has a nonempty string list value,
13820 each string in the list designating a unit contained in an immediate source
13821 of the project file.
13822
13823 When a Stand-alone Library is built, first the binder is invoked to build
13824 a package whose name depends on the library name
13825 (^b~dummy.ads/b^B$DUMMY.ADS/B^ in the example above).
13826 This binder-generated package includes initialization and
13827 finalization procedures whose
13828 names depend on the library name (dummyinit and dummyfinal in the example
13829 above). The object corresponding to this package is included in the library.
13830
13831 A dynamic or relocatable Stand-alone Library is automatically initialized
13832 if automatic initialization of Stand-alone Libraries is supported on the
13833 platform and if attribute @code{Library_Auto_Init} is not specified or
13834 is specified with the value "true". A static Stand-alone Library is never
13835 automatically initialized.
13836
13837 Single string attribute @code{Library_Auto_Init} may be specified with only
13838 two possible values: "false" or "true" (case-insensitive). Specifying
13839 "false" for attribute @code{Library_Auto_Init} will prevent automatic
13840 initialization of dynamic or relocatable libraries.
13841
13842 When a non-automatically initialized Stand-alone Library is used
13843 in an executable, its initialization procedure must be called before
13844 any service of the library is used.
13845 When the main subprogram is in Ada, it may mean that the initialization
13846 procedure has to be called during elaboration of another package.
13847
13848 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
13849 (those that are listed in attribute @code{Library_Interface}) are copied to
13850 the Library Directory. As a consequence, only the Interface Units may be
13851 imported from Ada units outside of the library. If other units are imported,
13852 the binding phase will fail.
13853
13854 When a Stand-Alone Library is bound, the switches that are specified in
13855 the attribute @code{Default_Switches ("Ada")} in package @code{Binder} are
13856 used in the call to @command{gnatbind}.
13857
13858 The string list attribute @code{Library_Options} may be used to specified
13859 additional switches to the call to @command{gcc} to link the library.
13860
13861 The attribute @code{Library_Src_Dir}, may be specified for a
13862 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
13863 single string value. Its value must be the path (absolute or relative to the
13864 project directory) of an existing directory. This directory cannot be the
13865 object directory or one of the source directories, but it can be the same as
13866 the library directory. The sources of the Interface
13867 Units of the library, necessary to an Ada client of the library, will be
13868 copied to the designated directory, called Interface Copy directory.
13869 These sources includes the specs of the Interface Units, but they may also
13870 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
13871 are used, or when there is a generic units in the spec. Before the sources
13872 are copied to the Interface Copy directory, an attempt is made to delete all
13873 files in the Interface Copy directory.
13874
13875 @c *************************************
13876 @c * Switches Related to Project Files *
13877 @c *************************************
13878 @node Switches Related to Project Files
13879 @section Switches Related to Project Files
13880
13881 @noindent
13882 The following switches are used by GNAT tools that support project files:
13883
13884 @table @option
13885
13886 @item ^-P^/PROJECT_FILE=^@var{project}
13887 @cindex @option{^-P^/PROJECT_FILE^} (any project-aware tool)
13888 Indicates the name of a project file. This project file will be parsed with
13889 the verbosity indicated by @option{^-vP^MESSAGE_PROJECT_FILES=^@emph{x}},
13890 if any, and using the external references indicated
13891 by @option{^-X^/EXTERNAL_REFERENCE^} switches, if any.
13892 @ifclear vms
13893 There may zero, one or more spaces between @option{-P} and @var{project}.
13894 @end ifclear
13895
13896 @noindent
13897 There must be only one @option{^-P^/PROJECT_FILE^} switch on the command line.
13898
13899 @noindent
13900 Since the Project Manager parses the project file only after all the switches
13901 on the command line are checked, the order of the switches
13902 @option{^-P^/PROJECT_FILE^},
13903 @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}}
13904 or @option{^-X^/EXTERNAL_REFERENCE^} is not significant.
13905
13906 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
13907 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (any project-aware tool)
13908 Indicates that external variable @var{name} has the value @var{value}.
13909 The Project Manager will use this value for occurrences of
13910 @code{external(name)} when parsing the project file.
13911
13912 @ifclear vms
13913 @noindent
13914 If @var{name} or @var{value} includes a space, then @var{name=value} should be
13915 put between quotes.
13916 @smallexample
13917   -XOS=NT
13918   -X"user=John Doe"
13919 @end smallexample
13920 @end ifclear
13921
13922 @noindent
13923 Several @option{^-X^/EXTERNAL_REFERENCE^} switches can be used simultaneously.
13924 If several @option{^-X^/EXTERNAL_REFERENCE^} switches specify the same
13925 @var{name}, only the last one is used.
13926
13927 @noindent
13928 An external variable specified with a @option{^-X^/EXTERNAL_REFERENCE^} switch
13929 takes precedence over the value of the same name in the environment.
13930
13931 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
13932 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (any project-aware tool)
13933 Indicates the verbosity of the parsing of GNAT project files.
13934
13935 @ifclear vms
13936 @option{-vP0} means Default;
13937 @option{-vP1} means Medium;
13938 @option{-vP2} means High.
13939 @end ifclear
13940
13941 @ifset vms
13942 There are three possible options for this qualifier: DEFAULT, MEDIUM and
13943 HIGH.
13944 @end ifset
13945
13946 @noindent
13947 The default is ^Default^DEFAULT^: no output for syntactically correct
13948 project files.
13949 @noindent
13950 If several @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}} switches are present,
13951 only the last one is used.
13952
13953 @item ^-aP^/ADD_PROJECT_SEARCH_DIR=^<dir>
13954 @cindex @option{^-aP^/ADD_PROJECT_SEARCH_DIR=^} (any project-aware tool)
13955 Add directory <dir> at the beginning of the project search path, in order,
13956 after the current working directory.
13957
13958 @ifclear vms
13959 @item -eL
13960 @cindex @option{-eL} (any project-aware tool)
13961 Follow all symbolic links when processing project files.
13962 @end ifclear
13963
13964 @item ^--subdirs^/SUBDIRS^=<subdir>
13965 @cindex @option{^--subdirs^/SUBDIRS^=} (gnatmake and gnatclean)
13966 This switch is recognized by gnatmake and gnatclean. It indicate that the real
13967 directories (except the source directories) are the subdirectories <subdir>
13968 of the directories specified in the project files. This applies in particular
13969 to object directories, library directories and exec directories. If the
13970 subdirectories do not exist, they are created automatically.
13971
13972 @end table
13973
13974 @c **********************************
13975 @c * Tools Supporting Project Files *
13976 @c **********************************
13977
13978 @node  Tools Supporting Project Files
13979 @section Tools Supporting Project Files
13980
13981 @menu
13982 * gnatmake and Project Files::
13983 * The GNAT Driver and Project Files::
13984 @end menu
13985
13986 @node gnatmake and Project Files
13987 @subsection gnatmake and Project Files
13988
13989 @noindent
13990 This section covers several topics related to @command{gnatmake} and
13991 project files: defining ^switches^switches^ for @command{gnatmake}
13992 and for the tools that it invokes; specifying configuration pragmas;
13993 the use of the @code{Main} attribute; building and rebuilding library project
13994 files.
13995
13996 @menu
13997 * ^Switches^Switches^ and Project Files::
13998 * Specifying Configuration Pragmas::
13999 * Project Files and Main Subprograms::
14000 * Library Project Files::
14001 @end menu
14002
14003 @node ^Switches^Switches^ and Project Files
14004 @subsubsection ^Switches^Switches^ and Project Files
14005
14006 @ifset vms
14007 It is not currently possible to specify VMS style qualifiers in the project
14008 files; only Unix style ^switches^switches^ may be specified.
14009 @end ifset
14010
14011 @noindent
14012 For each of the packages @code{Builder}, @code{Compiler}, @code{Binder}, and
14013 @code{Linker}, you can specify a @code{^Default_Switches^Default_Switches^}
14014 attribute, a @code{^Switches^Switches^} attribute, or both;
14015 as their names imply, these ^switch^switch^-related
14016 attributes affect the ^switches^switches^ that are used for each of these GNAT
14017 components when
14018 @command{gnatmake} is invoked.  As will be explained below, these
14019 component-specific ^switches^switches^ precede
14020 the ^switches^switches^ provided on the @command{gnatmake} command line.
14021
14022 The @code{^Default_Switches^Default_Switches^} attribute is an associative
14023 array indexed by language name (case insensitive) whose value is a string list.
14024 For example:
14025
14026 @smallexample @c projectfile
14027 @group
14028 package Compiler is
14029   for ^Default_Switches^Default_Switches^ ("Ada")
14030       use ("^-gnaty^-gnaty^",
14031            "^-v^-v^");
14032 end Compiler;
14033 @end group
14034 @end smallexample
14035
14036 @noindent
14037 The @code{^Switches^Switches^} attribute is also an associative array,
14038 indexed by a file name (which may or may not be case sensitive, depending
14039 on the operating system) whose value is a string list.  For example:
14040
14041 @smallexample @c projectfile
14042 @group
14043 package Builder is
14044    for ^Switches^Switches^ ("main1.adb")
14045        use ("^-O2^-O2^");
14046    for ^Switches^Switches^ ("main2.adb")
14047        use ("^-g^-g^");
14048 end Builder;
14049 @end group
14050 @end smallexample
14051
14052 @noindent
14053 For the @code{Builder} package, the file names must designate source files
14054 for main subprograms.  For the @code{Binder} and @code{Linker} packages, the
14055 file names must designate @file{ALI} or source files for main subprograms.
14056 In each case just the file name without an explicit extension is acceptable.
14057
14058 For each tool used in a program build (@command{gnatmake}, the compiler, the
14059 binder, and the linker), the corresponding package @dfn{contributes} a set of
14060 ^switches^switches^ for each file on which the tool is invoked, based on the
14061 ^switch^switch^-related attributes defined in the package.
14062 In particular, the ^switches^switches^
14063 that each of these packages contributes for a given file @var{f} comprise:
14064
14065 @itemize @bullet
14066 @item
14067 the value of attribute @code{^Switches^Switches^ (@var{f})},
14068 if it is specified in the package for the given file,
14069 @item
14070 otherwise, the value of @code{^Default_Switches^Default_Switches^ ("Ada")},
14071 if it is specified in the package.
14072 @end itemize
14073
14074 @noindent
14075 If neither of these attributes is defined in the package, then the package does
14076 not contribute any ^switches^switches^ for the given file.
14077
14078 When @command{gnatmake} is invoked on a file, the ^switches^switches^ comprise
14079 two sets, in the following order: those contributed for the file
14080 by the @code{Builder} package;
14081 and the switches passed on the command line.
14082
14083 When @command{gnatmake} invokes a tool (compiler, binder, linker) on a file,
14084 the ^switches^switches^ passed to the tool comprise three sets,
14085 in the following order:
14086
14087 @enumerate
14088 @item
14089 the applicable ^switches^switches^ contributed for the file
14090 by the @code{Builder} package in the project file supplied on the command line;
14091
14092 @item
14093 those contributed for the file by the package (in the relevant project file --
14094 see below) corresponding to the tool; and
14095
14096 @item
14097 the applicable switches passed on the command line.
14098 @end enumerate
14099
14100 @noindent
14101 The term @emph{applicable ^switches^switches^} reflects the fact that
14102 @command{gnatmake} ^switches^switches^ may or may not be passed to individual
14103 tools, depending on the individual ^switch^switch^.
14104
14105 @command{gnatmake} may invoke the compiler on source files from different
14106 projects. The Project Manager will use the appropriate project file to
14107 determine the @code{Compiler} package for each source file being compiled.
14108 Likewise for the @code{Binder} and @code{Linker} packages.
14109
14110 As an example, consider the following package in a project file:
14111
14112 @smallexample @c projectfile
14113 @group
14114 project Proj1 is
14115    package Compiler is
14116       for ^Default_Switches^Default_Switches^ ("Ada")
14117           use ("^-g^-g^");
14118       for ^Switches^Switches^ ("a.adb")
14119           use ("^-O1^-O1^");
14120       for ^Switches^Switches^ ("b.adb")
14121           use ("^-O2^-O2^",
14122                "^-gnaty^-gnaty^");
14123    end Compiler;
14124 end Proj1;
14125 @end group
14126 @end smallexample
14127
14128 @noindent
14129 If @command{gnatmake} is invoked with this project file, and it needs to
14130 compile, say, the files @file{a.adb}, @file{b.adb}, and @file{c.adb}, then
14131 @file{a.adb} will be compiled with the ^switch^switch^
14132 @option{^-O1^-O1^},
14133 @file{b.adb} with ^switches^switches^
14134 @option{^-O2^-O2^}
14135 and @option{^-gnaty^-gnaty^},
14136 and @file{c.adb} with @option{^-g^-g^}.
14137
14138 The following example illustrates the ordering of the ^switches^switches^
14139 contributed by different packages:
14140
14141 @smallexample @c projectfile
14142 @group
14143 project Proj2 is
14144    package Builder is
14145       for ^Switches^Switches^ ("main.adb")
14146           use ("^-g^-g^",
14147                "^-O1^-)1^",
14148                "^-f^-f^");
14149    end Builder;
14150 @end group
14151
14152 @group
14153    package Compiler is
14154       for ^Switches^Switches^ ("main.adb")
14155           use ("^-O2^-O2^");
14156    end Compiler;
14157 end Proj2;
14158 @end group
14159 @end smallexample
14160
14161 @noindent
14162 If you issue the command:
14163
14164 @smallexample
14165     gnatmake ^-Pproj2^/PROJECT_FILE=PROJ2^ -O0 main
14166 @end smallexample
14167
14168 @noindent
14169 then the compiler will be invoked on @file{main.adb} with the following
14170 sequence of ^switches^switches^
14171
14172 @smallexample
14173    ^-g -O1 -O2 -O0^-g -O1 -O2 -O0^
14174 @end smallexample
14175
14176 with the last @option{^-O^-O^}
14177 ^switch^switch^ having precedence over the earlier ones;
14178 several other ^switches^switches^
14179 (such as @option{^-c^-c^}) are added implicitly.
14180
14181 The ^switches^switches^
14182 @option{^-g^-g^}
14183 and @option{^-O1^-O1^} are contributed by package
14184 @code{Builder},  @option{^-O2^-O2^} is contributed
14185 by the package @code{Compiler}
14186 and @option{^-O0^-O0^} comes from the command line.
14187
14188 The @option{^-g^-g^}
14189 ^switch^switch^ will also be passed in the invocation of
14190 @command{Gnatlink.}
14191
14192 A final example illustrates switch contributions from packages in different
14193 project files:
14194
14195 @smallexample @c projectfile
14196 @group
14197 project Proj3 is
14198    for Source_Files use ("pack.ads", "pack.adb");
14199    package Compiler is
14200       for ^Default_Switches^Default_Switches^ ("Ada")
14201           use ("^-gnata^-gnata^");
14202    end Compiler;
14203 end Proj3;
14204 @end group
14205
14206 @group
14207 with "Proj3";
14208 project Proj4 is
14209    for Source_Files use ("foo_main.adb", "bar_main.adb");
14210    package Builder is
14211       for ^Switches^Switches^ ("foo_main.adb")
14212           use ("^-s^-s^",
14213                "^-g^-g^");
14214    end Builder;
14215 end Proj4;
14216 @end group
14217
14218 @group
14219 -- Ada source file:
14220 with Pack;
14221 procedure Foo_Main is
14222    @dots{}
14223 end Foo_Main;
14224 @end group
14225 @end smallexample
14226
14227 If the command is
14228 @smallexample
14229 gnatmake ^-PProj4^/PROJECT_FILE=PROJ4^ foo_main.adb -cargs -gnato
14230 @end smallexample
14231
14232 @noindent
14233 then the ^switches^switches^ passed to the compiler for @file{foo_main.adb} are
14234 @option{^-g^-g^} (contributed by the package @code{Proj4.Builder}) and
14235 @option{^-gnato^-gnato^} (passed on the command line).
14236 When the imported package @code{Pack} is compiled, the ^switches^switches^ used
14237 are @option{^-g^-g^} from @code{Proj4.Builder},
14238 @option{^-gnata^-gnata^} (contributed from package @code{Proj3.Compiler},
14239 and @option{^-gnato^-gnato^} from the command line.
14240
14241 @noindent
14242 When using @command{gnatmake} with project files, some ^switches^switches^ or
14243 arguments may be expressed as relative paths. As the working directory where
14244 compilation occurs may change, these relative paths are converted to absolute
14245 paths. For the ^switches^switches^ found in a project file, the relative paths
14246 are relative to the project file directory, for the switches on the command
14247 line, they are relative to the directory where @command{gnatmake} is invoked.
14248 The ^switches^switches^ for which this occurs are:
14249 ^-I^-I^,
14250 ^-A^-A^,
14251 ^-L^-L^,
14252 ^-aO^-aO^,
14253 ^-aL^-aL^,
14254 ^-aI^-aI^, as well as all arguments that are not switches (arguments to
14255 ^switch^switch^
14256 ^-o^-o^, object files specified in package @code{Linker} or after
14257 -largs on the command line). The exception to this rule is the ^switch^switch^
14258 ^--RTS=^--RTS=^ for which a relative path argument is never converted.
14259
14260 @node Specifying Configuration Pragmas
14261 @subsubsection Specifying Configuration Pragmas
14262
14263 When using @command{gnatmake} with project files, if there exists a file
14264 @file{gnat.adc} that contains configuration pragmas, this file will be
14265 ignored.
14266
14267 Configuration pragmas can be defined by means of the following attributes in
14268 project files: @code{Global_Configuration_Pragmas} in package @code{Builder}
14269 and @code{Local_Configuration_Pragmas} in package @code{Compiler}.
14270
14271 Both these attributes are single string attributes. Their values is the path
14272 name of a file containing configuration pragmas. If a path name is relative,
14273 then it is relative to the project directory of the project file where the
14274 attribute is defined.
14275
14276 When compiling a source, the configuration pragmas used are, in order,
14277 those listed in the file designated by attribute
14278 @code{Global_Configuration_Pragmas} in package @code{Builder} of the main
14279 project file, if it is specified, and those listed in the file designated by
14280 attribute @code{Local_Configuration_Pragmas} in package @code{Compiler} of
14281 the project file of the source, if it exists.
14282
14283 @node Project Files and Main Subprograms
14284 @subsubsection Project Files and Main Subprograms
14285
14286 @noindent
14287 When using a project file, you can invoke @command{gnatmake}
14288 with one or several main subprograms, by specifying their source files on the
14289 command line.
14290
14291 @smallexample
14292     gnatmake ^-P^/PROJECT_FILE=^prj main1 main2 main3
14293 @end smallexample
14294
14295 @noindent
14296 Each of these needs to be a source file of the same project, except
14297 when the switch ^-u^/UNIQUE^ is used.
14298
14299 @noindent
14300 When ^-u^/UNIQUE^ is not used, all the mains need to be sources of the
14301 same project, one of the project in the tree rooted at the project specified
14302 on the command line. The package @code{Builder} of this common project, the
14303 "main project" is the one that is considered by @command{gnatmake}.
14304
14305 @noindent
14306 When ^-u^/UNIQUE^ is used, the specified source files may be in projects
14307 imported directly or indirectly by the project specified on the command line.
14308 Note that if such a source file is not part of the project specified on the
14309 command line, the ^switches^switches^ found in package @code{Builder} of the
14310 project specified on the command line, if any, that are transmitted
14311 to the compiler will still be used, not those found in the project file of
14312 the source file.
14313
14314 @noindent
14315 When using a project file, you can also invoke @command{gnatmake} without
14316 explicitly specifying any main, and the effect depends on whether you have
14317 defined the @code{Main} attribute.  This attribute has a string list value,
14318 where each element in the list is the name of a source file (the file
14319 extension is optional) that contains a unit that can be a main subprogram.
14320
14321 If the @code{Main} attribute is defined in a project file as a non-empty
14322 string list and the switch @option{^-u^/UNIQUE^} is not used on the command
14323 line, then invoking @command{gnatmake} with this project file but without any
14324 main on the command line is equivalent to invoking @command{gnatmake} with all
14325 the file names in the @code{Main} attribute on the command line.
14326
14327 Example:
14328 @smallexample @c projectfile
14329 @group
14330    project Prj is
14331       for Main use ("main1", "main2", "main3");
14332    end Prj;
14333 @end group
14334 @end smallexample
14335
14336 @noindent
14337 With this project file, @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^"}
14338 is equivalent to
14339 @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^ main1 main2 main3"}.
14340
14341 When the project attribute @code{Main} is not specified, or is specified
14342 as an empty string list, or when the switch @option{-u} is used on the command
14343 line, then invoking @command{gnatmake} with no main on the command line will
14344 result in all immediate sources of the project file being checked, and
14345 potentially recompiled. Depending on the presence of the switch @option{-u},
14346 sources from other project files on which the immediate sources of the main
14347 project file depend are also checked and potentially recompiled. In other
14348 words, the @option{-u} switch is applied to all of the immediate sources of the
14349 main project file.
14350
14351 When no main is specified on the command line and attribute @code{Main} exists
14352 and includes several mains, or when several mains are specified on the
14353 command line, the default ^switches^switches^ in package @code{Builder} will
14354 be used for all mains, even if there are specific ^switches^switches^
14355 specified for one or several mains.
14356
14357 But the ^switches^switches^ from package @code{Binder} or @code{Linker} will be
14358 the specific ^switches^switches^ for each main, if they are specified.
14359
14360 @node Library Project Files
14361 @subsubsection Library Project Files
14362
14363 @noindent
14364 When @command{gnatmake} is invoked with a main project file that is a library
14365 project file, it is not allowed to specify one or more mains on the command
14366 line.
14367
14368 @noindent
14369 When a library project file is specified, switches ^-b^/ACTION=BIND^ and
14370 ^-l^/ACTION=LINK^ have special meanings.
14371
14372 @itemize @bullet
14373 @item ^-b^/ACTION=BIND^ is only allowed for stand-alone libraries. It indicates
14374 to @command{gnatmake} that @command{gnatbind} should be invoked for the
14375 library.
14376
14377 @item ^-l^/ACTION=LINK^ may be used for all library projects. It indicates
14378 to @command{gnatmake} that the binder generated file should be compiled
14379 (in the case of a stand-alone library) and that the library should be built.
14380
14381 @end itemize
14382
14383 @node The GNAT Driver and Project Files
14384 @subsection The GNAT Driver and Project Files
14385
14386 @noindent
14387 A number of GNAT tools, other than @command{^gnatmake^gnatmake^}
14388 can benefit from project files:
14389 @command{^gnatbind^gnatbind^},
14390 @command{^gnatcheck^gnatcheck^}),
14391 @command{^gnatclean^gnatclean^}),
14392 @command{^gnatelim^gnatelim^},
14393 @command{^gnatfind^gnatfind^},
14394 @command{^gnatlink^gnatlink^},
14395 @command{^gnatls^gnatls^},
14396 @command{^gnatmetric^gnatmetric^},
14397 @command{^gnatpp^gnatpp^},
14398 @command{^gnatstub^gnatstub^},
14399 and @command{^gnatxref^gnatxref^}. However, none of these tools can be invoked
14400 directly with a project file switch (@option{^-P^/PROJECT_FILE=^}).
14401 They must be invoked through the @command{gnat} driver.
14402
14403 The @command{gnat} driver is a wrapper that accepts a number of commands and
14404 calls the corresponding tool. It was designed initially for VMS platforms (to
14405 convert VMS qualifiers to Unix-style switches), but it is now available on all
14406 GNAT platforms.
14407
14408 On non-VMS platforms, the @command{gnat} driver accepts the following commands
14409 (case insensitive):
14410
14411 @itemize @bullet
14412 @item
14413 BIND to invoke @command{^gnatbind^gnatbind^}
14414 @item
14415 CHOP to invoke @command{^gnatchop^gnatchop^}
14416 @item
14417 CLEAN to invoke @command{^gnatclean^gnatclean^}
14418 @item
14419 COMP or COMPILE to invoke the compiler
14420 @item
14421 ELIM to invoke @command{^gnatelim^gnatelim^}
14422 @item
14423 FIND to invoke @command{^gnatfind^gnatfind^}
14424 @item
14425 KR or KRUNCH to invoke @command{^gnatkr^gnatkr^}
14426 @item
14427 LINK to invoke @command{^gnatlink^gnatlink^}
14428 @item
14429 LS or LIST to invoke @command{^gnatls^gnatls^}
14430 @item
14431 MAKE to invoke @command{^gnatmake^gnatmake^}
14432 @item
14433 NAME to invoke @command{^gnatname^gnatname^}
14434 @item
14435 PREP or PREPROCESS to invoke @command{^gnatprep^gnatprep^}
14436 @item
14437 PP or PRETTY to invoke @command{^gnatpp^gnatpp^}
14438 @item
14439 METRIC to invoke @command{^gnatmetric^gnatmetric^}
14440 @item
14441 STUB to invoke @command{^gnatstub^gnatstub^}
14442 @item
14443 XREF to invoke @command{^gnatxref^gnatxref^}
14444 @end itemize
14445
14446 @noindent
14447 (note that the compiler is invoked using the command
14448 @command{^gnatmake -f -u -c^gnatmake -f -u -c^}).
14449
14450 @noindent
14451 On non-VMS platforms, between @command{gnat} and the command, two
14452 special switches may be used:
14453
14454 @itemize @bullet
14455 @item
14456 @command{-v} to display the invocation of the tool.
14457 @item
14458 @command{-dn} to prevent the @command{gnat} driver from removing
14459 the temporary files it has created. These temporary files are
14460 configuration files and temporary file list files.
14461 @end itemize
14462
14463 @noindent
14464 The command may be followed by switches and arguments for the invoked
14465 tool.
14466
14467 @smallexample
14468   gnat bind -C main.ali
14469   gnat ls -a main
14470   gnat chop foo.txt
14471 @end smallexample
14472
14473 @noindent
14474 Switches may also be put in text files, one switch per line, and the text
14475 files may be specified with their path name preceded by '@@'.
14476
14477 @smallexample
14478    gnat bind @@args.txt main.ali
14479 @end smallexample
14480
14481 @noindent
14482 In addition, for commands BIND, COMP or COMPILE, FIND, ELIM, LS or LIST, LINK,
14483 METRIC, PP or PRETTY, STUB and XREF, the project file related switches
14484 (@option{^-P^/PROJECT_FILE^},
14485 @option{^-X^/EXTERNAL_REFERENCE^} and
14486 @option{^-vP^/MESSAGES_PROJECT_FILE=^x}) may be used in addition to
14487 the switches of the invoking tool.
14488
14489 @noindent
14490 When GNAT PP or GNAT PRETTY is used with a project file, but with no source
14491 specified on the command line, it invokes @command{^gnatpp^gnatpp^} with all
14492 the immediate sources of the specified project file.
14493
14494 @noindent
14495 When GNAT METRIC is used with a project file, but with no source
14496 specified on the command line, it invokes @command{^gnatmetric^gnatmetric^}
14497 with all the immediate sources of the specified project file and with
14498 @option{^-d^/DIRECTORY^} with the parameter pointing to the object directory
14499 of the project.
14500
14501 @noindent
14502 In addition, when GNAT PP, GNAT PRETTY or GNAT METRIC is used with
14503 a project file, no source is specified on the command line and
14504 switch ^-U^/ALL_PROJECTS^ is specified on the command line, then
14505 the underlying tool (^gnatpp^gnatpp^ or
14506 ^gnatmetric^gnatmetric^) is invoked for all sources of all projects,
14507 not only for the immediate sources of the main project.
14508 @ifclear vms
14509 (-U stands for Universal or Union of the project files of the project tree)
14510 @end ifclear
14511
14512 @noindent
14513 For each of the following commands, there is optionally a corresponding
14514 package in the main project.
14515
14516 @itemize @bullet
14517 @item
14518 package @code{Binder} for command BIND (invoking @code{^gnatbind^gnatbind^})
14519
14520 @item
14521 package @code{Check} for command CHECK (invoking
14522 @code{^gnatcheck^gnatcheck^})
14523
14524 @item
14525 package @code{Compiler} for command COMP or COMPILE (invoking the compiler)
14526
14527 @item
14528 package @code{Cross_Reference} for command XREF (invoking
14529 @code{^gnatxref^gnatxref^})
14530
14531 @item
14532 package @code{Eliminate} for command ELIM (invoking
14533 @code{^gnatelim^gnatelim^})
14534
14535 @item
14536 package @code{Finder} for command FIND (invoking @code{^gnatfind^gnatfind^})
14537
14538 @item
14539 package @code{Gnatls} for command LS or LIST (invoking @code{^gnatls^gnatls^})
14540
14541 @item
14542 package @code{Gnatstub} for command STUB
14543 (invoking @code{^gnatstub^gnatstub^})
14544
14545 @item
14546 package @code{Linker} for command LINK (invoking @code{^gnatlink^gnatlink^})
14547
14548 @item
14549 package @code{Metrics} for command METRIC
14550 (invoking @code{^gnatmetric^gnatmetric^})
14551
14552 @item
14553 package @code{Pretty_Printer} for command PP or PRETTY
14554 (invoking @code{^gnatpp^gnatpp^})
14555
14556 @end itemize
14557
14558 @noindent
14559 Package @code{Gnatls} has a unique attribute @code{^Switches^Switches^},
14560 a simple variable with a string list value. It contains ^switches^switches^
14561 for the invocation of @code{^gnatls^gnatls^}.
14562
14563 @smallexample @c projectfile
14564 @group
14565 project Proj1 is
14566    package gnatls is
14567       for ^Switches^Switches^
14568           use ("^-a^-a^",
14569                "^-v^-v^");
14570    end gnatls;
14571 end Proj1;
14572 @end group
14573 @end smallexample
14574
14575 @noindent
14576 All other packages have two attribute @code{^Switches^Switches^} and
14577 @code{^Default_Switches^Default_Switches^}.
14578
14579 @noindent
14580 @code{^Switches^Switches^} is an associative array attribute, indexed by the
14581 source file name, that has a string list value: the ^switches^switches^ to be
14582 used when the tool corresponding to the package is invoked for the specific
14583 source file.
14584
14585 @noindent
14586 @code{^Default_Switches^Default_Switches^} is an associative array attribute,
14587 indexed by  the programming language that has a string list value.
14588 @code{^Default_Switches^Default_Switches^ ("Ada")} contains the
14589 ^switches^switches^ for the invocation of the tool corresponding
14590 to the package, except if a specific @code{^Switches^Switches^} attribute
14591 is specified for the source file.
14592
14593 @smallexample @c projectfile
14594 @group
14595 project Proj is
14596
14597    for Source_Dirs use ("./**");
14598
14599    package gnatls is
14600       for ^Switches^Switches^ use
14601           ("^-a^-a^",
14602            "^-v^-v^");
14603    end gnatls;
14604 @end group
14605 @group
14606
14607    package Compiler is
14608       for ^Default_Switches^Default_Switches^ ("Ada")
14609           use ("^-gnatv^-gnatv^",
14610                "^-gnatwa^-gnatwa^");
14611    end Binder;
14612 @end group
14613 @group
14614
14615    package Binder is
14616       for ^Default_Switches^Default_Switches^ ("Ada")
14617           use ("^-C^-C^",
14618                "^-e^-e^");
14619    end Binder;
14620 @end group
14621 @group
14622
14623    package Linker is
14624       for ^Default_Switches^Default_Switches^ ("Ada")
14625           use ("^-C^-C^");
14626       for ^Switches^Switches^ ("main.adb")
14627           use ("^-C^-C^",
14628                "^-v^-v^",
14629                "^-v^-v^");
14630    end Linker;
14631 @end group
14632 @group
14633
14634    package Finder is
14635       for ^Default_Switches^Default_Switches^ ("Ada")
14636            use ("^-a^-a^",
14637                 "^-f^-f^");
14638    end Finder;
14639 @end group
14640 @group
14641
14642    package Cross_Reference is
14643       for ^Default_Switches^Default_Switches^ ("Ada")
14644           use ("^-a^-a^",
14645                "^-f^-f^",
14646                "^-d^-d^",
14647                "^-u^-u^");
14648    end Cross_Reference;
14649 end Proj;
14650 @end group
14651 @end smallexample
14652
14653 @noindent
14654 With the above project file, commands such as
14655
14656 @smallexample
14657    ^gnat comp -Pproj main^GNAT COMP /PROJECT_FILE=PROJ MAIN^
14658    ^gnat ls -Pproj main^GNAT LIST /PROJECT_FILE=PROJ MAIN^
14659    ^gnat xref -Pproj main^GNAT XREF /PROJECT_FILE=PROJ MAIN^
14660    ^gnat bind -Pproj main.ali^GNAT BIND /PROJECT_FILE=PROJ MAIN.ALI^
14661    ^gnat link -Pproj main.ali^GNAT LINK /PROJECT_FILE=PROJ MAIN.ALI^
14662 @end smallexample
14663
14664 @noindent
14665 will set up the environment properly and invoke the tool with the switches
14666 found in the package corresponding to the tool:
14667 @code{^Default_Switches^Default_Switches^ ("Ada")} for all tools,
14668 except @code{^Switches^Switches^ ("main.adb")}
14669 for @code{^gnatlink^gnatlink^}.
14670 It is also possible to invoke some of the tools,
14671 @code{^gnatcheck^gnatcheck^}),
14672 @code{^gnatmetric^gnatmetric^}),
14673 and @code{^gnatpp^gnatpp^})
14674 on a set of project units thanks to the combination of the switches
14675 @option{-P}, @option{-U} and possibly the main unit when one is interested
14676 in its closure. For instance,
14677 @smallexample
14678 gnat metric -Pproj
14679 @end smallexample
14680 will compute the metrics for all the immediate units of project
14681 @code{proj}.
14682 @smallexample
14683 gnat metric -Pproj -U
14684 @end smallexample
14685 will compute the metrics for all the units of the closure of projects
14686 rooted at @code{proj}.
14687 @smallexample
14688 gnat metric -Pproj -U main_unit
14689 @end smallexample
14690 will compute the metrics for the closure of units rooted at
14691 @code{main_unit}. This last possibility relies implicitly
14692 on @command{gnatbind}'s option @option{-R}.
14693
14694 @c **********************
14695 @node An Extended Example
14696 @section An Extended Example
14697
14698 @noindent
14699 Suppose that we have two programs, @var{prog1} and @var{prog2},
14700 whose sources are in corresponding directories. We would like
14701 to build them with a single @command{gnatmake} command, and we want to place
14702 their object files into @file{build} subdirectories of the source directories.
14703 Furthermore, we want to have to have two separate subdirectories
14704 in @file{build}  -- @file{release} and @file{debug} -- which will contain
14705 the object files compiled with different set of compilation flags.
14706
14707 In other words, we have the following structure:
14708
14709 @smallexample
14710 @group
14711    main
14712      |- prog1
14713      |    |- build
14714      |         | debug
14715      |         | release
14716      |- prog2
14717           |- build
14718                | debug
14719                | release
14720 @end group
14721 @end smallexample
14722
14723 @noindent
14724 Here are the project files that we must place in a directory @file{main}
14725 to maintain this structure:
14726
14727 @enumerate
14728
14729 @item We create a @code{Common} project with a package @code{Compiler} that
14730 specifies the compilation ^switches^switches^:
14731
14732 @smallexample
14733 File "common.gpr":
14734 @group
14735 @b{project} Common @b{is}
14736
14737    @b{for} Source_Dirs @b{use} (); -- No source files
14738 @end group
14739
14740 @group
14741    @b{type} Build_Type @b{is} ("release", "debug");
14742    Build : Build_Type := External ("BUILD", "debug");
14743 @end group
14744 @group
14745    @b{package} Compiler @b{is}
14746       @b{case} Build @b{is}
14747          @b{when} "release" =>
14748            @b{for} ^Default_Switches^Default_Switches^ ("Ada")
14749                    @b{use} ("^-O2^-O2^");
14750          @b{when} "debug"   =>
14751            @b{for} ^Default_Switches^Default_Switches^ ("Ada")
14752                    @b{use} ("^-g^-g^");
14753       @b{end case};
14754    @b{end} Compiler;
14755
14756 @b{end} Common;
14757 @end group
14758 @end smallexample
14759
14760 @item We create separate projects for the two programs:
14761
14762 @smallexample
14763 @group
14764 File "prog1.gpr":
14765
14766 @b{with} "common";
14767 @b{project} Prog1 @b{is}
14768
14769     @b{for} Source_Dirs @b{use} ("prog1");
14770     @b{for} Object_Dir  @b{use} "prog1/build/" & Common.Build;
14771
14772     @b{package} Compiler @b{renames} Common.Compiler;
14773
14774 @b{end} Prog1;
14775 @end group
14776 @end smallexample
14777
14778 @smallexample
14779 @group
14780 File "prog2.gpr":
14781
14782 @b{with} "common";
14783 @b{project} Prog2 @b{is}
14784
14785     @b{for} Source_Dirs @b{use} ("prog2");
14786     @b{for} Object_Dir  @b{use} "prog2/build/" & Common.Build;
14787
14788     @b{package} Compiler @b{renames} Common.Compiler;
14789
14790 @end group
14791 @b{end} Prog2;
14792 @end smallexample
14793
14794 @item We create a wrapping project @code{Main}:
14795
14796 @smallexample
14797 @group
14798 File "main.gpr":
14799
14800 @b{with} "common";
14801 @b{with} "prog1";
14802 @b{with} "prog2";
14803 @b{project} Main @b{is}
14804
14805    @b{package} Compiler @b{renames} Common.Compiler;
14806
14807 @b{end} Main;
14808 @end group
14809 @end smallexample
14810
14811 @item Finally we need to create a dummy procedure that @code{with}s (either
14812 explicitly or implicitly) all the sources of our two programs.
14813
14814 @end enumerate
14815
14816 @noindent
14817 Now we can build the programs using the command
14818
14819 @smallexample
14820    gnatmake ^-P^/PROJECT_FILE=^main dummy
14821 @end smallexample
14822
14823 @noindent
14824 for the Debug mode, or
14825
14826 @ifclear vms
14827 @smallexample
14828    gnatmake -Pmain -XBUILD=release
14829 @end smallexample
14830 @end ifclear
14831
14832 @ifset vms
14833 @smallexample
14834    GNAT MAKE /PROJECT_FILE=main /EXTERNAL_REFERENCE=BUILD=release
14835 @end smallexample
14836 @end ifset
14837
14838 @noindent
14839 for the Release mode.
14840
14841 @c ********************************
14842 @c * Project File Complete Syntax *
14843 @c ********************************
14844
14845 @node Project File Complete Syntax
14846 @section Project File Complete Syntax
14847
14848 @smallexample
14849 project ::=
14850   context_clause project_declaration
14851
14852 context_clause ::=
14853   @{with_clause@}
14854
14855 with_clause ::=
14856   @b{with} path_name @{ , path_name @} ;
14857
14858 path_name ::=
14859    string_literal
14860
14861 project_declaration ::=
14862   simple_project_declaration | project_extension
14863
14864 simple_project_declaration ::=
14865   @b{project} <project_>simple_name @b{is}
14866     @{declarative_item@}
14867   @b{end} <project_>simple_name;
14868
14869 project_extension ::=
14870   @b{project} <project_>simple_name  @b{extends} path_name @b{is}
14871     @{declarative_item@}
14872   @b{end} <project_>simple_name;
14873
14874 declarative_item ::=
14875   package_declaration |
14876   typed_string_declaration |
14877   other_declarative_item
14878
14879 package_declaration ::=
14880   package_spec | package_renaming
14881
14882 package_spec ::=
14883   @b{package} package_identifier @b{is}
14884     @{simple_declarative_item@}
14885   @b{end} package_identifier ;
14886
14887 package_identifier ::=
14888   @code{Naming} | @code{Builder} | @code{Compiler} | @code{Binder} |
14889   @code{Linker} | @code{Finder}  | @code{Cross_Reference} |
14890   @code{^gnatls^gnatls^} | @code{IDE}     | @code{Pretty_Printer}
14891
14892 package_renaming ::==
14893   @b{package} package_identifier @b{renames}
14894        <project_>simple_name.package_identifier ;
14895
14896 typed_string_declaration ::=
14897   @b{type} <typed_string_>_simple_name @b{is}
14898    ( string_literal @{, string_literal@} );
14899
14900 other_declarative_item ::=
14901   attribute_declaration |
14902   typed_variable_declaration |
14903   variable_declaration |
14904   case_construction
14905
14906 attribute_declaration ::=
14907   full_associative_array_declaration |
14908   @b{for} attribute_designator @b{use} expression ;
14909
14910 full_associative_array_declaration ::=
14911   @b{for} <associative_array_attribute_>simple_name @b{use}
14912   <project_>simple_name [ . <package_>simple_Name ] ' <attribute_>simple_name ;
14913
14914 attribute_designator ::=
14915   <simple_attribute_>simple_name |
14916   <associative_array_attribute_>simple_name ( string_literal )
14917
14918 typed_variable_declaration ::=
14919   <typed_variable_>simple_name : <typed_string_>name :=  string_expression ;
14920
14921 variable_declaration ::=
14922   <variable_>simple_name := expression;
14923
14924 expression ::=
14925   term @{& term@}
14926
14927 term ::=
14928   literal_string |
14929   string_list |
14930   <variable_>name |
14931   external_value |
14932   attribute_reference
14933
14934 string_literal ::=
14935   (same as Ada)
14936
14937 string_list ::=
14938   ( <string_>expression @{ , <string_>expression @} )
14939
14940 external_value ::=
14941   @b{external} ( string_literal [, string_literal] )
14942
14943 attribute_reference ::=
14944   attribute_prefix ' <simple_attribute_>simple_name [ ( literal_string ) ]
14945
14946 attribute_prefix ::=
14947   @b{project} |
14948   <project_>simple_name | package_identifier |
14949   <project_>simple_name . package_identifier
14950
14951 case_construction ::=
14952   @b{case} <typed_variable_>name @b{is}
14953     @{case_item@}
14954   @b{end case} ;
14955
14956 case_item ::=
14957   @b{when} discrete_choice_list =>
14958       @{case_construction | attribute_declaration@}
14959
14960 discrete_choice_list ::=
14961   string_literal @{| string_literal@} |
14962   @b{others}
14963
14964 name ::=
14965   simple_name @{. simple_name@}
14966
14967 simple_name ::=
14968   identifier (same as Ada)
14969
14970 @end smallexample
14971
14972 @node The Cross-Referencing Tools gnatxref and gnatfind
14973 @chapter  The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
14974 @findex gnatxref
14975 @findex gnatfind
14976
14977 @noindent
14978 The compiler generates cross-referencing information (unless
14979 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
14980 This information indicates where in the source each entity is declared and
14981 referenced. Note that entities in package Standard are not included, but
14982 entities in all other predefined units are included in the output.
14983
14984 Before using any of these two tools, you need to compile successfully your
14985 application, so that GNAT gets a chance to generate the cross-referencing
14986 information.
14987
14988 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
14989 information to provide the user with the capability to easily locate the
14990 declaration and references to an entity. These tools are quite similar,
14991 the difference being that @code{gnatfind} is intended for locating
14992 definitions and/or references to a specified entity or entities, whereas
14993 @code{gnatxref} is oriented to generating a full report of all
14994 cross-references.
14995
14996 To use these tools, you must not compile your application using the
14997 @option{-gnatx} switch on the @command{gnatmake} command line
14998 (@pxref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
14999 information will not be generated.
15000
15001 Note: to invoke @code{gnatxref} or @code{gnatfind} with a project file,
15002 use the @code{gnat} driver (see @ref{The GNAT Driver and Project Files}).
15003
15004 @menu
15005 * gnatxref Switches::
15006 * gnatfind Switches::
15007 * Project Files for gnatxref and gnatfind::
15008 * Regular Expressions in gnatfind and gnatxref::
15009 * Examples of gnatxref Usage::
15010 * Examples of gnatfind Usage::
15011 @end menu
15012
15013 @node gnatxref Switches
15014 @section @code{gnatxref} Switches
15015
15016 @noindent
15017 The command invocation for @code{gnatxref} is:
15018 @smallexample
15019 $ gnatxref @ovar{switches} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
15020 @end smallexample
15021
15022 @noindent
15023 where
15024
15025 @table @var
15026 @item sourcefile1
15027 @itemx sourcefile2
15028 identifies the source files for which a report is to be generated. The
15029 ``with''ed units will be processed too. You must provide at least one file.
15030
15031 These file names are considered to be regular expressions, so for instance
15032 specifying @file{source*.adb} is the same as giving every file in the current
15033 directory whose name starts with @file{source} and whose extension is
15034 @file{adb}.
15035
15036 You shouldn't specify any directory name, just base names. @command{gnatxref}
15037 and @command{gnatfind} will be able to locate these files by themselves using
15038 the source path. If you specify directories, no result is produced.
15039
15040 @end table
15041
15042 @noindent
15043 The switches can be:
15044 @table @option
15045 @c !sort!
15046 @item --version
15047 @cindex @option{--version} @command{gnatxref}
15048 Display Copyright and version, then exit disregarding all other options.
15049
15050 @item --help
15051 @cindex @option{--help} @command{gnatxref}
15052 If @option{--version} was not used, display usage, then exit disregarding
15053 all other options.
15054
15055 @item ^-a^/ALL_FILES^
15056 @cindex @option{^-a^/ALL_FILES^} (@command{gnatxref})
15057 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
15058 the read-only files found in the library search path. Otherwise, these files
15059 will be ignored. This option can be used to protect Gnat sources or your own
15060 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
15061 much faster, and their output much smaller. Read-only here refers to access
15062 or permissions status in the file system for the current user.
15063
15064 @item -aIDIR
15065 @cindex @option{-aIDIR} (@command{gnatxref})
15066 When looking for source files also look in directory DIR. The order in which
15067 source file search is undertaken is the same as for @command{gnatmake}.
15068
15069 @item -aODIR
15070 @cindex @option{-aODIR} (@command{gnatxref})
15071 When searching for library and object files, look in directory
15072 DIR. The order in which library files are searched is the same as for
15073 @command{gnatmake}.
15074
15075 @item -nostdinc
15076 @cindex @option{-nostdinc} (@command{gnatxref})
15077 Do not look for sources in the system default directory.
15078
15079 @item -nostdlib
15080 @cindex @option{-nostdlib} (@command{gnatxref})
15081 Do not look for library files in the system default directory.
15082
15083 @item --RTS=@var{rts-path}
15084 @cindex @option{--RTS} (@command{gnatxref})
15085 Specifies the default location of the runtime library. Same meaning as the
15086 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
15087
15088 @item ^-d^/DERIVED_TYPES^
15089 @cindex @option{^-d^/DERIVED_TYPES^} (@command{gnatxref})
15090 If this switch is set @code{gnatxref} will output the parent type
15091 reference for each matching derived types.
15092
15093 @item ^-f^/FULL_PATHNAME^
15094 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatxref})
15095 If this switch is set, the output file names will be preceded by their
15096 directory (if the file was found in the search path). If this switch is
15097 not set, the directory will not be printed.
15098
15099 @item ^-g^/IGNORE_LOCALS^
15100 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatxref})
15101 If this switch is set, information is output only for library-level
15102 entities, ignoring local entities. The use of this switch may accelerate
15103 @code{gnatfind} and @code{gnatxref}.
15104
15105 @item -IDIR
15106 @cindex @option{-IDIR} (@command{gnatxref})
15107 Equivalent to @samp{-aODIR -aIDIR}.
15108
15109 @item -pFILE
15110 @cindex @option{-pFILE} (@command{gnatxref})
15111 Specify a project file to use @xref{Project Files}.
15112 If you need to use the @file{.gpr}
15113 project files, you should use gnatxref through the GNAT driver
15114 (@command{gnat xref -Pproject}).
15115
15116 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
15117 project file in the current directory.
15118
15119 If a project file is either specified or found by the tools, then the content
15120 of the source directory and object directory lines are added as if they
15121 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^}
15122 and @samp{^-aO^OBJECT_SEARCH^}.
15123 @item ^-u^/UNUSED^
15124 Output only unused symbols. This may be really useful if you give your
15125 main compilation unit on the command line, as @code{gnatxref} will then
15126 display every unused entity and 'with'ed package.
15127
15128 @ifclear vms
15129 @item -v
15130 Instead of producing the default output, @code{gnatxref} will generate a
15131 @file{tags} file that can be used by vi. For examples how to use this
15132 feature, see @ref{Examples of gnatxref Usage}. The tags file is output
15133 to the standard output, thus you will have to redirect it to a file.
15134 @end ifclear
15135
15136 @end table
15137
15138 @noindent
15139 All these switches may be in any order on the command line, and may even
15140 appear after the file names. They need not be separated by spaces, thus
15141 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
15142 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
15143
15144 @node gnatfind Switches
15145 @section @code{gnatfind} Switches
15146
15147 @noindent
15148 The command line for @code{gnatfind} is:
15149
15150 @smallexample
15151 $ gnatfind @ovar{switches} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
15152       @r{[}@var{file1} @var{file2} @dots{}]
15153 @end smallexample
15154
15155 @noindent
15156 where
15157
15158 @table @var
15159 @item pattern
15160 An entity will be output only if it matches the regular expression found
15161 in @var{pattern}, see @ref{Regular Expressions in gnatfind and gnatxref}.
15162
15163 Omitting the pattern is equivalent to specifying @samp{*}, which
15164 will match any entity. Note that if you do not provide a pattern, you
15165 have to provide both a sourcefile and a line.
15166
15167 Entity names are given in Latin-1, with uppercase/lowercase equivalence
15168 for matching purposes. At the current time there is no support for
15169 8-bit codes other than Latin-1, or for wide characters in identifiers.
15170
15171 @item sourcefile
15172 @code{gnatfind} will look for references, bodies or declarations
15173 of symbols referenced in @file{@var{sourcefile}}, at line @var{line}
15174 and column @var{column}. See @ref{Examples of gnatfind Usage}
15175 for syntax examples.
15176
15177 @item line
15178 is a decimal integer identifying the line number containing
15179 the reference to the entity (or entities) to be located.
15180
15181 @item column
15182 is a decimal integer identifying the exact location on the
15183 line of the first character of the identifier for the
15184 entity reference. Columns are numbered from 1.
15185
15186 @item file1 file2 @dots{}
15187 The search will be restricted to these source files. If none are given, then
15188 the search will be done for every library file in the search path.
15189 These file must appear only after the pattern or sourcefile.
15190
15191 These file names are considered to be regular expressions, so for instance
15192 specifying @file{source*.adb} is the same as giving every file in the current
15193 directory whose name starts with @file{source} and whose extension is
15194 @file{adb}.
15195
15196 The location of the spec of the entity will always be displayed, even if it
15197 isn't in one of @file{@var{file1}}, @file{@var{file2}},@enddots{}  The
15198 occurrences of the entity in the separate units of the ones given on the
15199 command line will also be displayed.
15200
15201 Note that if you specify at least one file in this part, @code{gnatfind} may
15202 sometimes not be able to find the body of the subprograms.
15203
15204 @end table
15205
15206 @noindent
15207 At least one of 'sourcefile' or 'pattern' has to be present on
15208 the command line.
15209
15210 The following switches are available:
15211 @table @option
15212 @c !sort!
15213
15214 @cindex @option{--version} @command{gnatfind}
15215 Display Copyright and version, then exit disregarding all other options.
15216
15217 @item --help
15218 @cindex @option{--help} @command{gnatfind}
15219 If @option{--version} was not used, display usage, then exit disregarding
15220 all other options.
15221
15222 @item ^-a^/ALL_FILES^
15223 @cindex @option{^-a^/ALL_FILES^} (@command{gnatfind})
15224 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
15225 the read-only files found in the library search path. Otherwise, these files
15226 will be ignored. This option can be used to protect Gnat sources or your own
15227 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
15228 much faster, and their output much smaller. Read-only here refers to access
15229 or permission status in the file system for the current user.
15230
15231 @item -aIDIR
15232 @cindex @option{-aIDIR} (@command{gnatfind})
15233 When looking for source files also look in directory DIR. The order in which
15234 source file search is undertaken is the same as for @command{gnatmake}.
15235
15236 @item -aODIR
15237 @cindex @option{-aODIR} (@command{gnatfind})
15238 When searching for library and object files, look in directory
15239 DIR. The order in which library files are searched is the same as for
15240 @command{gnatmake}.
15241
15242 @item -nostdinc
15243 @cindex @option{-nostdinc} (@command{gnatfind})
15244 Do not look for sources in the system default directory.
15245
15246 @item -nostdlib
15247 @cindex @option{-nostdlib} (@command{gnatfind})
15248 Do not look for library files in the system default directory.
15249
15250 @item --RTS=@var{rts-path}
15251 @cindex @option{--RTS} (@command{gnatfind})
15252 Specifies the default location of the runtime library. Same meaning as the
15253 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
15254
15255 @item ^-d^/DERIVED_TYPE_INFORMATION^
15256 @cindex @option{^-d^/DERIVED_TYPE_INFORMATION^} (@code{gnatfind})
15257 If this switch is set, then @code{gnatfind} will output the parent type
15258 reference for each matching derived types.
15259
15260 @item ^-e^/EXPRESSIONS^
15261 @cindex @option{^-e^/EXPRESSIONS^} (@command{gnatfind})
15262 By default, @code{gnatfind} accept the simple regular expression set for
15263 @samp{pattern}. If this switch is set, then the pattern will be
15264 considered as full Unix-style regular expression.
15265
15266 @item ^-f^/FULL_PATHNAME^
15267 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatfind})
15268 If this switch is set, the output file names will be preceded by their
15269 directory (if the file was found in the search path). If this switch is
15270 not set, the directory will not be printed.
15271
15272 @item ^-g^/IGNORE_LOCALS^
15273 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatfind})
15274 If this switch is set, information is output only for library-level
15275 entities, ignoring local entities. The use of this switch may accelerate
15276 @code{gnatfind} and @code{gnatxref}.
15277
15278 @item -IDIR
15279 @cindex @option{-IDIR} (@command{gnatfind})
15280 Equivalent to @samp{-aODIR -aIDIR}.
15281
15282 @item -pFILE
15283 @cindex @option{-pFILE} (@command{gnatfind})
15284 Specify a project file (@pxref{Project Files}) to use.
15285 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
15286 project file in the current directory.
15287
15288 If a project file is either specified or found by the tools, then the content
15289 of the source directory and object directory lines are added as if they
15290 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and
15291 @samp{^-aO^/OBJECT_SEARCH^}.
15292
15293 @item ^-r^/REFERENCES^
15294 @cindex @option{^-r^/REFERENCES^} (@command{gnatfind})
15295 By default, @code{gnatfind} will output only the information about the
15296 declaration, body or type completion of the entities. If this switch is
15297 set, the @code{gnatfind} will locate every reference to the entities in
15298 the files specified on the command line (or in every file in the search
15299 path if no file is given on the command line).
15300
15301 @item ^-s^/PRINT_LINES^
15302 @cindex @option{^-s^/PRINT_LINES^} (@command{gnatfind})
15303 If this switch is set, then @code{gnatfind} will output the content
15304 of the Ada source file lines were the entity was found.
15305
15306 @item ^-t^/TYPE_HIERARCHY^
15307 @cindex @option{^-t^/TYPE_HIERARCHY^} (@command{gnatfind})
15308 If this switch is set, then @code{gnatfind} will output the type hierarchy for
15309 the specified type. It act like -d option but recursively from parent
15310 type to parent type. When this switch is set it is not possible to
15311 specify more than one file.
15312
15313 @end table
15314
15315 @noindent
15316 All these switches may be in any order on the command line, and may even
15317 appear after the file names. They need not be separated by spaces, thus
15318 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
15319 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
15320
15321 As stated previously, gnatfind will search in every directory in the
15322 search path. You can force it to look only in the current directory if
15323 you specify @code{*} at the end of the command line.
15324
15325 @node Project Files for gnatxref and gnatfind
15326 @section Project Files for @command{gnatxref} and @command{gnatfind}
15327
15328 @noindent
15329 Project files allow a programmer to specify how to compile its
15330 application, where to find sources, etc.  These files are used
15331 @ifclear vms
15332 primarily by GPS, but they can also be used
15333 @end ifclear
15334 by the two tools
15335 @code{gnatxref} and @code{gnatfind}.
15336
15337 A project file name must end with @file{.gpr}. If a single one is
15338 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
15339 extract the information from it. If multiple project files are found, none of
15340 them is read, and you have to use the @samp{-p} switch to specify the one
15341 you want to use.
15342
15343 The following lines can be included, even though most of them have default
15344 values which can be used in most cases.
15345 The lines can be entered in any order in the file.
15346 Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
15347 each line. If you have multiple instances, only the last one is taken into
15348 account.
15349
15350 @table @code
15351 @item src_dir=DIR
15352 [default: @code{"^./^[]^"}]
15353 specifies a directory where to look for source files. Multiple @code{src_dir}
15354 lines can be specified and they will be searched in the order they
15355 are specified.
15356
15357 @item obj_dir=DIR
15358 [default: @code{"^./^[]^"}]
15359 specifies a directory where to look for object and library files. Multiple
15360 @code{obj_dir} lines can be specified, and they will be searched in the order
15361 they are specified
15362
15363 @item comp_opt=SWITCHES
15364 [default: @code{""}]
15365 creates a variable which can be referred to subsequently by using
15366 the @code{$@{comp_opt@}} notation. This is intended to store the default
15367 switches given to @command{gnatmake} and @command{gcc}.
15368
15369 @item bind_opt=SWITCHES
15370 [default: @code{""}]
15371 creates a variable which can be referred to subsequently by using
15372 the @samp{$@{bind_opt@}} notation. This is intended to store the default
15373 switches given to @command{gnatbind}.
15374
15375 @item link_opt=SWITCHES
15376 [default: @code{""}]
15377 creates a variable which can be referred to subsequently by using
15378 the @samp{$@{link_opt@}} notation. This is intended to store the default
15379 switches given to @command{gnatlink}.
15380
15381 @item main=EXECUTABLE
15382 [default: @code{""}]
15383 specifies the name of the executable for the application. This variable can
15384 be referred to in the following lines by using the @samp{$@{main@}} notation.
15385
15386 @ifset vms
15387 @item comp_cmd=COMMAND
15388 [default: @code{"GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"}]
15389 @end ifset
15390 @ifclear vms
15391 @item comp_cmd=COMMAND
15392 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
15393 @end ifclear
15394 specifies the command used to compile a single file in the application.
15395
15396 @ifset vms
15397 @item make_cmd=COMMAND
15398 [default: @code{"GNAT MAKE $@{main@}
15399 /SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@}
15400 /DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@}
15401 /BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"}]
15402 @end ifset
15403 @ifclear vms
15404 @item make_cmd=COMMAND
15405 [default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
15406 -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
15407 -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
15408 @end ifclear
15409 specifies the command used to recompile the whole application.
15410
15411 @item run_cmd=COMMAND
15412 [default: @code{"$@{main@}"}]
15413 specifies the command used to run the application.
15414
15415 @item debug_cmd=COMMAND
15416 [default: @code{"gdb $@{main@}"}]
15417 specifies the command used to debug the application
15418
15419 @end table
15420
15421 @noindent
15422 @command{gnatxref} and @command{gnatfind} only take into account the
15423 @code{src_dir} and @code{obj_dir} lines, and ignore the others.
15424
15425 @node Regular Expressions in gnatfind and gnatxref
15426 @section  Regular Expressions in @code{gnatfind} and @code{gnatxref}
15427
15428 @noindent
15429 As specified in the section about @command{gnatfind}, the pattern can be a
15430 regular expression. Actually, there are to set of regular expressions
15431 which are recognized by the program:
15432
15433 @table @code
15434 @item globbing patterns
15435 These are the most usual regular expression. They are the same that you
15436 generally used in a Unix shell command line, or in a DOS session.
15437
15438 Here is a more formal grammar:
15439 @smallexample
15440 @group
15441 @iftex
15442 @leftskip=.5cm
15443 @end iftex
15444 regexp ::= term
15445 term   ::= elmt            -- matches elmt
15446 term   ::= elmt elmt       -- concatenation (elmt then elmt)
15447 term   ::= *               -- any string of 0 or more characters
15448 term   ::= ?               -- matches any character
15449 term   ::= [char @{char@}]   -- matches any character listed
15450 term   ::= [char - char]   -- matches any character in range
15451 @end group
15452 @end smallexample
15453
15454 @item full regular expression
15455 The second set of regular expressions is much more powerful. This is the
15456 type of regular expressions recognized by utilities such a @file{grep}.
15457
15458 The following is the form of a regular expression, expressed in Ada
15459 reference manual style BNF is as follows
15460
15461 @smallexample
15462 @iftex
15463 @leftskip=.5cm
15464 @end iftex
15465 @group
15466 regexp ::= term @{| term@}   -- alternation (term or term @dots{})
15467
15468 term ::= item @{item@}       -- concatenation (item then item)
15469
15470 item ::= elmt              -- match elmt
15471 item ::= elmt *            -- zero or more elmt's
15472 item ::= elmt +            -- one or more elmt's
15473 item ::= elmt ?            -- matches elmt or nothing
15474 @end group
15475 @group
15476 elmt ::= nschar            -- matches given character
15477 elmt ::= [nschar @{nschar@}]   -- matches any character listed
15478 elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed
15479 elmt ::= [char - char]     -- matches chars in given range
15480 elmt ::= \ char            -- matches given character
15481 elmt ::= .                 -- matches any single character
15482 elmt ::= ( regexp )        -- parens used for grouping
15483
15484 char ::= any character, including special characters
15485 nschar ::= any character except ()[].*+?^^^
15486 @end group
15487 @end smallexample
15488
15489 Following are a few examples:
15490
15491 @table @samp
15492 @item abcde|fghi
15493 will match any of the two strings @samp{abcde} and @samp{fghi},
15494
15495 @item abc*d
15496 will match any string like @samp{abd}, @samp{abcd}, @samp{abccd},
15497 @samp{abcccd}, and so on,
15498
15499 @item [a-z]+
15500 will match any string which has only lowercase characters in it (and at
15501 least one character.
15502
15503 @end table
15504 @end table
15505
15506 @node Examples of gnatxref Usage
15507 @section Examples of @code{gnatxref} Usage
15508
15509 @subsection General Usage
15510
15511 @noindent
15512 For the following examples, we will consider the following units:
15513
15514 @smallexample @c ada
15515 @group
15516 @cartouche
15517 main.ads:
15518 1: with Bar;
15519 2: package Main is
15520 3:     procedure Foo (B : in Integer);
15521 4:     C : Integer;
15522 5: private
15523 6:     D : Integer;
15524 7: end Main;
15525
15526 main.adb:
15527 1: package body Main is
15528 2:     procedure Foo (B : in Integer) is
15529 3:     begin
15530 4:        C := B;
15531 5:        D := B;
15532 6:        Bar.Print (B);
15533 7:        Bar.Print (C);
15534 8:     end Foo;
15535 9: end Main;
15536
15537 bar.ads:
15538 1: package Bar is
15539 2:     procedure Print (B : Integer);
15540 3: end bar;
15541 @end cartouche
15542 @end group
15543 @end smallexample
15544
15545 @table @code
15546
15547 @noindent
15548 The first thing to do is to recompile your application (for instance, in
15549 that case just by doing a @samp{gnatmake main}, so that GNAT generates
15550 the cross-referencing information.
15551 You can then issue any of the following commands:
15552
15553 @item gnatxref main.adb
15554 @code{gnatxref} generates cross-reference information for main.adb
15555 and every unit 'with'ed by main.adb.
15556
15557 The output would be:
15558 @smallexample
15559 @iftex
15560 @leftskip=0cm
15561 @end iftex
15562 B                                                      Type: Integer
15563   Decl: bar.ads           2:22
15564 B                                                      Type: Integer
15565   Decl: main.ads          3:20
15566   Body: main.adb          2:20
15567   Ref:  main.adb          4:13     5:13     6:19
15568 Bar                                                    Type: Unit
15569   Decl: bar.ads           1:9
15570   Ref:  main.adb          6:8      7:8
15571        main.ads           1:6
15572 C                                                      Type: Integer
15573   Decl: main.ads          4:5
15574   Modi: main.adb          4:8
15575   Ref:  main.adb          7:19
15576 D                                                      Type: Integer
15577   Decl: main.ads          6:5
15578   Modi: main.adb          5:8
15579 Foo                                                    Type: Unit
15580   Decl: main.ads          3:15
15581   Body: main.adb          2:15
15582 Main                                                    Type: Unit
15583   Decl: main.ads          2:9
15584   Body: main.adb          1:14
15585 Print                                                   Type: Unit
15586   Decl: bar.ads           2:15
15587   Ref:  main.adb          6:12     7:12
15588 @end smallexample
15589
15590 @noindent
15591 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
15592 its body is in main.adb, line 1, column 14 and is not referenced any where.
15593
15594 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
15595 it referenced in main.adb, line 6 column 12 and line 7 column 12.
15596
15597 @item gnatxref package1.adb package2.ads
15598 @code{gnatxref} will generates cross-reference information for
15599 package1.adb, package2.ads and any other package 'with'ed by any
15600 of these.
15601
15602 @end table
15603
15604 @ifclear vms
15605 @subsection Using gnatxref with vi
15606
15607 @code{gnatxref} can generate a tags file output, which can be used
15608 directly from @command{vi}. Note that the standard version of @command{vi}
15609 will not work properly with overloaded symbols. Consider using another
15610 free implementation of @command{vi}, such as @command{vim}.
15611
15612 @smallexample
15613 $ gnatxref -v gnatfind.adb > tags
15614 @end smallexample
15615
15616 @noindent
15617 will generate the tags file for @code{gnatfind} itself (if the sources
15618 are in the search path!).
15619
15620 From @command{vi}, you can then use the command @samp{:tag @var{entity}}
15621 (replacing @var{entity} by whatever you are looking for), and vi will
15622 display a new file with the corresponding declaration of entity.
15623 @end ifclear
15624
15625 @node Examples of gnatfind Usage
15626 @section Examples of @code{gnatfind} Usage
15627
15628 @table @code
15629
15630 @item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb
15631 Find declarations for all entities xyz referenced at least once in
15632 main.adb. The references are search in every library file in the search
15633 path.
15634
15635 The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
15636 switch is set)
15637
15638 The output will look like:
15639 @smallexample
15640 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
15641 ^directory/^[directory]^main.adb:24:10: xyz <= body
15642 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
15643 @end smallexample
15644
15645 @noindent
15646 that is to say, one of the entities xyz found in main.adb is declared at
15647 line 12 of main.ads (and its body is in main.adb), and another one is
15648 declared at line 45 of foo.ads
15649
15650 @item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb
15651 This is the same command as the previous one, instead @code{gnatfind} will
15652 display the content of the Ada source file lines.
15653
15654 The output will look like:
15655
15656 @smallexample
15657 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
15658    procedure xyz;
15659 ^directory/^[directory]^main.adb:24:10: xyz <= body
15660    procedure xyz is
15661 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
15662    xyz : Integer;
15663 @end smallexample
15664
15665 @noindent
15666 This can make it easier to find exactly the location your are looking
15667 for.
15668
15669 @item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb
15670 Find references to all entities containing an x that are
15671 referenced on line 123 of main.ads.
15672 The references will be searched only in main.ads and foo.adb.
15673
15674 @item gnatfind main.ads:123
15675 Find declarations and bodies for all entities that are referenced on
15676 line 123 of main.ads.
15677
15678 This is the same as @code{gnatfind "*":main.adb:123}.
15679
15680 @item gnatfind ^mydir/^[mydir]^main.adb:123:45
15681 Find the declaration for the entity referenced at column 45 in
15682 line 123 of file main.adb in directory mydir. Note that it
15683 is usual to omit the identifier name when the column is given,
15684 since the column position identifies a unique reference.
15685
15686 The column has to be the beginning of the identifier, and should not
15687 point to any character in the middle of the identifier.
15688
15689 @end table
15690
15691 @c *********************************
15692 @node The GNAT Pretty-Printer gnatpp
15693 @chapter The GNAT Pretty-Printer @command{gnatpp}
15694 @findex gnatpp
15695 @cindex Pretty-Printer
15696
15697 @noindent
15698 ^The @command{gnatpp} tool^GNAT PRETTY^ is an ASIS-based utility
15699 for source reformatting / pretty-printing.
15700 It takes an Ada source file as input and generates a reformatted
15701 version as output.
15702 You can specify various style directives via switches; e.g.,
15703 identifier case conventions, rules of indentation, and comment layout.
15704
15705 To produce a reformatted file, @command{gnatpp} generates and uses the ASIS
15706 tree for the input source and thus requires the input to be syntactically and
15707 semantically legal.
15708 If this condition is not met, @command{gnatpp} will terminate with an
15709 error message; no output file will be generated.
15710
15711 If the source files presented to @command{gnatpp} contain
15712 preprocessing directives, then the output file will
15713 correspond to the generated source after all
15714 preprocessing is carried out. There is no way
15715 using @command{gnatpp} to obtain pretty printed files that
15716 include the preprocessing directives.
15717
15718 If the compilation unit
15719 contained in the input source depends semantically upon units located
15720 outside the current directory, you have to provide the source search path
15721 when invoking @command{gnatpp}, if these units are contained in files with
15722 names that do not follow the GNAT file naming rules, you have to provide
15723 the configuration file describing the corresponding naming scheme;
15724 see the description of the @command{gnatpp}
15725 switches below. Another possibility is to use a project file and to
15726 call @command{gnatpp} through the @command{gnat} driver
15727
15728 The @command{gnatpp} command has the form
15729
15730 @smallexample
15731 $ gnatpp @ovar{switches} @var{filename}
15732 @end smallexample
15733
15734 @noindent
15735 where
15736 @itemize @bullet
15737 @item
15738 @var{switches} is an optional sequence of switches defining such properties as
15739 the formatting rules, the source search path, and the destination for the
15740 output source file
15741
15742 @item
15743 @var{filename} is the name (including the extension) of the source file to
15744 reformat; ``wildcards'' or several file names on the same gnatpp command are
15745 allowed.  The file name may contain path information; it does not have to
15746 follow the GNAT file naming rules
15747 @end itemize
15748
15749 @menu
15750 * Switches for gnatpp::
15751 * Formatting Rules::
15752 @end menu
15753
15754 @node Switches for gnatpp
15755 @section Switches for @command{gnatpp}
15756
15757 @noindent
15758 The following subsections describe the various switches accepted by
15759 @command{gnatpp}, organized by category.
15760
15761 @ifclear vms
15762 You specify a switch by supplying a name and generally also a value.
15763 In many cases the values for a switch with a given name are incompatible with
15764 each other
15765 (for example the switch that controls the casing of a reserved word may have
15766 exactly one value: upper case, lower case, or
15767 mixed case) and thus exactly one such switch can be in effect for an
15768 invocation of @command{gnatpp}.
15769 If more than one is supplied, the last one is used.
15770 However, some values for the same switch are mutually compatible.
15771 You may supply several such switches to @command{gnatpp}, but then
15772 each must be specified in full, with both the name and the value.
15773 Abbreviated forms (the name appearing once, followed by each value) are
15774 not permitted.
15775 For example, to set
15776 the alignment of the assignment delimiter both in declarations and in
15777 assignment statements, you must write @option{-A2A3}
15778 (or @option{-A2 -A3}), but not @option{-A23}.
15779 @end ifclear
15780
15781 @ifset vms
15782 In many cases the set of options for a given qualifier are incompatible with
15783 each other (for example the qualifier that controls the casing of a reserved
15784 word may have exactly one option, which specifies either upper case, lower
15785 case, or mixed case), and thus exactly one such option can be in effect for
15786 an invocation of @command{gnatpp}.
15787 If more than one is supplied, the last one is used.
15788 However, some qualifiers have options that are mutually compatible,
15789 and then you may then supply several such options when invoking
15790 @command{gnatpp}.
15791 @end ifset
15792
15793 In most cases, it is obvious whether or not the
15794 ^values for a switch with a given name^options for a given qualifier^
15795 are compatible with each other.
15796 When the semantics might not be evident, the summaries below explicitly
15797 indicate the effect.
15798
15799 @menu
15800 * Alignment Control::
15801 * Casing Control::
15802 * Construct Layout Control::
15803 * General Text Layout Control::
15804 * Other Formatting Options::
15805 * Setting the Source Search Path::
15806 * Output File Control::
15807 * Other gnatpp Switches::
15808 @end menu
15809
15810 @node Alignment Control
15811 @subsection Alignment Control
15812 @cindex Alignment control in @command{gnatpp}
15813
15814 @noindent
15815 Programs can be easier to read if certain constructs are vertically aligned.
15816 By default all alignments are set ON.
15817 Through the @option{^-A0^/ALIGN=OFF^} switch you may reset the default to
15818 OFF, and then use one or more of the other
15819 ^@option{-A@var{n}} switches^@option{/ALIGN} options^
15820 to activate alignment for specific constructs.
15821
15822 @table @option
15823 @cindex @option{^-A@var{n}^/ALIGN^} (@command{gnatpp})
15824
15825 @ifset vms
15826 @item /ALIGN=ON
15827 Set all alignments to ON
15828 @end ifset
15829
15830 @item ^-A0^/ALIGN=OFF^
15831 Set all alignments to OFF
15832
15833 @item ^-A1^/ALIGN=COLONS^
15834 Align @code{:} in declarations
15835
15836 @item ^-A2^/ALIGN=DECLARATIONS^
15837 Align @code{:=} in initializations in declarations
15838
15839 @item ^-A3^/ALIGN=STATEMENTS^
15840 Align @code{:=} in assignment statements
15841
15842 @item ^-A4^/ALIGN=ARROWS^
15843 Align @code{=>} in associations
15844
15845 @item ^-A5^/ALIGN=COMPONENT_CLAUSES^
15846 Align @code{at} keywords in the component clauses in record
15847 representation clauses
15848 @end table
15849
15850 @noindent
15851 The @option{^-A^/ALIGN^} switches are mutually compatible; any combination
15852 is allowed.
15853
15854 @node Casing Control
15855 @subsection Casing Control
15856 @cindex Casing control in @command{gnatpp}
15857
15858 @noindent
15859 @command{gnatpp} allows you to specify the casing for reserved words,
15860 pragma names, attribute designators and identifiers.
15861 For identifiers you may define a
15862 general rule for name casing but also override this rule
15863 via a set of dictionary files.
15864
15865 Three types of casing are supported: lower case, upper case, and mixed case.
15866 Lower and upper case are self-explanatory (but since some letters in
15867 Latin1 and other GNAT-supported character sets
15868 exist only in lower-case form, an upper case conversion will have no
15869 effect on them.)
15870 ``Mixed case'' means that the first letter, and also each letter immediately
15871 following an underscore, are converted to their uppercase forms;
15872 all the other letters are converted to their lowercase forms.
15873
15874 @table @option
15875 @cindex @option{^-a@var{x}^/ATTRIBUTE^} (@command{gnatpp})
15876 @item ^-aL^/ATTRIBUTE_CASING=LOWER_CASE^
15877 Attribute designators are lower case
15878
15879 @item ^-aU^/ATTRIBUTE_CASING=UPPER_CASE^
15880 Attribute designators are upper case
15881
15882 @item ^-aM^/ATTRIBUTE_CASING=MIXED_CASE^
15883 Attribute designators are mixed case (this is the default)
15884
15885 @cindex @option{^-k@var{x}^/KEYWORD_CASING^} (@command{gnatpp})
15886 @item ^-kL^/KEYWORD_CASING=LOWER_CASE^
15887 Keywords (technically, these are known in Ada as @emph{reserved words}) are
15888 lower case (this is the default)
15889
15890 @item ^-kU^/KEYWORD_CASING=UPPER_CASE^
15891 Keywords are upper case
15892
15893 @cindex @option{^-n@var{x}^/NAME_CASING^} (@command{gnatpp})
15894 @item ^-nD^/NAME_CASING=AS_DECLARED^
15895 Name casing for defining occurrences are as they appear in the source file
15896 (this is the default)
15897
15898 @item ^-nU^/NAME_CASING=UPPER_CASE^
15899 Names are in upper case
15900
15901 @item ^-nL^/NAME_CASING=LOWER_CASE^
15902 Names are in lower case
15903
15904 @item ^-nM^/NAME_CASING=MIXED_CASE^
15905 Names are in mixed case
15906
15907 @cindex @option{^-p@var{x}^/PRAGMA_CASING^} (@command{gnatpp})
15908 @item ^-pL^/PRAGMA_CASING=LOWER_CASE^
15909 Pragma names are lower case
15910
15911 @item ^-pU^/PRAGMA_CASING=UPPER_CASE^
15912 Pragma names are upper case
15913
15914 @item ^-pM^/PRAGMA_CASING=MIXED_CASE^
15915 Pragma names are mixed case (this is the default)
15916
15917 @item ^-D@var{file}^/DICTIONARY=@var{file}^
15918 @cindex @option{^-D^/DICTIONARY^} (@command{gnatpp})
15919 Use @var{file} as a @emph{dictionary file} that defines
15920 the casing for a set of specified names,
15921 thereby overriding the effect on these names by
15922 any explicit or implicit
15923 ^-n^/NAME_CASING^ switch.
15924 To supply more than one dictionary file,
15925 use ^several @option{-D} switches^a list of files as options^.
15926
15927 @noindent
15928 @option{gnatpp} implicitly uses a @emph{default dictionary file}
15929 to define the casing for the Ada predefined names and
15930 the names declared in the GNAT libraries.
15931
15932 @item ^-D-^/SPECIFIC_CASING^
15933 @cindex @option{^-D-^/SPECIFIC_CASING^} (@command{gnatpp})
15934 Do not use the default dictionary file;
15935 instead, use the casing
15936 defined by a @option{^-n^/NAME_CASING^} switch and any explicit
15937 dictionary file(s)
15938 @end table
15939
15940 @noindent
15941 The structure of a dictionary file, and details on the conventions
15942 used in the default dictionary file, are defined in @ref{Name Casing}.
15943
15944 The @option{^-D-^/SPECIFIC_CASING^} and
15945 @option{^-D@var{file}^/DICTIONARY=@var{file}^} switches are mutually
15946 compatible.
15947
15948 @node Construct Layout Control
15949 @subsection Construct Layout Control
15950 @cindex Layout control in @command{gnatpp}
15951
15952 @noindent
15953 This group of @command{gnatpp} switches controls the layout of comments and
15954 complex syntactic constructs.  See @ref{Formatting Comments} for details
15955 on their effect.
15956
15957 @table @option
15958 @cindex @option{^-c@var{n}^/COMMENTS_LAYOUT^} (@command{gnatpp})
15959 @item ^-c0^/COMMENTS_LAYOUT=UNTOUCHED^
15960 All the comments remain unchanged
15961
15962 @item ^-c1^/COMMENTS_LAYOUT=DEFAULT^
15963 GNAT-style comment line indentation (this is the default).
15964
15965 @item ^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^
15966 Reference-manual comment line indentation.
15967
15968 @item ^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^
15969 GNAT-style comment beginning
15970
15971 @item ^-c4^/COMMENTS_LAYOUT=REFORMAT^
15972 Reformat comment blocks
15973
15974 @item ^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^
15975 Keep unchanged special form comments
15976
15977 Reformat comment blocks
15978
15979 @cindex @option{^-l@var{n}^/CONSTRUCT_LAYOUT^} (@command{gnatpp})
15980 @item ^-l1^/CONSTRUCT_LAYOUT=GNAT^
15981 GNAT-style layout (this is the default)
15982
15983 @item ^-l2^/CONSTRUCT_LAYOUT=COMPACT^
15984 Compact layout
15985
15986 @item ^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^
15987 Uncompact layout
15988
15989 @cindex @option{^-N^/NOTABS^} (@command{gnatpp})
15990 @item ^-N^/NOTABS^
15991 All the VT characters are removed from the comment text. All the HT characters
15992 are expanded with the sequences of space characters to get to the next tab
15993 stops.
15994
15995 @cindex @option{^--no-separate-is^/NO_SEPARATE_IS^} (@command{gnatpp})
15996 @item ^--no-separate-is^/NO_SEPARATE_IS^
15997 Do not place the keyword @code{is} on a separate line in a subprogram body in
15998 case if the spec occupies more then one line.
15999
16000 @cindex @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} (@command{gnatpp})
16001 @item ^--separate-loop-then^/SEPARATE_LOOP_THEN^
16002 Place the keyword @code{loop} in FOR and WHILE loop statements and the
16003 keyword @code{then} in IF statements on a separate line.
16004
16005 @cindex @option{^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^} (@command{gnatpp})
16006 @item ^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^
16007 Do not place the keyword @code{loop} in FOR and WHILE loop statements and the
16008 keyword @code{then} in IF statements on a separate line. This option is
16009 incompatible with @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} option.
16010
16011 @cindex @option{^--use-on-new-line^/USE_ON_NEW_LINE^} (@command{gnatpp})
16012 @item ^--use-on-new-line^/USE_ON_NEW_LINE^
16013 Start each USE clause in a context clause from a separate line.
16014
16015 @cindex @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^} (@command{gnatpp})
16016 @item ^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^
16017 Use a separate line for a loop or block statement name, but do not use an extra
16018 indentation level for the statement itself.
16019
16020 @end table
16021
16022 @ifclear vms
16023 @noindent
16024 The @option{-c1} and @option{-c2} switches are incompatible.
16025 The @option{-c3} and @option{-c4} switches are compatible with each other and
16026 also with @option{-c1} and @option{-c2}. The @option{-c0} switch disables all
16027 the other comment formatting switches.
16028
16029 The @option{-l1}, @option{-l2}, and @option{-l3} switches are incompatible.
16030 @end ifclear
16031
16032 @ifset vms
16033 @noindent
16034 For the @option{/COMMENTS_LAYOUT} qualifier:
16035 @itemize @bullet
16036 @item
16037 The @option{DEFAULT} and @option{STANDARD_INDENT} options are incompatible.
16038 @item
16039 The @option{GNAT_BEGINNING} and @option{REFORMAT} options are compatible with
16040 each other and also with @option{DEFAULT} and @option{STANDARD_INDENT}.
16041 @end itemize
16042
16043 @noindent
16044 The @option{GNAT}, @option{COMPACT}, and @option{UNCOMPACT} options for the
16045 @option{/CONSTRUCT_LAYOUT} qualifier are incompatible.
16046 @end ifset
16047
16048 @node General Text Layout Control
16049 @subsection General Text Layout Control
16050
16051 @noindent
16052 These switches allow control over line length and indentation.
16053
16054 @table @option
16055 @item ^-M@var{nnn}^/LINE_LENGTH_MAX=@var{nnn}^
16056 @cindex @option{^-M^/LINE_LENGTH^} (@command{gnatpp})
16057 Maximum line length, @var{nnn} from 32@dots{}256, the default value is 79
16058
16059 @item ^-i@var{nnn}^/INDENTATION_LEVEL=@var{nnn}^
16060 @cindex @option{^-i^/INDENTATION_LEVEL^} (@command{gnatpp})
16061 Indentation level, @var{nnn} from 1@dots{}9, the default value is 3
16062
16063 @item ^-cl@var{nnn}^/CONTINUATION_INDENT=@var{nnn}^
16064 @cindex @option{^-cl^/CONTINUATION_INDENT^} (@command{gnatpp})
16065 Indentation level for continuation lines (relative to the line being
16066 continued), @var{nnn} from 1@dots{}9.
16067 The default
16068 value is one less then the (normal) indentation level, unless the
16069 indentation is set to 1 (in which case the default value for continuation
16070 line indentation is also 1)
16071 @end table
16072
16073 @node Other Formatting Options
16074 @subsection Other Formatting Options
16075
16076 @noindent
16077 These switches control the inclusion of missing end/exit labels, and
16078 the indentation level in @b{case} statements.
16079
16080 @table @option
16081 @item ^-e^/NO_MISSED_LABELS^
16082 @cindex @option{^-e^/NO_MISSED_LABELS^} (@command{gnatpp})
16083 Do not insert missing end/exit labels. An end label is the name of
16084 a construct that may optionally be repeated at the end of the
16085 construct's declaration;
16086 e.g., the names of packages, subprograms, and tasks.
16087 An exit label is the name of a loop that may appear as target
16088 of an exit statement within the loop.
16089 By default, @command{gnatpp} inserts these end/exit labels when
16090 they are absent from the original source. This option suppresses such
16091 insertion, so that the formatted source reflects the original.
16092
16093 @item ^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^
16094 @cindex @option{^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^} (@command{gnatpp})
16095 Insert a Form Feed character after a pragma Page.
16096
16097 @item ^-T@var{nnn}^/MAX_INDENT=@var{nnn}^
16098 @cindex @option{^-T^/MAX_INDENT^} (@command{gnatpp})
16099 Do not use an additional indentation level for @b{case} alternatives
16100 and variants if there are @var{nnn} or more (the default
16101 value is 10).
16102 If @var{nnn} is 0, an additional indentation level is
16103 used for @b{case} alternatives and variants regardless of their number.
16104 @end table
16105
16106 @node Setting the Source Search Path
16107 @subsection Setting the Source Search Path
16108
16109 @noindent
16110 To define the search path for the input source file, @command{gnatpp}
16111 uses the same switches as the GNAT compiler, with the same effects.
16112
16113 @table @option
16114 @item ^-I^/SEARCH=^@var{dir}
16115 @cindex @option{^-I^/SEARCH^} (@code{gnatpp})
16116 The same as the corresponding gcc switch
16117
16118 @item ^-I-^/NOCURRENT_DIRECTORY^
16119 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatpp})
16120 The same as the corresponding gcc switch
16121
16122 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE^=@var{path}
16123 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@code{gnatpp})
16124 The same as the corresponding gcc switch
16125
16126 @item ^--RTS^/RUNTIME_SYSTEM^=@var{path}
16127 @cindex @option{^--RTS^/RUNTIME_SYSTEM^} (@code{gnatpp})
16128 The same as the corresponding gcc switch
16129
16130 @end table
16131
16132 @node Output File Control
16133 @subsection Output File Control
16134
16135 @noindent
16136 By default the output is sent to the file whose name is obtained by appending
16137 the ^@file{.pp}^@file{$PP}^ suffix to the name of the input file
16138 (if the file with this name already exists, it is unconditionally overwritten).
16139 Thus if the input file is @file{^my_ada_proc.adb^MY_ADA_PROC.ADB^} then
16140 @command{gnatpp} will produce @file{^my_ada_proc.adb.pp^MY_ADA_PROC.ADB$PP^}
16141 as output file.
16142 The output may be redirected by the following switches:
16143
16144 @table @option
16145 @item ^-pipe^/STANDARD_OUTPUT^
16146 @cindex @option{^-pipe^/STANDARD_OUTPUT^} (@code{gnatpp})
16147 Send the output to @code{Standard_Output}
16148
16149 @item ^-o @var{output_file}^/OUTPUT=@var{output_file}^
16150 @cindex @option{^-o^/OUTPUT^} (@code{gnatpp})
16151 Write the output into @var{output_file}.
16152 If @var{output_file} already exists, @command{gnatpp} terminates without
16153 reading or processing the input file.
16154
16155 @item ^-of ^/FORCED_OUTPUT=^@var{output_file}
16156 @cindex @option{^-of^/FORCED_OUTPUT^} (@code{gnatpp})
16157 Write the output into @var{output_file}, overwriting the existing file
16158 (if one is present).
16159
16160 @item ^-r^/REPLACE^
16161 @cindex @option{^-r^/REPLACE^} (@code{gnatpp})
16162 Replace the input source file with the reformatted output, and copy the
16163 original input source into the file whose name is obtained by appending the
16164 ^@file{.npp}^@file{$NPP}^ suffix to the name of the input file.
16165 If a file with this name already exists, @command{gnatpp} terminates without
16166 reading or processing the input file.
16167
16168 @item ^-rf^/OVERRIDING_REPLACE^
16169 @cindex @option{^-rf^/OVERRIDING_REPLACE^} (@code{gnatpp})
16170 Like @option{^-r^/REPLACE^} except that if the file with the specified name
16171 already exists, it is overwritten.
16172
16173 @item ^-rnb^/REPLACE_NO_BACKUP^
16174 @cindex @option{^-rnb^/REPLACE_NO_BACKUP^} (@code{gnatpp})
16175 Replace the input source file with the reformatted output without
16176 creating any backup copy of the input source.
16177
16178 @item ^--eol=@var{xxx}^/END_OF_LINE=@var{xxx}^
16179 @cindex @option{^--eol^/END_OF_LINE^} (@code{gnatpp})
16180 Specifies the format of the reformatted output file. The @var{xxx}
16181 ^string specified with the switch^option^ may be either
16182 @itemize @bullet
16183 @item ``@option{^dos^DOS^}'' MS DOS style, lines end with CR LF characters
16184 @item ``@option{^crlf^CRLF^}''
16185 the same as @option{^crlf^CRLF^}
16186 @item ``@option{^unix^UNIX^}'' UNIX style, lines end with LF character
16187 @item ``@option{^lf^LF^}''
16188 the same as @option{^unix^UNIX^}
16189 @end itemize
16190
16191 @item ^-W^/RESULT_ENCODING=^@var{e}
16192 @cindex @option{^-W^/RESULT_ENCODING=^} (@command{gnatpp})
16193 Specify the wide character encoding method used to write the code in the
16194 result file
16195 @var{e} is one of the following:
16196
16197 @itemize @bullet
16198
16199 @item ^h^HEX^
16200 Hex encoding
16201
16202 @item ^u^UPPER^
16203 Upper half encoding
16204
16205 @item ^s^SHIFT_JIS^
16206 Shift/JIS encoding
16207
16208 @item ^e^EUC^
16209 EUC encoding
16210
16211 @item ^8^UTF8^
16212 UTF-8 encoding
16213
16214 @item ^b^BRACKETS^
16215 Brackets encoding (default value)
16216 @end itemize
16217
16218 @end table
16219
16220 @noindent
16221 Options @option{^-pipe^/STANDARD_OUTPUT^},
16222 @option{^-o^/OUTPUT^} and
16223 @option{^-of^/FORCED_OUTPUT^} are allowed only if the call to gnatpp
16224 contains only one file to reformat.
16225 Option
16226 @option{^--eol^/END_OF_LINE^}
16227 and
16228 @option{^-W^/RESULT_ENCODING^}
16229 cannot be used together
16230 with @option{^-pipe^/STANDARD_OUTPUT^} option.
16231
16232 @node Other gnatpp Switches
16233 @subsection Other @code{gnatpp} Switches
16234
16235 @noindent
16236 The additional @command{gnatpp} switches are defined in this subsection.
16237
16238 @table @option
16239 @item ^-files @var{filename}^/FILES=@var{output_file}^
16240 @cindex @option{^-files^/FILES^} (@code{gnatpp})
16241 Take the argument source files from the specified file. This file should be an
16242 ordinary textual file containing file names separated by spaces or
16243 line breaks. You can use this switch more then once in the same call to
16244 @command{gnatpp}. You also can combine this switch with explicit list of
16245 files.
16246
16247 @item ^-v^/VERBOSE^
16248 @cindex @option{^-v^/VERBOSE^} (@code{gnatpp})
16249 Verbose mode;
16250 @command{gnatpp} generates version information and then
16251 a trace of the actions it takes to produce or obtain the ASIS tree.
16252
16253 @item ^-w^/WARNINGS^
16254 @cindex @option{^-w^/WARNINGS^} (@code{gnatpp})
16255 Warning mode;
16256 @command{gnatpp} generates a warning whenever it cannot provide
16257 a required layout in the result source.
16258 @end table
16259
16260 @node Formatting Rules
16261 @section Formatting Rules
16262
16263 @noindent
16264 The following subsections show how @command{gnatpp} treats ``white space'',
16265 comments, program layout, and name casing.
16266 They provide the detailed descriptions of the switches shown above.
16267
16268 @menu
16269 * White Space and Empty Lines::
16270 * Formatting Comments::
16271 * Construct Layout::
16272 * Name Casing::
16273 @end menu
16274
16275 @node White Space and Empty Lines
16276 @subsection White Space and Empty Lines
16277
16278 @noindent
16279 @command{gnatpp} does not have an option to control space characters.
16280 It will add or remove spaces according to the style illustrated by the
16281 examples in the @cite{Ada Reference Manual}.
16282
16283 The only format effectors
16284 (see @cite{Ada Reference Manual}, paragraph 2.1(13))
16285 that will appear in the output file are platform-specific line breaks,
16286 and also format effectors within (but not at the end of) comments.
16287 In particular, each horizontal tab character that is not inside
16288 a comment will be treated as a space and thus will appear in the
16289 output file as zero or more spaces depending on
16290 the reformatting of the line in which it appears.
16291 The only exception is a Form Feed character, which is inserted after a
16292 pragma @code{Page} when @option{-ff} is set.
16293
16294 The output file will contain no lines with trailing ``white space'' (spaces,
16295 format effectors).
16296
16297 Empty lines in the original source are preserved
16298 only if they separate declarations or statements.
16299 In such contexts, a
16300 sequence of two or more empty lines is replaced by exactly one empty line.
16301 Note that a blank line will be removed if it separates two ``comment blocks''
16302 (a comment block is a sequence of whole-line comments).
16303 In order to preserve a visual separation between comment blocks, use an
16304 ``empty comment'' (a line comprising only hyphens) rather than an empty line.
16305 Likewise, if for some reason you wish to have a sequence of empty lines,
16306 use a sequence of empty comments instead.
16307
16308 @node Formatting Comments
16309 @subsection Formatting Comments
16310
16311 @noindent
16312 Comments in Ada code are of two kinds:
16313 @itemize @bullet
16314 @item
16315 a @emph{whole-line comment}, which appears by itself (possibly preceded by
16316 ``white space'') on a line
16317
16318 @item
16319 an @emph{end-of-line comment}, which follows some other Ada lexical element
16320 on the same line.
16321 @end itemize
16322
16323 @noindent
16324 The indentation of a whole-line comment is that of either
16325 the preceding or following line in
16326 the formatted source, depending on switch settings as will be described below.
16327
16328 For an end-of-line comment, @command{gnatpp} leaves the same number of spaces
16329 between the end of the preceding Ada lexical element and the beginning
16330 of the comment as appear in the original source,
16331 unless either the comment has to be split to
16332 satisfy the line length limitation, or else the next line contains a
16333 whole line comment that is considered a continuation of this end-of-line
16334 comment (because it starts at the same position).
16335 In the latter two
16336 cases, the start of the end-of-line comment is moved right to the nearest
16337 multiple of the indentation level.
16338 This may result in a ``line overflow'' (the right-shifted comment extending
16339 beyond the maximum line length), in which case the comment is split as
16340 described below.
16341
16342 There is a difference between @option{^-c1^/COMMENTS_LAYOUT=DEFAULT^}
16343 (GNAT-style comment line indentation)
16344 and @option{^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^}
16345 (reference-manual comment line indentation).
16346 With reference-manual style, a whole-line comment is indented as if it
16347 were a declaration or statement at the same place
16348 (i.e., according to the indentation of the preceding line(s)).
16349 With GNAT style, a whole-line comment that is immediately followed by an
16350 @b{if} or @b{case} statement alternative, a record variant, or the reserved
16351 word @b{begin}, is indented based on the construct that follows it.
16352
16353 For example:
16354 @smallexample @c ada
16355 @cartouche
16356 if A then
16357     null;
16358        -- some comment
16359 else
16360    null;
16361 end if;
16362 @end cartouche
16363 @end smallexample
16364
16365 @noindent
16366 Reference-manual indentation produces:
16367
16368 @smallexample @c ada
16369 @cartouche
16370 if A then
16371    null;
16372    --  some comment
16373 else
16374    null;
16375 end if;
16376 @end cartouche
16377 @end smallexample
16378
16379 @noindent
16380 while GNAT-style indentation produces:
16381
16382 @smallexample @c ada
16383 @cartouche
16384 if A then
16385    null;
16386 --  some comment
16387 else
16388    null;
16389 end if;
16390 @end cartouche
16391 @end smallexample
16392
16393 @noindent
16394 The @option{^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^} switch
16395 (GNAT style comment beginning) has the following
16396 effect:
16397
16398 @itemize @bullet
16399 @item
16400 For each whole-line comment that does not end with two hyphens,
16401 @command{gnatpp} inserts spaces if necessary after the starting two hyphens
16402 to ensure that there are at least two spaces between these hyphens and the
16403 first non-blank character of the comment.
16404 @end itemize
16405
16406 @noindent
16407 For an end-of-line comment, if in the original source the next line is a
16408 whole-line comment that starts at the same position
16409 as the end-of-line comment,
16410 then the whole-line comment (and all whole-line comments
16411 that follow it and that start at the same position)
16412 will start at this position in the output file.
16413
16414 @noindent
16415 That is, if in the original source we have:
16416
16417 @smallexample @c ada
16418 @cartouche
16419 begin
16420 A := B + C;            --  B must be in the range Low1..High1
16421                        --  C must be in the range Low2..High2
16422              --B+C will be in the range Low1+Low2..High1+High2
16423 X := X + 1;
16424 @end cartouche
16425 @end smallexample
16426
16427 @noindent
16428 Then in the formatted source we get
16429
16430 @smallexample @c ada
16431 @cartouche
16432 begin
16433    A := B + C;            --  B must be in the range Low1..High1
16434                           --  C must be in the range Low2..High2
16435    --  B+C will be in the range Low1+Low2..High1+High2
16436    X := X + 1;
16437 @end cartouche
16438 @end smallexample
16439
16440 @noindent
16441 A comment that exceeds the line length limit will be split.
16442 Unless switch
16443 @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} (reformat comment blocks) is set and
16444 the line belongs to a reformattable block, splitting the line generates a
16445 @command{gnatpp} warning.
16446 The @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} switch specifies that whole-line
16447 comments may be reformatted in typical
16448 word processor style (that is, moving words between lines and putting as
16449 many words in a line as possible).
16450
16451 @noindent
16452 The @option{^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^} switch specifies, that comments
16453 that has a special format (that is, a character that is neither a letter nor digit
16454 not white space nor line break immediately following the leading @code{--} of
16455 the comment) should be without any change moved from the argument source
16456 into reformatted source. This switch allows to preserve comments that are used
16457 as a special marks in the code (e.g.@: SPARK annotation).
16458
16459 @node Construct Layout
16460 @subsection Construct Layout
16461
16462 @noindent
16463 In several cases the suggested layout in the Ada Reference Manual includes
16464 an extra level of indentation that many programmers prefer to avoid. The
16465 affected cases include:
16466
16467 @itemize @bullet
16468
16469 @item Record type declaration (RM 3.8)
16470
16471 @item Record representation clause (RM 13.5.1)
16472
16473 @item Loop statement in case if a loop has a statement identifier (RM 5.6)
16474
16475 @item Block statement in case if a block has a statement identifier (RM 5.6)
16476 @end itemize
16477
16478 @noindent
16479 In compact mode (when GNAT style layout or compact layout is set),
16480 the pretty printer uses one level of indentation instead
16481 of two. This is achieved in the record definition and record representation
16482 clause cases by putting the @code{record} keyword on the same line as the
16483 start of the declaration or representation clause, and in the block and loop
16484 case by putting the block or loop header on the same line as the statement
16485 identifier.
16486
16487 @noindent
16488 The difference between GNAT style @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^}
16489 and compact @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^}
16490 layout on the one hand, and uncompact layout
16491 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} on the other hand,
16492 can be illustrated by the following examples:
16493
16494 @iftex
16495 @cartouche
16496 @multitable @columnfractions .5 .5
16497 @item @i{GNAT style, compact layout} @tab @i{Uncompact layout}
16498
16499 @item
16500 @smallexample @c ada
16501 type q is record
16502    a : integer;
16503    b : integer;
16504 end record;
16505 @end smallexample
16506 @tab
16507 @smallexample @c ada
16508 type q is
16509    record
16510       a : integer;
16511       b : integer;
16512    end record;
16513 @end smallexample
16514
16515 @item
16516 @smallexample @c ada
16517 for q use record
16518    a at 0 range  0 .. 31;
16519    b at 4 range  0 .. 31;
16520 end record;
16521 @end smallexample
16522 @tab
16523 @smallexample @c ada
16524 for q use
16525    record
16526       a at 0 range  0 .. 31;
16527       b at 4 range  0 .. 31;
16528    end record;
16529 @end smallexample
16530
16531 @item
16532 @smallexample @c ada
16533 Block : declare
16534    A : Integer := 3;
16535 begin
16536    Proc (A, A);
16537 end Block;
16538 @end smallexample
16539 @tab
16540 @smallexample @c ada
16541 Block :
16542    declare
16543       A : Integer := 3;
16544    begin
16545       Proc (A, A);
16546    end Block;
16547 @end smallexample
16548
16549 @item
16550 @smallexample @c ada
16551 Clear : for J in 1 .. 10 loop
16552    A (J) := 0;
16553 end loop Clear;
16554 @end smallexample
16555 @tab
16556 @smallexample @c ada
16557 Clear :
16558    for J in 1 .. 10 loop
16559       A (J) := 0;
16560    end loop Clear;
16561 @end smallexample
16562 @end multitable
16563 @end cartouche
16564 @end iftex
16565
16566 @ifnottex
16567 @smallexample
16568 @cartouche
16569 GNAT style, compact layout              Uncompact layout
16570
16571 type q is record                        type q is
16572    a : integer;                            record
16573    b : integer;                               a : integer;
16574 end record;                                   b : integer;
16575                                            end record;
16576
16577 for q use record                        for q use
16578    a at 0 range  0 .. 31;                  record
16579    b at 4 range  0 .. 31;                     a at 0 range  0 .. 31;
16580 end record;                                   b at 4 range  0 .. 31;
16581                                            end record;
16582
16583 Block : declare                         Block :
16584    A : Integer := 3;                       declare
16585 begin                                         A : Integer := 3;
16586    Proc (A, A);                            begin
16587 end Block;                                    Proc (A, A);
16588                                            end Block;
16589
16590 Clear : for J in 1 .. 10 loop           Clear :
16591    A (J) := 0;                             for J in 1 .. 10 loop
16592 end loop Clear;                               A (J) := 0;
16593                                            end loop Clear;
16594 @end cartouche
16595 @end smallexample
16596 @end ifnottex
16597
16598 @noindent
16599 A further difference between GNAT style layout and compact layout is that
16600 GNAT style layout inserts empty lines as separation for
16601 compound statements, return statements and bodies.
16602
16603 Note that the layout specified by
16604 @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^}
16605 for named block and loop statements overrides the layout defined by these
16606 constructs by @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^},
16607 @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^} or
16608 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} option.
16609
16610 @node Name Casing
16611 @subsection Name Casing
16612
16613 @noindent
16614 @command{gnatpp} always converts the usage occurrence of a (simple) name to
16615 the same casing as the corresponding defining identifier.
16616
16617 You control the casing for defining occurrences via the
16618 @option{^-n^/NAME_CASING^} switch.
16619 @ifclear vms
16620 With @option{-nD} (``as declared'', which is the default),
16621 @end ifclear
16622 @ifset vms
16623 With @option{/NAME_CASING=AS_DECLARED}, which is the default,
16624 @end ifset
16625 defining occurrences appear exactly as in the source file
16626 where they are declared.
16627 The other ^values for this switch^options for this qualifier^ ---
16628 @option{^-nU^UPPER_CASE^},
16629 @option{^-nL^LOWER_CASE^},
16630 @option{^-nM^MIXED_CASE^} ---
16631 result in
16632 ^upper, lower, or mixed case, respectively^the corresponding casing^.
16633 If @command{gnatpp} changes the casing of a defining
16634 occurrence, it analogously changes the casing of all the
16635 usage occurrences of this name.
16636
16637 If the defining occurrence of a name is not in the source compilation unit
16638 currently being processed by @command{gnatpp}, the casing of each reference to
16639 this name is changed according to the value of the @option{^-n^/NAME_CASING^}
16640 switch (subject to the dictionary file mechanism described below).
16641 Thus @command{gnatpp} acts as though the @option{^-n^/NAME_CASING^} switch
16642 had affected the
16643 casing for the defining occurrence of the name.
16644
16645 Some names may need to be spelled with casing conventions that are not
16646 covered by the upper-, lower-, and mixed-case transformations.
16647 You can arrange correct casing by placing such names in a
16648 @emph{dictionary file},
16649 and then supplying a @option{^-D^/DICTIONARY^} switch.
16650 The casing of names from dictionary files overrides
16651 any @option{^-n^/NAME_CASING^} switch.
16652
16653 To handle the casing of Ada predefined names and the names from GNAT libraries,
16654 @command{gnatpp} assumes a default dictionary file.
16655 The name of each predefined entity is spelled with the same casing as is used
16656 for the entity in the @cite{Ada Reference Manual}.
16657 The name of each entity in the GNAT libraries is spelled with the same casing
16658 as is used in the declaration of that entity.
16659
16660 The @w{@option{^-D-^/SPECIFIC_CASING^}} switch suppresses the use of the
16661 default dictionary file.
16662 Instead, the casing for predefined and GNAT-defined names will be established
16663 by the @option{^-n^/NAME_CASING^} switch or explicit dictionary files.
16664 For example, by default the names @code{Ada.Text_IO} and @code{GNAT.OS_Lib}
16665 will appear as just shown,
16666 even in the presence of a @option{^-nU^/NAME_CASING=UPPER_CASE^} switch.
16667 To ensure that even such names are rendered in uppercase,
16668 additionally supply the @w{@option{^-D-^/SPECIFIC_CASING^}} switch
16669 (or else, less conveniently, place these names in upper case in a dictionary
16670 file).
16671
16672 A dictionary file is
16673 a plain text file; each line in this file can be either a blank line
16674 (containing only space characters and ASCII.HT characters), an Ada comment
16675 line, or the specification of exactly one @emph{casing schema}.
16676
16677 A casing schema is a string that has the following syntax:
16678
16679 @smallexample
16680 @cartouche
16681   @var{casing_schema} ::= @var{identifier} | *@var{simple_identifier}*
16682
16683   @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
16684 @end cartouche
16685 @end smallexample
16686
16687 @noindent
16688 (See @cite{Ada Reference Manual}, Section 2.3) for the definition of the
16689 @var{identifier} lexical element and the @var{letter_or_digit} category.)
16690
16691 The casing schema string can be followed by white space and/or an Ada-style
16692 comment; any amount of white space is allowed before the string.
16693
16694 If a dictionary file is passed as
16695 @ifclear vms
16696 the value of a @option{-D@var{file}} switch
16697 @end ifclear
16698 @ifset vms
16699 an option to the @option{/DICTIONARY} qualifier
16700 @end ifset
16701 then for every
16702 simple name and every identifier, @command{gnatpp} checks if the dictionary
16703 defines the casing for the name or for some of its parts (the term ``subword''
16704 is used below to denote the part of a name which is delimited by ``_'' or by
16705 the beginning or end of the word and which does not contain any ``_'' inside):
16706
16707 @itemize @bullet
16708 @item
16709 if the whole name is in the dictionary, @command{gnatpp} uses for this name
16710 the casing defined by the dictionary; no subwords are checked for this word
16711
16712 @item
16713 for every subword @command{gnatpp} checks if the dictionary contains the
16714 corresponding string of the form @code{*@var{simple_identifier}*},
16715 and if it does, the casing of this @var{simple_identifier} is used
16716 for this subword
16717
16718 @item
16719 if the whole name does not contain any ``_'' inside, and if for this name
16720 the dictionary contains two entries - one of the form @var{identifier},
16721 and another - of the form *@var{simple_identifier}*, then the first one
16722 is applied to define the casing of this name
16723
16724 @item
16725 if more than one dictionary file is passed as @command{gnatpp} switches, each
16726 dictionary adds new casing exceptions and overrides all the existing casing
16727 exceptions set by the previous dictionaries
16728
16729 @item
16730 when @command{gnatpp} checks if the word or subword is in the dictionary,
16731 this check is not case sensitive
16732 @end itemize
16733
16734 @noindent
16735 For example, suppose we have the following source to reformat:
16736
16737 @smallexample @c ada
16738 @cartouche
16739 procedure test is
16740    name1 : integer := 1;
16741    name4_name3_name2 : integer := 2;
16742    name2_name3_name4 : Boolean;
16743    name1_var : Float;
16744 begin
16745    name2_name3_name4 := name4_name3_name2 > name1;
16746 end;
16747 @end cartouche
16748 @end smallexample
16749
16750 @noindent
16751 And suppose we have two dictionaries:
16752
16753 @smallexample
16754 @cartouche
16755 @i{dict1:}
16756    NAME1
16757    *NaMe3*
16758    *Name1*
16759 @end cartouche
16760
16761 @cartouche
16762 @i{dict2:}
16763   *NAME3*
16764 @end cartouche
16765 @end smallexample
16766
16767 @noindent
16768 If @command{gnatpp} is called with the following switches:
16769
16770 @smallexample
16771 @ifclear vms
16772 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
16773 @end ifclear
16774 @ifset vms
16775 @command{gnatpp test.adb /NAME_CASING=MIXED_CASE /DICTIONARY=(dict1, dict2)}
16776 @end ifset
16777 @end smallexample
16778
16779 @noindent
16780 then we will get the following name casing in the @command{gnatpp} output:
16781
16782 @smallexample @c ada
16783 @cartouche
16784 procedure Test is
16785    NAME1             : Integer := 1;
16786    Name4_NAME3_Name2 : Integer := 2;
16787    Name2_NAME3_Name4 : Boolean;
16788    Name1_Var         : Float;
16789 begin
16790    Name2_NAME3_Name4 := Name4_NAME3_Name2 > NAME1;
16791 end Test;
16792 @end cartouche
16793 @end smallexample
16794
16795 @c *********************************
16796 @node The GNAT Metric Tool gnatmetric
16797 @chapter The GNAT Metric Tool @command{gnatmetric}
16798 @findex gnatmetric
16799 @cindex Metric tool
16800
16801 @noindent
16802 ^The @command{gnatmetric} tool^@command{GNAT METRIC}^ is an ASIS-based utility
16803 for computing various program metrics.
16804 It takes an Ada source file as input and generates a file containing the
16805 metrics data as output. Various switches control which
16806 metrics are computed and output.
16807
16808 @command{gnatmetric} generates and uses the ASIS
16809 tree for the input source and thus requires the input to be syntactically and
16810 semantically legal.
16811 If this condition is not met, @command{gnatmetric} will generate
16812 an error message; no metric information for this file will be
16813 computed and reported.
16814
16815 If the compilation unit contained in the input source depends semantically
16816 upon units in files located outside the current directory, you have to provide
16817 the source search path when invoking @command{gnatmetric}.
16818 If it depends semantically upon units that are contained
16819 in files with names that do not follow the GNAT file naming rules, you have to
16820 provide the configuration file describing the corresponding naming scheme (see
16821 the description of the @command{gnatmetric} switches below.)
16822 Alternatively, you may use a project file and invoke @command{gnatmetric}
16823 through the @command{gnat} driver.
16824
16825 The @command{gnatmetric} command has the form
16826
16827 @smallexample
16828 $ gnatmetric @ovar{switches} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
16829 @end smallexample
16830
16831 @noindent
16832 where
16833 @itemize @bullet
16834 @item
16835 @var{switches} specify the metrics to compute and define the destination for
16836 the output
16837
16838 @item
16839 Each @var{filename} is the name (including the extension) of a source
16840 file to process. ``Wildcards'' are allowed, and
16841 the file name may contain path information.
16842 If no @var{filename} is supplied, then the @var{switches} list must contain
16843 at least one
16844 @option{-files} switch (@pxref{Other gnatmetric Switches}).
16845 Including both a @option{-files} switch and one or more
16846 @var{filename} arguments is permitted.
16847
16848 @item
16849 @samp{-cargs @var{gcc_switches}} is a list of switches for
16850 @command{gcc}. They will be passed on to all compiler invocations made by
16851 @command{gnatmetric} to generate the ASIS trees. Here you can provide
16852 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
16853 and use the @option{-gnatec} switch to set the configuration file.
16854 @end itemize
16855
16856 @menu
16857 * Switches for gnatmetric::
16858 @end menu
16859
16860 @node Switches for gnatmetric
16861 @section Switches for @command{gnatmetric}
16862
16863 @noindent
16864 The following subsections describe the various switches accepted by
16865 @command{gnatmetric}, organized by category.
16866
16867 @menu
16868 * Output Files Control::
16869 * Disable Metrics For Local Units::
16870 * Specifying a set of metrics to compute::
16871 * Other gnatmetric Switches::
16872 * Generate project-wide metrics::
16873 @end menu
16874
16875 @node Output Files Control
16876 @subsection Output File Control
16877 @cindex Output file control in @command{gnatmetric}
16878
16879 @noindent
16880 @command{gnatmetric} has two output formats. It can generate a
16881 textual (human-readable) form, and also XML. By default only textual
16882 output is generated.
16883
16884 When generating the output in textual form, @command{gnatmetric} creates
16885 for each Ada source file a corresponding text file
16886 containing the computed metrics, except for the case when the set of metrics
16887 specified by gnatmetric parameters consists only of metrics that are computed
16888 for the whole set of analyzed sources, but not for each Ada source.
16889 By default, this file is placed in the same directory as where the source
16890 file is located, and its name is obtained
16891 by appending the ^@file{.metrix}^@file{$METRIX}^ suffix to the name of the
16892 input file.
16893
16894 All the output information generated in XML format is placed in a single
16895 file. By default this file is placed in the current directory and has the
16896 name ^@file{metrix.xml}^@file{METRIX$XML}^.
16897
16898 Some of the computed metrics are summed over the units passed to
16899 @command{gnatmetric}; for example, the total number of lines of code.
16900 By default this information is sent to @file{stdout}, but a file
16901 can be specified with the @option{-og} switch.
16902
16903 The following switches control the @command{gnatmetric} output:
16904
16905 @table @option
16906 @cindex @option{^-x^/XML^} (@command{gnatmetric})
16907 @item ^-x^/XML^
16908 Generate the XML output
16909
16910 @cindex @option{^-nt^/NO_TEXT^} (@command{gnatmetric})
16911 @item ^-nt^/NO_TEXT^
16912 Do not generate the output in text form (implies @option{^-x^/XML^})
16913
16914 @cindex @option{^-d^/DIRECTORY^} (@command{gnatmetric})
16915 @item ^-d @var{output_dir}^/DIRECTORY=@var{output_dir}^
16916 Put textual files with detailed metrics into @var{output_dir}
16917
16918 @cindex @option{^-o^/SUFFIX_DETAILS^} (@command{gnatmetric})
16919 @item ^-o @var{file_suffix}^/SUFFIX_DETAILS=@var{file_suffix}^
16920 Use @var{file_suffix}, instead of ^@file{.metrix}^@file{$METRIX}^
16921 in the name of the output file.
16922
16923 @cindex @option{^-og^/GLOBAL_OUTPUT^} (@command{gnatmetric})
16924 @item ^-og @var{file_name}^/GLOBAL_OUTPUT=@var{file_name}^
16925 Put global metrics into @var{file_name}
16926
16927 @cindex @option{^-ox^/XML_OUTPUT^} (@command{gnatmetric})
16928 @item ^-ox @var{file_name}^/XML_OUTPUT=@var{file_name}^
16929 Put the XML output into @var{file_name} (also implies @option{^-x^/XML^})
16930
16931 @cindex @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} (@command{gnatmetric})
16932 @item ^-sfn^/SHORT_SOURCE_FILE_NAME^
16933 Use ``short'' source file names in the output.  (The @command{gnatmetric}
16934 output includes the name(s) of the Ada source file(s) from which the metrics
16935 are computed.  By default each name includes the absolute path. The
16936 @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} switch causes @command{gnatmetric}
16937 to exclude all directory information from the file names that are output.)
16938
16939 @end table
16940
16941 @node Disable Metrics For Local Units
16942 @subsection Disable Metrics For Local Units
16943 @cindex Disable Metrics For Local Units in @command{gnatmetric}
16944
16945 @noindent
16946 @command{gnatmetric} relies on the GNAT compilation model @minus{}
16947 one compilation
16948 unit per one source file. It computes line metrics for the whole source
16949 file, and it also computes syntax
16950 and complexity metrics for the file's outermost unit.
16951
16952 By default, @command{gnatmetric} will also compute all metrics for certain
16953 kinds of locally declared program units:
16954
16955 @itemize @bullet
16956 @item
16957 subprogram (and generic subprogram) bodies;
16958
16959 @item
16960 package (and generic package) specs and bodies;
16961
16962 @item
16963 task object and type specifications and bodies;
16964
16965 @item
16966 protected object and type specifications and bodies.
16967 @end itemize
16968
16969 @noindent
16970 These kinds of entities will be referred to as
16971 @emph{eligible local program units}, or simply @emph{eligible local units},
16972 @cindex Eligible local unit (for @command{gnatmetric})
16973 in the discussion below.
16974
16975 Note that a subprogram declaration, generic instantiation,
16976 or renaming declaration only receives metrics
16977 computation when it appear as the outermost entity
16978 in a source file.
16979
16980 Suppression of metrics computation for eligible local units can be
16981 obtained via the following switch:
16982
16983 @table @option
16984 @cindex @option{^-n@var{x}^/SUPPRESS^} (@command{gnatmetric})
16985 @item ^-nolocal^/SUPPRESS=LOCAL_DETAILS^
16986 Do not compute detailed metrics for eligible local program units
16987
16988 @end table
16989
16990 @node Specifying a set of metrics to compute
16991 @subsection Specifying a set of metrics to compute
16992
16993 @noindent
16994 By default all the metrics are computed and reported. The switches
16995 described in this subsection allow you to control, on an individual
16996 basis, whether metrics are computed and
16997 reported. If at least one positive metric
16998 switch is specified (that is, a switch that defines that a given
16999 metric or set of metrics is to be computed), then only
17000 explicitly specified metrics are reported.
17001
17002 @menu
17003 * Line Metrics Control::
17004 * Syntax Metrics Control::
17005 * Complexity Metrics Control::
17006 * Object-Oriented Metrics Control::
17007 @end menu
17008
17009 @node Line Metrics Control
17010 @subsubsection Line Metrics Control
17011 @cindex Line metrics control in @command{gnatmetric}
17012
17013 @noindent
17014 For any (legal) source file, and for each of its
17015 eligible local program units, @command{gnatmetric} computes the following
17016 metrics:
17017
17018 @itemize @bullet
17019 @item
17020 the total number of lines;
17021
17022 @item
17023 the total number of code lines (i.e., non-blank lines that are not comments)
17024
17025 @item
17026 the number of comment lines
17027
17028 @item
17029 the number of code lines containing end-of-line comments;
17030
17031 @item
17032 the comment percentage: the ratio between the number of lines that contain
17033 comments and the number of all non-blank lines, expressed as a percentage;
17034
17035 @item
17036 the number of empty lines and lines containing only space characters and/or
17037 format effectors (blank lines)
17038
17039 @item
17040 the average number of code lines in subprogram bodies, task bodies, entry
17041 bodies and statement sequences in package bodies (this metric is only computed
17042 across the whole set of the analyzed units)
17043
17044 @end itemize
17045
17046 @noindent
17047 @command{gnatmetric} sums the values of the line metrics for all the
17048 files being processed and then generates the cumulative results. The tool
17049 also computes for all the files being processed the average number of code
17050 lines in bodies.
17051
17052 You can use the following switches to select the specific line metrics
17053 to be computed and reported.
17054
17055 @table @option
17056 @cindex @option{^--lines@var{x}^/LINE_COUNT_METRICS^} (@command{gnatmetric})
17057
17058 @ifclear vms
17059 @cindex @option{--no-lines@var{x}}
17060 @end ifclear
17061
17062 @item ^--lines-all^/LINE_COUNT_METRICS=ALL_ON^
17063 Report all the line metrics
17064
17065 @item ^--no-lines-all^/LINE_COUNT_METRICS=ALL_OFF^
17066 Do not report any of line metrics
17067
17068 @item ^--lines^/LINE_COUNT_METRICS=ALL_LINES_ON^
17069 Report the number of all lines
17070
17071 @item ^--no-lines^/LINE_COUNT_METRICS=ALL_LINES_OFF^
17072 Do not report the number of all lines
17073
17074 @item ^--lines-code^/LINE_COUNT_METRICS=CODE_LINES_ON^
17075 Report the number of code lines
17076
17077 @item ^--no-lines-code^/LINE_COUNT_METRICS=CODE_LINES_OFF^
17078 Do not report the number of code lines
17079
17080 @item ^--lines-comment^/LINE_COUNT_METRICS=COMMENT_LINES_ON^
17081 Report the number of comment lines
17082
17083 @item ^--no-lines-comment^/LINE_COUNT_METRICS=COMMENT_LINES_OFF^
17084 Do not report the number of comment lines
17085
17086 @item ^--lines-eol-comment^/LINE_COUNT_METRICS=CODE_COMMENT_LINES_ON^
17087 Report the number of code lines containing
17088 end-of-line comments
17089
17090 @item ^--no-lines-eol-comment^/LINE_COUNT_METRICS=CODE_COMMENT_LINES_OFF^
17091 Do not report the number of code lines containing
17092 end-of-line comments
17093
17094 @item ^--lines-ratio^/LINE_COUNT_METRICS=COMMENT_PERCENTAGE_ON^
17095 Report the comment percentage in the program text
17096
17097 @item ^--no-lines-ratio^/LINE_COUNT_METRICS=COMMENT_PERCENTAGE_OFF^
17098 Do not report the comment percentage in the program text
17099
17100 @item ^--lines-blank^/LINE_COUNT_METRICS=BLANK_LINES_ON^
17101 Report the number of blank lines
17102
17103 @item ^--no-lines-blank^/LINE_COUNT_METRICS=BLANK_LINES_OFF^
17104 Do not report the number of blank lines
17105
17106 @item ^--lines-average^/LINE_COUNT_METRICS=AVERAGE_BODY_LINES_ON^
17107 Report the average number of code lines in subprogram bodies, task bodies,
17108 entry bodies and statement sequences in package bodies. The metric is computed
17109 and reported for the whole set of processed Ada sources only.
17110
17111 @item ^--no-lines-average^/LINE_COUNT_METRICS=AVERAGE_BODY_LINES_OFF^
17112 Do not report the average number of code lines in subprogram bodies,
17113 task bodies, entry bodies and statement sequences in package bodies.
17114
17115 @end table
17116
17117 @node Syntax Metrics Control
17118 @subsubsection Syntax Metrics Control
17119 @cindex Syntax metrics control in @command{gnatmetric}
17120
17121 @noindent
17122 @command{gnatmetric} computes various syntactic metrics for the
17123 outermost unit and for each eligible local unit:
17124
17125 @table @emph
17126 @item LSLOC (``Logical Source Lines Of Code'')
17127 The total number of declarations and the total number of statements
17128
17129 @item Maximal static nesting level of inner program units
17130 According to
17131 @cite{Ada Reference Manual}, 10.1(1), ``A program unit is either a
17132 package, a task unit, a protected unit, a
17133 protected entry, a generic unit, or an explicitly declared subprogram other
17134 than an enumeration literal.''
17135
17136 @item Maximal nesting level of composite syntactic constructs
17137 This corresponds to the notion of the
17138 maximum nesting level in the GNAT built-in style checks
17139 (@pxref{Style Checking})
17140 @end table
17141
17142 @noindent
17143 For the outermost unit in the file, @command{gnatmetric} additionally computes
17144 the following metrics:
17145
17146 @table @emph
17147 @item Public subprograms
17148 This metric is computed for package specs. It is the
17149 number of subprograms and generic subprograms declared in the visible
17150 part (including the visible part of nested packages, protected objects, and
17151 protected types).
17152
17153 @item All subprograms
17154 This metric is computed for bodies and subunits. The
17155 metric is equal to a total number of subprogram bodies in the compilation
17156 unit.
17157 Neither generic instantiations nor renamings-as-a-body nor body stubs
17158 are counted. Any subprogram body is counted, independently of its nesting
17159 level and enclosing constructs. Generic bodies and bodies of protected
17160 subprograms are counted in the same way as ``usual'' subprogram bodies.
17161
17162 @item Public types
17163 This metric is computed for package specs and
17164 generic package declarations. It is the total number of types
17165 that can be referenced from outside this compilation unit, plus the
17166 number of types from all the visible parts of all the visible generic
17167 packages. Generic formal types are not counted.  Only types, not subtypes,
17168 are included.
17169
17170 @noindent
17171 Along with the total number of public types, the following
17172 types are counted and reported separately:
17173
17174 @itemize @bullet
17175 @item
17176 Abstract types
17177
17178 @item
17179 Root tagged types (abstract, non-abstract, private, non-private). Type
17180 extensions are @emph{not} counted
17181
17182 @item
17183 Private types (including private extensions)
17184
17185 @item
17186 Task types
17187
17188 @item
17189 Protected types
17190
17191 @end itemize
17192
17193 @item All types
17194 This metric is computed for any compilation unit. It is equal to the total
17195 number of the declarations of different types given in the compilation unit.
17196 The private and the corresponding full type declaration are counted as one
17197 type declaration. Incomplete type declarations and generic formal types
17198 are not counted.
17199 No distinction is made among different kinds of types (abstract,
17200 private etc.); the total number of types is computed and reported.
17201
17202 @end table
17203
17204 @noindent
17205 By default, all the syntax metrics are computed and reported. You can use the
17206 following switches to select specific syntax metrics.
17207
17208 @table @option
17209
17210 @cindex @option{^--syntax@var{x}^/SYNTAX_METRICS^} (@command{gnatmetric})
17211
17212 @ifclear vms
17213 @cindex @option{--no-syntax@var{x}} (@command{gnatmetric})
17214 @end ifclear
17215
17216 @item ^--syntax-all^/SYNTAX_METRICS=ALL_ON^
17217 Report all the syntax metrics
17218
17219 @item ^--no-syntax-all^/ALL_OFF^
17220 Do not report any of syntax metrics
17221
17222 @item ^--declarations^/SYNTAX_METRICS=DECLARATIONS_ON^
17223 Report the total number of declarations
17224
17225 @item ^--no-declarations^/SYNTAX_METRICS=DECLARATIONS_OFF^
17226 Do not report the total number of declarations
17227
17228 @item ^--statements^/SYNTAX_METRICS=STATEMENTS_ON^
17229 Report the total number of statements
17230
17231 @item ^--no-statements^/SYNTAX_METRICS=STATEMENTS_OFF^
17232 Do not report the total number of statements
17233
17234 @item ^--public-subprograms^/SYNTAX_METRICS=PUBLIC_SUBPROGRAMS_ON^
17235 Report the number of public subprograms in a compilation unit
17236
17237 @item ^--no-public-subprograms^/SYNTAX_METRICS=PUBLIC_SUBPROGRAMS_OFF^
17238 Do not report the number of public subprograms in a compilation unit
17239
17240 @item ^--all-subprograms^/SYNTAX_METRICS=ALL_SUBPROGRAMS_ON^
17241 Report the number of all the subprograms in a compilation unit
17242
17243 @item ^--no-all-subprograms^/SYNTAX_METRICS=ALL_SUBPROGRAMS_OFF^
17244 Do not report the number of all the subprograms in a compilation unit
17245
17246 @item ^--public-types^/SYNTAX_METRICS=PUBLIC_TYPES_ON^
17247 Report the number of public types in a compilation unit
17248
17249 @item ^--no-public-types^/SYNTAX_METRICS=PUBLIC_TYPES_OFF^
17250 Do not report the number of public types in a compilation unit
17251
17252 @item ^--all-types^/SYNTAX_METRICS=ALL_TYPES_ON^
17253 Report the number of all the types in a compilation unit
17254
17255 @item ^--no-all-types^/SYNTAX_METRICS=ALL_TYPES_OFF^
17256 Do not report the number of all the types in a compilation unit
17257
17258 @item ^--unit-nesting^/SYNTAX_METRICS=UNIT_NESTING_ON^
17259 Report the maximal program unit nesting level
17260
17261 @item ^--no-unit-nesting^/SYNTAX_METRICS=UNIT_NESTING_OFF^
17262 Do not report the maximal program unit nesting level
17263
17264 @item ^--construct-nesting^/SYNTAX_METRICS=CONSTRUCT_NESTING_ON^
17265 Report the maximal construct nesting level
17266
17267 @item ^--no-construct-nesting^/SYNTAX_METRICS=CONSTRUCT_NESTING_OFF^
17268 Do not report the maximal construct nesting level
17269
17270 @end table
17271
17272 @node Complexity Metrics Control
17273 @subsubsection Complexity Metrics Control
17274 @cindex Complexity metrics control in @command{gnatmetric}
17275
17276 @noindent
17277 For a program unit that is an executable body (a subprogram body (including
17278 generic bodies), task body, entry body or a package body containing
17279 its own statement sequence) @command{gnatmetric} computes the following
17280 complexity metrics:
17281
17282 @itemize @bullet
17283 @item
17284 McCabe cyclomatic complexity;
17285
17286 @item
17287 McCabe essential complexity;
17288
17289 @item
17290 maximal loop nesting level
17291
17292 @end itemize
17293
17294 @noindent
17295 The McCabe complexity metrics are defined
17296 in @url{http://www.mccabe.com/pdf/nist235r.pdf}
17297
17298 According to McCabe, both control statements and short-circuit control forms
17299 should be taken into account when computing cyclomatic complexity. For each
17300 body, we compute three metric values:
17301
17302 @itemize @bullet
17303 @item
17304 the complexity introduced by control
17305 statements only, without taking into account short-circuit forms,
17306
17307 @item
17308 the complexity introduced by short-circuit control forms only, and
17309
17310 @item
17311 the total
17312 cyclomatic complexity, which is the sum of these two values.
17313 @end itemize
17314
17315 @noindent
17316 When computing cyclomatic and essential complexity, @command{gnatmetric} skips
17317 the code in the exception handlers and in all the nested program units.
17318
17319 By default, all the complexity metrics are computed and reported.
17320 For more fine-grained control you can use
17321 the following switches:
17322
17323 @table @option
17324 @cindex @option{^-complexity@var{x}^/COMPLEXITY_METRICS^} (@command{gnatmetric})
17325
17326 @ifclear vms
17327 @cindex @option{--no-complexity@var{x}}
17328 @end ifclear
17329
17330 @item ^--complexity-all^/COMPLEXITY_METRICS=ALL_ON^
17331 Report all the complexity metrics
17332
17333 @item ^--no-complexity-all^/COMPLEXITY_METRICS=ALL_OFF^
17334 Do not report any of complexity metrics
17335
17336 @item ^--complexity-cyclomatic^/COMPLEXITY_METRICS=CYCLOMATIC_ON^
17337 Report the McCabe Cyclomatic Complexity
17338
17339 @item ^--no-complexity-cyclomatic^/COMPLEXITY_METRICS=CYCLOMATIC_OFF^
17340 Do not report the McCabe Cyclomatic Complexity
17341
17342 @item ^--complexity-essential^/COMPLEXITY_METRICS=ESSENTIAL_ON^
17343 Report the Essential Complexity
17344
17345 @item ^--no-complexity-essential^/COMPLEXITY_METRICS=ESSENTIAL_OFF^
17346 Do not report the Essential Complexity
17347
17348 @item ^--loop-nesting^/COMPLEXITY_METRICS=LOOP_NESTING_ON^
17349 Report maximal loop nesting level
17350
17351 @item ^--no-loop-nesting^/COMPLEXITY_METRICS=LOOP_NESTING_OFF^
17352 Do not report maximal loop nesting level
17353
17354 @item ^--complexity-average^/COMPLEXITY_METRICS=AVERAGE_COMPLEXITY_ON^
17355 Report the average McCabe Cyclomatic Complexity for all the subprogram bodies,
17356 task bodies, entry bodies and statement sequences in package bodies.
17357 The metric is computed and reported for whole set of processed Ada sources
17358 only.
17359
17360 @item ^--no-complexity-average^/COMPLEXITY_METRICS=AVERAGE_COMPLEXITY_OFF^
17361 Do not report the average McCabe Cyclomatic Complexity for all the subprogram
17362 bodies, task bodies, entry bodies and statement sequences in package bodies
17363
17364 @cindex @option{^-ne^/NO_EXITS_AS_GOTOS^} (@command{gnatmetric})
17365 @item ^-ne^/NO_EXITS_AS_GOTOS^
17366 Do not consider @code{exit} statements as @code{goto}s when
17367 computing Essential Complexity
17368
17369 @end table
17370
17371
17372 @node Object-Oriented Metrics Control
17373 @subsubsection Object-Oriented Metrics Control
17374 @cindex Object-Oriented metrics control in @command{gnatmetric}
17375
17376 @noindent
17377 @cindex Coupling metrics (in in @command{gnatmetric})
17378 Coupling metrics are object-oriented metrics that measure the
17379 dependencies between a given class (or a group of classes) and the
17380 ``external world'' (that is, the other classes in the program). In this
17381 subsection the term ``class'' is used in its
17382 traditional object-oriented programming sense
17383 (an instantiable module that contains data and/or method members).
17384 A @emph{category} (of classes)
17385 is a group of closely related classes that are reused and/or
17386 modified together.
17387
17388 A class @code{K}'s @emph{efferent coupling} is the number of classes
17389 that @code{K} depends upon.
17390 A category's efferent coupling is the number of classes outside the
17391 category that the classes inside the category depend upon.
17392
17393 A class @code{K}'s @emph{afferent coupling} is the number of classes
17394 that depend upon @code{K}.
17395 A category's afferent coupling is the number of classes outside the
17396 category that depend on classes belonging to the category.
17397
17398 Ada's implementation of the object-oriented paradigm does not use the
17399 traditional class notion, so the definition of the coupling
17400 metrics for Ada maps the class and class category notions
17401 onto Ada constructs.
17402
17403 For the coupling metrics, several kinds of modules -- a library package,
17404 a library generic package, and a library generic package instantiation --
17405 that define a tagged type or an interface type are
17406 considered to be a class. A category consists of a library package (or
17407 a library generic package) that defines a tagged or an interface type,
17408 together with all its descendant (generic) packages that define tagged
17409 or interface types. For any package counted as a class,
17410 its body (if any) is considered
17411 together with its spec when counting the dependencies. For dependencies
17412 between classes, the Ada semantic dependencies are considered.
17413 For coupling metrics, only dependencies on units that are considered as
17414 classes, are considered.
17415
17416 When computing coupling metrics, @command{gnatmetric} counts only
17417 dependencies between units that are arguments of the gnatmetric call.
17418 Coupling metrics are program-wide (or project-wide) metrics, so to
17419 get a valid result, you should call @command{gnatmetric} for
17420 the whole set of sources that make up your program. It can be done
17421 by calling @command{gnatmetric} from the GNAT driver with @option{-U}
17422 option (see See @ref{The GNAT Driver and Project Files} for details.
17423
17424 By default, all the coupling metrics are disabled. You can use the following
17425 switches to specify the coupling metrics to be computed and reported:
17426
17427 @table @option
17428
17429 @ifclear vms
17430 @cindex @option{--package@var{x}} (@command{gnatmetric})
17431 @cindex @option{--no-package@var{x}} (@command{gnatmetric})
17432 @cindex @option{--category@var{x}} (@command{gnatmetric})
17433 @cindex @option{--no-category@var{x}} (@command{gnatmetric})
17434 @end ifclear
17435
17436 @ifset vms
17437 @cindex @option{/COUPLING_METRICS} (@command{gnatmetric})
17438 @end ifset
17439
17440 @item ^--coupling-all^/COUPLING_METRICS=ALL_ON^
17441 Report all the coupling metrics
17442
17443 @item ^--no-coupling-all^/COUPLING_METRICS=ALL_OFF^
17444 Do not report any of  metrics
17445
17446 @item ^--package-efferent-coupling^/COUPLING_METRICS=PACKAGE_EFFERENT_ON^
17447 Report package efferent coupling
17448
17449 @item ^--no-package-efferent-coupling^/COUPLING_METRICS=PACKAGE_EFFERENT_OFF^
17450 Do not report package efferent coupling
17451
17452 @item ^--package-afferent-coupling^/COUPLING_METRICS=PACKAGE_AFFERENT_ON^
17453 Report package afferent coupling
17454
17455 @item ^--no-package-afferent-coupling^/COUPLING_METRICS=PACKAGE_AFFERENT_OFF^
17456 Do not report package afferent coupling
17457
17458 @item ^--category-efferent-coupling^/COUPLING_METRICS=CATEGORY_EFFERENT_ON^
17459 Report category efferent coupling
17460
17461 @item ^--no-category-efferent-coupling^/COUPLING_METRICS=CATEGORY_EFFERENT_OFF^
17462 Do not report category efferent coupling
17463
17464 @item ^--category-afferent-coupling^/COUPLING_METRICS=CATEGORY_AFFERENT_ON^
17465 Report category afferent coupling
17466
17467 @item ^--no-category-afferent-coupling^/COUPLING_METRICS=CATEGORY_AFFERENT_OFF^
17468 Do not report category afferent coupling
17469
17470 @end table
17471
17472 @node Other gnatmetric Switches
17473 @subsection Other @code{gnatmetric} Switches
17474
17475 @noindent
17476 Additional @command{gnatmetric} switches are as follows:
17477
17478 @table @option
17479 @item ^-files @var{filename}^/FILES=@var{filename}^
17480 @cindex @option{^-files^/FILES^} (@code{gnatmetric})
17481 Take the argument source files from the specified file. This file should be an
17482 ordinary text file containing file names separated by spaces or
17483 line breaks. You can use this switch more then once in the same call to
17484 @command{gnatmetric}. You also can combine this switch with
17485 an explicit list of files.
17486
17487 @item ^-v^/VERBOSE^
17488 @cindex @option{^-v^/VERBOSE^} (@code{gnatmetric})
17489 Verbose mode;
17490 @command{gnatmetric} generates version information and then
17491 a trace of sources being processed.
17492
17493 @item ^-dv^/DEBUG_OUTPUT^
17494 @cindex @option{^-dv^/DEBUG_OUTPUT^} (@code{gnatmetric})
17495 Debug mode;
17496 @command{gnatmetric} generates various messages useful to understand what
17497 happens during the metrics computation
17498
17499 @item ^-q^/QUIET^
17500 @cindex @option{^-q^/QUIET^} (@code{gnatmetric})
17501 Quiet mode.
17502 @end table
17503
17504 @node Generate project-wide metrics
17505 @subsection Generate project-wide metrics
17506
17507 In order to compute metrics on all units of a given project, you can use
17508 the @command{gnat} driver along with the @option{-P} option:
17509 @smallexample
17510    gnat metric -Pproj
17511 @end smallexample
17512
17513 @noindent
17514 If the project @code{proj} depends upon other projects, you can compute
17515 the metrics on the project closure using the @option{-U} option:
17516 @smallexample
17517    gnat metric -Pproj -U
17518 @end smallexample
17519
17520 @noindent
17521 Finally, if not all the units are relevant to a particular main
17522 program in the project closure, you can generate metrics for the set
17523 of units needed to create a given main program (unit closure) using
17524 the @option{-U} option followed by the name of the main unit:
17525 @smallexample
17526    gnat metric -Pproj -U main
17527 @end smallexample
17528
17529
17530 @c ***********************************
17531 @node File Name Krunching Using gnatkr
17532 @chapter File Name Krunching Using @code{gnatkr}
17533 @findex gnatkr
17534
17535 @noindent
17536 This chapter discusses the method used by the compiler to shorten
17537 the default file names chosen for Ada units so that they do not
17538 exceed the maximum length permitted. It also describes the
17539 @code{gnatkr} utility that can be used to determine the result of
17540 applying this shortening.
17541 @menu
17542 * About gnatkr::
17543 * Using gnatkr::
17544 * Krunching Method::
17545 * Examples of gnatkr Usage::
17546 @end menu
17547
17548 @node About gnatkr
17549 @section About @code{gnatkr}
17550
17551 @noindent
17552 The default file naming rule in GNAT
17553 is that the file name must be derived from
17554 the unit name. The exact default rule is as follows:
17555 @itemize @bullet
17556 @item
17557 Take the unit name and replace all dots by hyphens.
17558 @item
17559 If such a replacement occurs in the
17560 second character position of a name, and the first character is
17561 ^@samp{a}, @samp{g}, @samp{s}, or @samp{i}, ^@samp{A}, @samp{G}, @samp{S}, or @samp{I},^
17562 then replace the dot by the character
17563 ^@samp{~} (tilde)^@samp{$} (dollar sign)^
17564 instead of a minus.
17565 @end itemize
17566 The reason for this exception is to avoid clashes
17567 with the standard names for children of System, Ada, Interfaces,
17568 and GNAT, which use the prefixes
17569 ^@samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},^@samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},^
17570 respectively.
17571
17572 The @option{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}}
17573 switch of the compiler activates a ``krunching''
17574 circuit that limits file names to nn characters (where nn is a decimal
17575 integer). For example, using OpenVMS,
17576 where the maximum file name length is
17577 39, the value of nn is usually set to 39, but if you want to generate
17578 a set of files that would be usable if ported to a system with some
17579 different maximum file length, then a different value can be specified.
17580 The default value of 39 for OpenVMS need not be specified.
17581
17582 The @code{gnatkr} utility can be used to determine the krunched name for
17583 a given file, when krunched to a specified maximum length.
17584
17585 @node Using gnatkr
17586 @section Using @code{gnatkr}
17587
17588 @noindent
17589 The @code{gnatkr} command has the form
17590
17591 @ifclear vms
17592 @smallexample
17593 $ gnatkr @var{name} @ovar{length}
17594 @end smallexample
17595 @end ifclear
17596
17597 @ifset vms
17598 @smallexample
17599 $ gnatkr @var{name} /COUNT=nn
17600 @end smallexample
17601 @end ifset
17602
17603 @noindent
17604 @var{name} is the uncrunched file name, derived from the name of the unit
17605 in the standard manner described in the previous section (i.e., in particular
17606 all dots are replaced by hyphens). The file name may or may not have an
17607 extension (defined as a suffix of the form period followed by arbitrary
17608 characters other than period). If an extension is present then it will
17609 be preserved in the output. For example, when krunching @file{hellofile.ads}
17610 to eight characters, the result will be hellofil.ads.
17611
17612 Note: for compatibility with previous versions of @code{gnatkr} dots may
17613 appear in the name instead of hyphens, but the last dot will always be
17614 taken as the start of an extension. So if @code{gnatkr} is given an argument
17615 such as @file{Hello.World.adb} it will be treated exactly as if the first
17616 period had been a hyphen, and for example krunching to eight characters
17617 gives the result @file{hellworl.adb}.
17618
17619 Note that the result is always all lower case (except on OpenVMS where it is
17620 all upper case). Characters of the other case are folded as required.
17621
17622 @var{length} represents the length of the krunched name. The default
17623 when no argument is given is ^8^39^ characters. A length of zero stands for
17624 unlimited, in other words do not chop except for system files where the
17625 implied crunching length is always eight characters.
17626
17627 @noindent
17628 The output is the krunched name. The output has an extension only if the
17629 original argument was a file name with an extension.
17630
17631 @node Krunching Method
17632 @section Krunching Method
17633
17634 @noindent
17635 The initial file name is determined by the name of the unit that the file
17636 contains. The name is formed by taking the full expanded name of the
17637 unit and replacing the separating dots with hyphens and
17638 using ^lowercase^uppercase^
17639 for all letters, except that a hyphen in the second character position is
17640 replaced by a ^tilde^dollar sign^ if the first character is
17641 ^@samp{a}, @samp{i}, @samp{g}, or @samp{s}^@samp{A}, @samp{I}, @samp{G}, or @samp{S}^.
17642 The extension is @code{.ads} for a
17643 spec and @code{.adb} for a body.
17644 Krunching does not affect the extension, but the file name is shortened to
17645 the specified length by following these rules:
17646
17647 @itemize @bullet
17648 @item
17649 The name is divided into segments separated by hyphens, tildes or
17650 underscores and all hyphens, tildes, and underscores are
17651 eliminated. If this leaves the name short enough, we are done.
17652
17653 @item
17654 If the name is too long, the longest segment is located (left-most
17655 if there are two of equal length), and shortened by dropping
17656 its last character. This is repeated until the name is short enough.
17657
17658 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
17659 to fit the name into 8 characters as required by some operating systems.
17660
17661 @smallexample
17662 our-strings-wide_fixed 22
17663 our strings wide fixed 19
17664 our string  wide fixed 18
17665 our strin   wide fixed 17
17666 our stri    wide fixed 16
17667 our stri    wide fixe  15
17668 our str     wide fixe  14
17669 our str     wid  fixe  13
17670 our str     wid  fix   12
17671 ou  str     wid  fix   11
17672 ou  st      wid  fix   10
17673 ou  st      wi   fix   9
17674 ou  st      wi   fi    8
17675 Final file name: oustwifi.adb
17676 @end smallexample
17677
17678 @item
17679 The file names for all predefined units are always krunched to eight
17680 characters. The krunching of these predefined units uses the following
17681 special prefix replacements:
17682
17683 @table @file
17684 @item ada-
17685 replaced by @file{^a^A^-}
17686
17687 @item gnat-
17688 replaced by @file{^g^G^-}
17689
17690 @item interfaces-
17691 replaced by @file{^i^I^-}
17692
17693 @item system-
17694 replaced by @file{^s^S^-}
17695 @end table
17696
17697 These system files have a hyphen in the second character position. That
17698 is why normal user files replace such a character with a
17699 ^tilde^dollar sign^, to
17700 avoid confusion with system file names.
17701
17702 As an example of this special rule, consider
17703 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
17704
17705 @smallexample
17706 ada-strings-wide_fixed 22
17707 a-  strings wide fixed 18
17708 a-  string  wide fixed 17
17709 a-  strin   wide fixed 16
17710 a-  stri    wide fixed 15
17711 a-  stri    wide fixe  14
17712 a-  str     wide fixe  13
17713 a-  str     wid  fixe  12
17714 a-  str     wid  fix   11
17715 a-  st      wid  fix   10
17716 a-  st      wi   fix   9
17717 a-  st      wi   fi    8
17718 Final file name: a-stwifi.adb
17719 @end smallexample
17720 @end itemize
17721
17722 Of course no file shortening algorithm can guarantee uniqueness over all
17723 possible unit names, and if file name krunching is used then it is your
17724 responsibility to ensure that no name clashes occur. The utility
17725 program @code{gnatkr} is supplied for conveniently determining the
17726 krunched name of a file.
17727
17728 @node Examples of gnatkr Usage
17729 @section Examples of @code{gnatkr} Usage
17730
17731 @smallexample
17732 @iftex
17733 @leftskip=0cm
17734 @end iftex
17735 @ifclear vms
17736 $ gnatkr very_long_unit_name.ads      --> velounna.ads
17737 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
17738 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
17739 $ gnatkr grandparent-parent-child     --> grparchi
17740 @end ifclear
17741 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
17742 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
17743 @end smallexample
17744
17745 @node Preprocessing Using gnatprep
17746 @chapter Preprocessing Using @code{gnatprep}
17747 @findex gnatprep
17748
17749 @noindent
17750 This chapter discusses how to use GNAT's @code{gnatprep} utility for simple
17751 preprocessing.
17752 Although designed for use with GNAT, @code{gnatprep} does not depend on any
17753 special GNAT features.
17754 For further discussion of conditional compilation in general, see
17755 @ref{Conditional Compilation}.
17756
17757 @menu
17758 * Preprocessing Symbols::
17759 * Using gnatprep::
17760 * Switches for gnatprep::
17761 * Form of Definitions File::
17762 * Form of Input Text for gnatprep::
17763 @end menu
17764
17765 @node Preprocessing Symbols
17766 @section Preprocessing Symbols
17767
17768 @noindent
17769 Preprocessing symbols are defined in definition files and referred to in
17770 sources to be preprocessed. A Preprocessing symbol is an identifier, following
17771 normal Ada (case-insensitive) rules for its syntax, with the restriction that
17772 all characters need to be in the ASCII set (no accented letters).
17773
17774 @node Using gnatprep
17775 @section Using @code{gnatprep}
17776
17777 @noindent
17778 To call @code{gnatprep} use
17779
17780 @smallexample
17781 $ gnatprep @ovar{switches} @var{infile} @var{outfile} @ovar{deffile}
17782 @end smallexample
17783
17784 @noindent
17785 where
17786 @table @var
17787 @item switches
17788 is an optional sequence of switches as described in the next section.
17789
17790 @item infile
17791 is the full name of the input file, which is an Ada source
17792 file containing preprocessor directives.
17793
17794 @item outfile
17795 is the full name of the output file, which is an Ada source
17796 in standard Ada form. When used with GNAT, this file name will
17797 normally have an ads or adb suffix.
17798
17799 @item deffile
17800 is the full name of a text file containing definitions of
17801 preprocessing symbols to be referenced by the preprocessor. This argument is
17802 optional, and can be replaced by the use of the @option{-D} switch.
17803
17804 @end table
17805
17806 @node Switches for gnatprep
17807 @section Switches for @code{gnatprep}
17808
17809 @table @option
17810 @c !sort!
17811
17812 @item ^-b^/BLANK_LINES^
17813 @cindex @option{^-b^/BLANK_LINES^} (@command{gnatprep})
17814 Causes both preprocessor lines and the lines deleted by
17815 preprocessing to be replaced by blank lines in the output source file,
17816 preserving line numbers in the output file.
17817
17818 @item ^-c^/COMMENTS^
17819 @cindex @option{^-c^/COMMENTS^} (@command{gnatprep})
17820 Causes both preprocessor lines and the lines deleted
17821 by preprocessing to be retained in the output source as comments marked
17822 with the special string @code{"--! "}. This option will result in line numbers
17823 being preserved in the output file.
17824
17825 @item ^-C^/REPLACE_IN_COMMENTS^
17826 @cindex @option{^-C^/REPLACE_IN_COMMENTS^} (@command{gnatprep})
17827 Causes comments to be scanned. Normally comments are ignored by gnatprep.
17828 If this option is specified, then comments are scanned and any $symbol
17829 substitutions performed as in program text. This is particularly useful
17830 when structured comments are used (e.g., when writing programs in the
17831 SPARK dialect of Ada). Note that this switch is not available when
17832 doing integrated preprocessing (it would be useless in this context
17833 since comments are ignored by the compiler in any case).
17834
17835 @item ^-Dsymbol=value^/ASSOCIATE="symbol=value"^
17836 @cindex @option{^-D^/ASSOCIATE^} (@command{gnatprep})
17837 Defines a new preprocessing symbol, associated with value. If no value is given
17838 on the command line, then symbol is considered to be @code{True}. This switch
17839 can be used in place of a definition file.
17840
17841 @ifset vms
17842 @item /REMOVE
17843 @cindex @option{/REMOVE} (@command{gnatprep})
17844 This is the default setting which causes lines deleted by preprocessing
17845 to be entirely removed from the output file.
17846 @end ifset
17847
17848 @item ^-r^/REFERENCE^
17849 @cindex @option{^-r^/REFERENCE^} (@command{gnatprep})
17850 Causes a @code{Source_Reference} pragma to be generated that
17851 references the original input file, so that error messages will use
17852 the file name of this original file. The use of this switch implies
17853 that preprocessor lines are not to be removed from the file, so its
17854 use will force @option{^-b^/BLANK_LINES^} mode if
17855 @option{^-c^/COMMENTS^}
17856 has not been specified explicitly.
17857
17858 Note that if the file to be preprocessed contains multiple units, then
17859 it will be necessary to @code{gnatchop} the output file from
17860 @code{gnatprep}. If a @code{Source_Reference} pragma is present
17861 in the preprocessed file, it will be respected by
17862 @code{gnatchop ^-r^/REFERENCE^}
17863 so that the final chopped files will correctly refer to the original
17864 input source file for @code{gnatprep}.
17865
17866 @item ^-s^/SYMBOLS^
17867 @cindex @option{^-s^/SYMBOLS^} (@command{gnatprep})
17868 Causes a sorted list of symbol names and values to be
17869 listed on the standard output file.
17870
17871 @item ^-u^/UNDEFINED^
17872 @cindex @option{^-u^/UNDEFINED^} (@command{gnatprep})
17873 Causes undefined symbols to be treated as having the value FALSE in the context
17874 of a preprocessor test. In the absence of this option, an undefined symbol in
17875 a @code{#if} or @code{#elsif} test will be treated as an error.
17876
17877 @end table
17878
17879 @ifclear vms
17880 @noindent
17881 Note: if neither @option{-b} nor @option{-c} is present,
17882 then preprocessor lines and
17883 deleted lines are completely removed from the output, unless -r is
17884 specified, in which case -b is assumed.
17885 @end ifclear
17886
17887 @node Form of Definitions File
17888 @section Form of Definitions File
17889
17890 @noindent
17891 The definitions file contains lines of the form
17892
17893 @smallexample
17894 symbol := value
17895 @end smallexample
17896
17897 @noindent
17898 where symbol is a preprocessing symbol, and value is one of the following:
17899
17900 @itemize @bullet
17901 @item
17902 Empty, corresponding to a null substitution
17903 @item
17904 A string literal using normal Ada syntax
17905 @item
17906 Any sequence of characters from the set
17907 (letters, digits, period, underline).
17908 @end itemize
17909
17910 @noindent
17911 Comment lines may also appear in the definitions file, starting with
17912 the usual @code{--},
17913 and comments may be added to the definitions lines.
17914
17915 @node Form of Input Text for gnatprep
17916 @section Form of Input Text for @code{gnatprep}
17917
17918 @noindent
17919 The input text may contain preprocessor conditional inclusion lines,
17920 as well as general symbol substitution sequences.
17921
17922 The preprocessor conditional inclusion commands have the form
17923
17924 @smallexample
17925 @group
17926 @cartouche
17927 #if @i{expression} @r{[}then@r{]}
17928    lines
17929 #elsif @i{expression} @r{[}then@r{]}
17930    lines
17931 #elsif @i{expression} @r{[}then@r{]}
17932    lines
17933 @dots{}
17934 #else
17935    lines
17936 #end if;
17937 @end cartouche
17938 @end group
17939 @end smallexample
17940
17941 @noindent
17942 In this example, @i{expression} is defined by the following grammar:
17943 @smallexample
17944 @i{expression} ::=  <symbol>
17945 @i{expression} ::=  <symbol> = "<value>"
17946 @i{expression} ::=  <symbol> = <symbol>
17947 @i{expression} ::=  <symbol> 'Defined
17948 @i{expression} ::=  not @i{expression}
17949 @i{expression} ::=  @i{expression} and @i{expression}
17950 @i{expression} ::=  @i{expression} or @i{expression}
17951 @i{expression} ::=  @i{expression} and then @i{expression}
17952 @i{expression} ::=  @i{expression} or else @i{expression}
17953 @i{expression} ::=  ( @i{expression} )
17954 @end smallexample
17955
17956 The following restriction exists: it is not allowed to have "and" or "or"
17957 following "not" in the same expression without parentheses. For example, this
17958 is not allowed:
17959
17960 @smallexample
17961    not X or Y
17962 @end smallexample
17963
17964 This should be one of the following:
17965
17966 @smallexample
17967    (not X) or Y
17968    not (X or Y)
17969 @end smallexample
17970
17971 @noindent
17972 For the first test (@i{expression} ::= <symbol>) the symbol must have
17973 either the value true or false, that is to say the right-hand of the
17974 symbol definition must be one of the (case-insensitive) literals
17975 @code{True} or @code{False}. If the value is true, then the
17976 corresponding lines are included, and if the value is false, they are
17977 excluded.
17978
17979 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
17980 the symbol has been defined in the definition file or by a @option{-D}
17981 switch on the command line. Otherwise, the test is false.
17982
17983 The equality tests are case insensitive, as are all the preprocessor lines.
17984
17985 If the symbol referenced is not defined in the symbol definitions file,
17986 then the effect depends on whether or not switch @option{-u}
17987 is specified. If so, then the symbol is treated as if it had the value
17988 false and the test fails. If this switch is not specified, then
17989 it is an error to reference an undefined symbol. It is also an error to
17990 reference a symbol that is defined with a value other than @code{True}
17991 or @code{False}.
17992
17993 The use of the @code{not} operator inverts the sense of this logical test.
17994 The @code{not} operator cannot be combined with the @code{or} or @code{and}
17995 operators, without parentheses. For example, "if not X or Y then" is not
17996 allowed, but "if (not X) or Y then" and "if not (X or Y) then" are.
17997
17998 The @code{then} keyword is optional as shown
17999
18000 The @code{#} must be the first non-blank character on a line, but
18001 otherwise the format is free form. Spaces or tabs may appear between
18002 the @code{#} and the keyword. The keywords and the symbols are case
18003 insensitive as in normal Ada code. Comments may be used on a
18004 preprocessor line, but other than that, no other tokens may appear on a
18005 preprocessor line. Any number of @code{elsif} clauses can be present,
18006 including none at all. The @code{else} is optional, as in Ada.
18007
18008 The @code{#} marking the start of a preprocessor line must be the first
18009 non-blank character on the line, i.e., it must be preceded only by
18010 spaces or horizontal tabs.
18011
18012 Symbol substitution outside of preprocessor lines is obtained by using
18013 the sequence
18014
18015 @smallexample
18016 $symbol
18017 @end smallexample
18018
18019 @noindent
18020 anywhere within a source line, except in a comment or within a
18021 string literal. The identifier
18022 following the @code{$} must match one of the symbols defined in the symbol
18023 definition file, and the result is to substitute the value of the
18024 symbol in place of @code{$symbol} in the output file.
18025
18026 Note that although the substitution of strings within a string literal
18027 is not possible, it is possible to have a symbol whose defined value is
18028 a string literal. So instead of setting XYZ to @code{hello} and writing:
18029
18030 @smallexample
18031 Header : String := "$XYZ";
18032 @end smallexample
18033
18034 @noindent
18035 you should set XYZ to @code{"hello"} and write:
18036
18037 @smallexample
18038 Header : String := $XYZ;
18039 @end smallexample
18040
18041 @noindent
18042 and then the substitution will occur as desired.
18043
18044 @ifset vms
18045 @node The GNAT Run-Time Library Builder gnatlbr
18046 @chapter The GNAT Run-Time Library Builder @code{gnatlbr}
18047 @findex gnatlbr
18048 @cindex Library builder
18049
18050 @noindent
18051 @code{gnatlbr} is a tool for rebuilding the GNAT run time with user
18052 supplied configuration pragmas.
18053
18054 @menu
18055 * Running gnatlbr::
18056 * Switches for gnatlbr::
18057 * Examples of gnatlbr Usage::
18058 @end menu
18059
18060 @node Running gnatlbr
18061 @section Running @code{gnatlbr}
18062
18063 @noindent
18064 The @code{gnatlbr} command has the form
18065
18066 @smallexample
18067 $ GNAT LIBRARY /@r{[}CREATE@r{|}SET@r{|}DELETE@r{]}=directory @r{[}/CONFIG=file@r{]}
18068 @end smallexample
18069
18070 @node Switches for gnatlbr
18071 @section Switches for @code{gnatlbr}
18072
18073 @noindent
18074 @code{gnatlbr} recognizes the following switches:
18075
18076 @table @option
18077 @c !sort!
18078 @item /CREATE=directory
18079 @cindex @code{/CREATE} (@code{gnatlbr})
18080 Create the new run-time library in the specified directory.
18081
18082 @item /SET=directory
18083 @cindex @code{/SET} (@code{gnatlbr})
18084 Make the library in the specified directory the current run-time library.
18085
18086 @item /DELETE=directory
18087 @cindex @code{/DELETE} (@code{gnatlbr})
18088 Delete the run-time library in the specified directory.
18089
18090 @item /CONFIG=file
18091 @cindex @code{/CONFIG} (@code{gnatlbr})
18092 With /CREATE: Use the configuration pragmas in the specified file when
18093 building the library.
18094
18095 With /SET: Use the configuration pragmas in the specified file when
18096 compiling.
18097
18098 @end table
18099
18100 @node Examples of gnatlbr Usage
18101 @section Example of @code{gnatlbr} Usage
18102
18103 @smallexample
18104 Contents of VAXFLOAT.ADC:
18105 pragma Float_Representation (VAX_Float);
18106
18107 $ GNAT LIBRARY /CREATE=[.VAXFLOAT] /CONFIG=VAXFLOAT.ADC
18108
18109 GNAT LIBRARY rebuilds the run-time library in directory [.VAXFLOAT]
18110
18111 @end smallexample
18112 @end ifset
18113
18114 @node The GNAT Library Browser gnatls
18115 @chapter The GNAT Library Browser @code{gnatls}
18116 @findex gnatls
18117 @cindex Library browser
18118
18119 @noindent
18120 @code{gnatls} is a tool that outputs information about compiled
18121 units. It gives the relationship between objects, unit names and source
18122 files. It can also be used to check the source dependencies of a unit
18123 as well as various characteristics.
18124
18125 Note: to invoke @code{gnatls} with a project file, use the @code{gnat}
18126 driver (see @ref{The GNAT Driver and Project Files}).
18127
18128 @menu
18129 * Running gnatls::
18130 * Switches for gnatls::
18131 * Examples of gnatls Usage::
18132 @end menu
18133
18134 @node Running gnatls
18135 @section Running @code{gnatls}
18136
18137 @noindent
18138 The @code{gnatls} command has the form
18139
18140 @smallexample
18141 $ gnatls switches @var{object_or_ali_file}
18142 @end smallexample
18143
18144 @noindent
18145 The main argument is the list of object or @file{ali} files
18146 (@pxref{The Ada Library Information Files})
18147 for which information is requested.
18148
18149 In normal mode, without additional option, @code{gnatls} produces a
18150 four-column listing. Each line represents information for a specific
18151 object. The first column gives the full path of the object, the second
18152 column gives the name of the principal unit in this object, the third
18153 column gives the status of the source and the fourth column gives the
18154 full path of the source representing this unit.
18155 Here is a simple example of use:
18156
18157 @smallexample
18158 $ gnatls *.o
18159 ^./^[]^demo1.o            demo1            DIF demo1.adb
18160 ^./^[]^demo2.o            demo2             OK demo2.adb
18161 ^./^[]^hello.o            h1                OK hello.adb
18162 ^./^[]^instr-child.o      instr.child      MOK instr-child.adb
18163 ^./^[]^instr.o            instr             OK instr.adb
18164 ^./^[]^tef.o              tef              DIF tef.adb
18165 ^./^[]^text_io_example.o  text_io_example   OK text_io_example.adb
18166 ^./^[]^tgef.o             tgef             DIF tgef.adb
18167 @end smallexample
18168
18169 @noindent
18170 The first line can be interpreted as follows: the main unit which is
18171 contained in
18172 object file @file{demo1.o} is demo1, whose main source is in
18173 @file{demo1.adb}. Furthermore, the version of the source used for the
18174 compilation of demo1 has been modified (DIF). Each source file has a status
18175 qualifier which can be:
18176
18177 @table @code
18178 @item OK (unchanged)
18179 The version of the source file used for the compilation of the
18180 specified unit corresponds exactly to the actual source file.
18181
18182 @item MOK (slightly modified)
18183 The version of the source file used for the compilation of the
18184 specified unit differs from the actual source file but not enough to
18185 require recompilation. If you use gnatmake with the qualifier
18186 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
18187 MOK will not be recompiled.
18188
18189 @item DIF (modified)
18190 No version of the source found on the path corresponds to the source
18191 used to build this object.
18192
18193 @item ??? (file not found)
18194 No source file was found for this unit.
18195
18196 @item HID (hidden,  unchanged version not first on PATH)
18197 The version of the source that corresponds exactly to the source used
18198 for compilation has been found on the path but it is hidden by another
18199 version of the same source that has been modified.
18200
18201 @end table
18202
18203 @node Switches for gnatls
18204 @section Switches for @code{gnatls}
18205
18206 @noindent
18207 @code{gnatls} recognizes the following switches:
18208
18209 @table @option
18210 @c !sort!
18211 @cindex @option{--version} @command{gnatls}
18212 Display Copyright and version, then exit disregarding all other options.
18213
18214 @item --help
18215 @cindex @option{--help} @command{gnatls}
18216 If @option{--version} was not used, display usage, then exit disregarding
18217 all other options.
18218
18219 @item ^-a^/ALL_UNITS^
18220 @cindex @option{^-a^/ALL_UNITS^} (@code{gnatls})
18221 Consider all units, including those of the predefined Ada library.
18222 Especially useful with @option{^-d^/DEPENDENCIES^}.
18223
18224 @item ^-d^/DEPENDENCIES^
18225 @cindex @option{^-d^/DEPENDENCIES^} (@code{gnatls})
18226 List sources from which specified units depend on.
18227
18228 @item ^-h^/OUTPUT=OPTIONS^
18229 @cindex @option{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
18230 Output the list of options.
18231
18232 @item ^-o^/OUTPUT=OBJECTS^
18233 @cindex @option{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
18234 Only output information about object files.
18235
18236 @item ^-s^/OUTPUT=SOURCES^
18237 @cindex @option{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
18238 Only output information about source files.
18239
18240 @item ^-u^/OUTPUT=UNITS^
18241 @cindex @option{^-u^/OUTPUT=UNITS^} (@code{gnatls})
18242 Only output information about compilation units.
18243
18244 @item ^-files^/FILES^=@var{file}
18245 @cindex @option{^-files^/FILES^} (@code{gnatls})
18246 Take as arguments the files listed in text file @var{file}.
18247 Text file @var{file} may contain empty lines that are ignored.
18248 Each nonempty line should contain the name of an existing file.
18249 Several such switches may be specified simultaneously.
18250
18251 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
18252 @itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
18253 @itemx ^-I^/SEARCH=^@var{dir}
18254 @itemx  ^-I-^/NOCURRENT_DIRECTORY^
18255 @itemx -nostdinc
18256 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatls})
18257 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatls})
18258 @cindex @option{^-I^/SEARCH^} (@code{gnatls})
18259 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatls})
18260 Source path manipulation. Same meaning as the equivalent @command{gnatmake}
18261 flags (@pxref{Switches for gnatmake}).
18262
18263 @item --RTS=@var{rts-path}
18264 @cindex @option{--RTS} (@code{gnatls})
18265 Specifies the default location of the runtime library. Same meaning as the
18266 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
18267
18268 @item ^-v^/OUTPUT=VERBOSE^
18269 @cindex @option{^-v^/OUTPUT=VERBOSE^} (@code{gnatls})
18270 Verbose mode. Output the complete source, object and project paths. Do not use
18271 the default column layout but instead use long format giving as much as
18272 information possible on each requested units, including special
18273 characteristics such as:
18274
18275 @table @code
18276 @item  Preelaborable
18277 The unit is preelaborable in the Ada sense.
18278
18279 @item No_Elab_Code
18280 No elaboration code has been produced by the compiler for this unit.
18281
18282 @item Pure
18283 The unit is pure in the Ada sense.
18284
18285 @item Elaborate_Body
18286 The unit contains a pragma Elaborate_Body.
18287
18288 @item Remote_Types
18289 The unit contains a pragma Remote_Types.
18290
18291 @item Shared_Passive
18292 The unit contains a pragma Shared_Passive.
18293
18294 @item Predefined
18295 This unit is part of the predefined environment and cannot be modified
18296 by the user.
18297
18298 @item Remote_Call_Interface
18299 The unit contains a pragma Remote_Call_Interface.
18300
18301 @end table
18302
18303 @end table
18304
18305 @node Examples of gnatls Usage
18306 @section Example of @code{gnatls} Usage
18307 @ifclear vms
18308
18309 @noindent
18310 Example of using the verbose switch. Note how the source and
18311 object paths are affected by the -I switch.
18312
18313 @smallexample
18314 $ gnatls -v -I.. demo1.o
18315
18316 GNATLS 5.03w (20041123-34)
18317 Copyright 1997-2004 Free Software Foundation, Inc.
18318
18319 Source Search Path:
18320    <Current_Directory>
18321    ../
18322    /home/comar/local/adainclude/
18323
18324 Object Search Path:
18325    <Current_Directory>
18326    ../
18327    /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
18328
18329 Project Search Path:
18330    <Current_Directory>
18331    /home/comar/local/lib/gnat/
18332
18333 ./demo1.o
18334    Unit =>
18335      Name   => demo1
18336      Kind   => subprogram body
18337      Flags  => No_Elab_Code
18338      Source => demo1.adb    modified
18339 @end smallexample
18340
18341 @noindent
18342 The following is an example of use of the dependency list.
18343 Note the use of the -s switch
18344 which gives a straight list of source files. This can be useful for
18345 building specialized scripts.
18346
18347 @smallexample
18348 $ gnatls -d demo2.o
18349 ./demo2.o   demo2        OK demo2.adb
18350                          OK gen_list.ads
18351                          OK gen_list.adb
18352                          OK instr.ads
18353                          OK instr-child.ads
18354
18355 $ gnatls -d -s -a demo1.o
18356 demo1.adb
18357 /home/comar/local/adainclude/ada.ads
18358 /home/comar/local/adainclude/a-finali.ads
18359 /home/comar/local/adainclude/a-filico.ads
18360 /home/comar/local/adainclude/a-stream.ads
18361 /home/comar/local/adainclude/a-tags.ads
18362 gen_list.ads
18363 gen_list.adb
18364 /home/comar/local/adainclude/gnat.ads
18365 /home/comar/local/adainclude/g-io.ads
18366 instr.ads
18367 /home/comar/local/adainclude/system.ads
18368 /home/comar/local/adainclude/s-exctab.ads
18369 /home/comar/local/adainclude/s-finimp.ads
18370 /home/comar/local/adainclude/s-finroo.ads
18371 /home/comar/local/adainclude/s-secsta.ads
18372 /home/comar/local/adainclude/s-stalib.ads
18373 /home/comar/local/adainclude/s-stoele.ads
18374 /home/comar/local/adainclude/s-stratt.ads
18375 /home/comar/local/adainclude/s-tasoli.ads
18376 /home/comar/local/adainclude/s-unstyp.ads
18377 /home/comar/local/adainclude/unchconv.ads
18378 @end smallexample
18379 @end ifclear
18380
18381 @ifset vms
18382 @smallexample
18383 GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
18384
18385 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
18386 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
18387 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
18388 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
18389 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
18390 demo1.adb
18391 gen_list.ads
18392 gen_list.adb
18393 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
18394 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
18395 instr.ads
18396 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
18397 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
18398 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
18399 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
18400 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
18401 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
18402 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
18403 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
18404 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
18405 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
18406 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
18407 @end smallexample
18408 @end ifset
18409
18410 @node Cleaning Up Using gnatclean
18411 @chapter Cleaning Up Using @code{gnatclean}
18412 @findex gnatclean
18413 @cindex Cleaning tool
18414
18415 @noindent
18416 @code{gnatclean} is a tool that allows the deletion of files produced by the
18417 compiler, binder and linker, including ALI files, object files, tree files,
18418 expanded source files, library files, interface copy source files, binder
18419 generated files and executable files.
18420
18421 @menu
18422 * Running gnatclean::
18423 * Switches for gnatclean::
18424 @c * Examples of gnatclean Usage::
18425 @end menu
18426
18427 @node Running gnatclean
18428 @section Running @code{gnatclean}
18429
18430 @noindent
18431 The @code{gnatclean} command has the form:
18432
18433 @smallexample
18434 $ gnatclean switches @var{names}
18435 @end smallexample
18436
18437 @noindent
18438 @var{names} is a list of source file names. Suffixes @code{.^ads^ADS^} and
18439 @code{^adb^ADB^} may be omitted. If a project file is specified using switch
18440 @code{^-P^/PROJECT_FILE=^}, then @var{names} may be completely omitted.
18441
18442 @noindent
18443 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
18444 if switch @code{^-c^/COMPILER_FILES_ONLY^} is not specified, by the binder and
18445 the linker. In informative-only mode, specified by switch
18446 @code{^-n^/NODELETE^}, the list of files that would have been deleted in
18447 normal mode is listed, but no file is actually deleted.
18448
18449 @node Switches for gnatclean
18450 @section Switches for @code{gnatclean}
18451
18452 @noindent
18453 @code{gnatclean} recognizes the following switches:
18454
18455 @table @option
18456 @c !sort!
18457 @cindex @option{--version} @command{gnatclean}
18458 Display Copyright and version, then exit disregarding all other options.
18459
18460 @item --help
18461 @cindex @option{--help} @command{gnatclean}
18462 If @option{--version} was not used, display usage, then exit disregarding
18463 all other options.
18464
18465 @item ^-c^/COMPILER_FILES_ONLY^
18466 @cindex @option{^-c^/COMPILER_FILES_ONLY^} (@code{gnatclean})
18467 Only attempt to delete the files produced by the compiler, not those produced
18468 by the binder or the linker. The files that are not to be deleted are library
18469 files, interface copy files, binder generated files and executable files.
18470
18471 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
18472 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatclean})
18473 Indicate that ALI and object files should normally be found in directory
18474 @var{dir}.
18475
18476 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
18477 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatclean})
18478 When using project files, if some errors or warnings are detected during
18479 parsing and verbose mode is not in effect (no use of switch
18480 ^-v^/VERBOSE^), then error lines start with the full path name of the project
18481 file, rather than its simple file name.
18482
18483 @item ^-h^/HELP^
18484 @cindex @option{^-h^/HELP^} (@code{gnatclean})
18485 Output a message explaining the usage of @code{^gnatclean^gnatclean^}.
18486
18487 @item ^-n^/NODELETE^
18488 @cindex @option{^-n^/NODELETE^} (@code{gnatclean})
18489 Informative-only mode. Do not delete any files. Output the list of the files
18490 that would have been deleted if this switch was not specified.
18491
18492 @item ^-P^/PROJECT_FILE=^@var{project}
18493 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatclean})
18494 Use project file @var{project}. Only one such switch can be used.
18495 When cleaning a project file, the files produced by the compilation of the
18496 immediate sources or inherited sources of the project files are to be
18497 deleted. This is not depending on the presence or not of executable names
18498 on the command line.
18499
18500 @item ^-q^/QUIET^
18501 @cindex @option{^-q^/QUIET^} (@code{gnatclean})
18502 Quiet output. If there are no errors, do not output anything, except in
18503 verbose mode (switch ^-v^/VERBOSE^) or in informative-only mode
18504 (switch ^-n^/NODELETE^).
18505
18506 @item ^-r^/RECURSIVE^
18507 @cindex @option{^-r^/RECURSIVE^} (@code{gnatclean})
18508 When a project file is specified (using switch ^-P^/PROJECT_FILE=^),
18509 clean all imported and extended project files, recursively. If this switch
18510 is not specified, only the files related to the main project file are to be
18511 deleted. This switch has no effect if no project file is specified.
18512
18513 @item ^-v^/VERBOSE^
18514 @cindex @option{^-v^/VERBOSE^} (@code{gnatclean})
18515 Verbose mode.
18516
18517 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
18518 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (@code{gnatclean})
18519 Indicates the verbosity of the parsing of GNAT project files.
18520 @xref{Switches Related to Project Files}.
18521
18522 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
18523 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (@code{gnatclean})
18524 Indicates that external variable @var{name} has the value @var{value}.
18525 The Project Manager will use this value for occurrences of
18526 @code{external(name)} when parsing the project file.
18527 @xref{Switches Related to Project Files}.
18528
18529 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
18530 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatclean})
18531 When searching for ALI and object files, look in directory
18532 @var{dir}.
18533
18534 @item ^-I^/SEARCH=^@var{dir}
18535 @cindex @option{^-I^/SEARCH^} (@code{gnatclean})
18536 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}}.
18537
18538 @item ^-I-^/NOCURRENT_DIRECTORY^
18539 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatclean})
18540 @cindex Source files, suppressing search
18541 Do not look for ALI or object files in the directory
18542 where @code{gnatclean} was invoked.
18543
18544 @end table
18545
18546 @c @node Examples of gnatclean Usage
18547 @c @section Examples of @code{gnatclean} Usage
18548
18549 @ifclear vms
18550 @node GNAT and Libraries
18551 @chapter GNAT and Libraries
18552 @cindex Library, building, installing, using
18553
18554 @noindent
18555 This chapter describes how to build and use libraries with GNAT, and also shows
18556 how to recompile the GNAT run-time library. You should be familiar with the
18557 Project Manager facility (@pxref{GNAT Project Manager}) before reading this
18558 chapter.
18559
18560 @menu
18561 * Introduction to Libraries in GNAT::
18562 * General Ada Libraries::
18563 * Stand-alone Ada Libraries::
18564 * Rebuilding the GNAT Run-Time Library::
18565 @end menu
18566
18567 @node Introduction to Libraries in GNAT
18568 @section Introduction to Libraries in GNAT
18569
18570 @noindent
18571 A library is, conceptually, a collection of objects which does not have its
18572 own main thread of execution, but rather provides certain services to the
18573 applications that use it. A library can be either statically linked with the
18574 application, in which case its code is directly included in the application,
18575 or, on platforms that support it, be dynamically linked, in which case
18576 its code is shared by all applications making use of this library.
18577
18578 GNAT supports both types of libraries.
18579 In the static case, the compiled code can be provided in different ways. The
18580 simplest approach is to provide directly the set of objects resulting from
18581 compilation of the library source files. Alternatively, you can group the
18582 objects into an archive using whatever commands are provided by the operating
18583 system. For the latter case, the objects are grouped into a shared library.
18584
18585 In the GNAT environment, a library has three types of components:
18586 @itemize @bullet
18587 @item
18588 Source files.
18589 @item
18590 @file{ALI} files.
18591 @xref{The Ada Library Information Files}.
18592 @item
18593 Object files, an archive or a shared library.
18594 @end itemize
18595
18596 @noindent
18597 A GNAT library may expose all its source files, which is useful for
18598 documentation purposes. Alternatively, it may expose only the units needed by
18599 an external user to make use of the library. That is to say, the specs
18600 reflecting the library services along with all the units needed to compile
18601 those specs, which can include generic bodies or any body implementing an
18602 inlined routine. In the case of @emph{stand-alone libraries} those exposed
18603 units are called @emph{interface units} (@pxref{Stand-alone Ada Libraries}).
18604
18605 All compilation units comprising an application, including those in a library,
18606 need to be elaborated in an order partially defined by Ada's semantics. GNAT
18607 computes the elaboration order from the @file{ALI} files and this is why they
18608 constitute a mandatory part of GNAT libraries. Except in the case of
18609 @emph{stand-alone libraries}, where a specific library elaboration routine is
18610 produced independently of the application(s) using the library.
18611
18612 @node General Ada Libraries
18613 @section General Ada Libraries
18614
18615 @menu
18616 * Building a library::
18617 * Installing a library::
18618 * Using a library::
18619 @end menu
18620
18621 @node Building a library
18622 @subsection Building a library
18623
18624 @noindent
18625 The easiest way to build a library is to use the Project Manager,
18626 which supports a special type of project called a @emph{Library Project}
18627 (@pxref{Library Projects}).
18628
18629 A project is considered a library project, when two project-level attributes
18630 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
18631 control different aspects of library configuration, additional optional
18632 project-level attributes can be specified:
18633 @table @code
18634 @item Library_Kind
18635 This attribute controls whether the library is to be static or dynamic
18636
18637 @item Library_Version
18638 This attribute specifies the library version; this value is used
18639 during dynamic linking of shared libraries to determine if the currently
18640 installed versions of the binaries are compatible.
18641
18642 @item Library_Options
18643 @item Library_GCC
18644 These attributes specify additional low-level options to be used during
18645 library generation, and redefine the actual application used to generate
18646 library.
18647 @end table
18648
18649 @noindent
18650 The GNAT Project Manager takes full care of the library maintenance task,
18651 including recompilation of the source files for which objects do not exist
18652 or are not up to date, assembly of the library archive, and installation of
18653 the library (i.e., copying associated source, object and @file{ALI} files
18654 to the specified location).
18655
18656 Here is a simple library project file:
18657 @smallexample @c ada
18658 project My_Lib is
18659    for Source_Dirs use ("src1", "src2");
18660    for Object_Dir use "obj";
18661    for Library_Name use "mylib";
18662    for Library_Dir use "lib";
18663    for Library_Kind use "dynamic";
18664 end My_lib;
18665 @end smallexample
18666
18667 @noindent
18668 and the compilation command to build and install the library:
18669
18670 @smallexample @c ada
18671   $ gnatmake -Pmy_lib
18672 @end smallexample
18673
18674 @noindent
18675 It is not entirely trivial to perform manually all the steps required to
18676 produce a library. We recommend that you use the GNAT Project Manager
18677 for this task. In special cases where this is not desired, the necessary
18678 steps are discussed below.
18679
18680 There are various possibilities for compiling the units that make up the
18681 library: for example with a Makefile (@pxref{Using the GNU make Utility}) or
18682 with a conventional script. For simple libraries, it is also possible to create
18683 a dummy main program which depends upon all the packages that comprise the
18684 interface of the library. This dummy main program can then be given to
18685 @command{gnatmake}, which will ensure that all necessary objects are built.
18686
18687 After this task is accomplished, you should follow the standard procedure
18688 of the underlying operating system to produce the static or shared library.
18689
18690 Here is an example of such a dummy program:
18691 @smallexample @c ada
18692 @group
18693 with My_Lib.Service1;
18694 with My_Lib.Service2;
18695 with My_Lib.Service3;
18696 procedure My_Lib_Dummy is
18697 begin
18698    null;
18699 end;
18700 @end group
18701 @end smallexample
18702
18703 @noindent
18704 Here are the generic commands that will build an archive or a shared library.
18705
18706 @smallexample
18707 # compiling the library
18708 $ gnatmake -c my_lib_dummy.adb
18709
18710 # we don't need the dummy object itself
18711 $ rm my_lib_dummy.o my_lib_dummy.ali
18712
18713 # create an archive with the remaining objects
18714 $ ar rc libmy_lib.a *.o
18715 # some systems may require "ranlib" to be run as well
18716
18717 # or create a shared library
18718 $ gcc -shared -o libmy_lib.so *.o
18719 # some systems may require the code to have been compiled with -fPIC
18720
18721 # remove the object files that are now in the library
18722 $ rm *.o
18723
18724 # Make the ALI files read-only so that gnatmake will not try to
18725 # regenerate the objects that are in the library
18726 $ chmod -w *.ali
18727 @end smallexample
18728
18729 @noindent
18730 Please note that the library must have a name of the form @file{lib@var{xxx}.a}
18731 or @file{lib@var{xxx}.so} (or @file{lib@var{xxx}.dll} on Windows) in order to
18732 be accessed by the directive @option{-l@var{xxx}} at link time.
18733
18734 @node Installing a library
18735 @subsection Installing a library
18736 @cindex @code{ADA_PROJECT_PATH}
18737
18738 @noindent
18739 If you use project files, library installation is part of the library build
18740 process. Thus no further action is needed in order to make use of the
18741 libraries that are built as part of the general application build. A usable
18742 version of the library is installed in the directory specified by the
18743 @code{Library_Dir} attribute of the library project file.
18744
18745 You may want to install a library in a context different from where the library
18746 is built. This situation arises with third party suppliers, who may want
18747 to distribute a library in binary form where the user is not expected to be
18748 able to recompile the library. The simplest option in this case is to provide
18749 a project file slightly different from the one used to build the library, by
18750 using the @code{externally_built} attribute. For instance, the project
18751 file used to build the library in the previous section can be changed into the
18752 following one when the library is installed:
18753
18754 @smallexample @c projectfile
18755 project My_Lib is
18756    for Source_Dirs use ("src1", "src2");
18757    for Library_Name use "mylib";
18758    for Library_Dir use "lib";
18759    for Library_Kind use "dynamic";
18760    for Externally_Built use "true";
18761 end My_lib;
18762 @end smallexample
18763
18764 @noindent
18765 This project file assumes that the directories @file{src1},
18766 @file{src2}, and @file{lib} exist in
18767 the directory containing the project file. The @code{externally_built}
18768 attribute makes it clear to the GNAT builder that it should not attempt to
18769 recompile any of the units from this library. It allows the library provider to
18770 restrict the source set to the minimum necessary for clients to make use of the
18771 library as described in the first section of this chapter. It is the
18772 responsibility of the library provider to install the necessary sources, ALI
18773 files and libraries in the directories mentioned in the project file. For
18774 convenience, the user's library project file should be installed in a location
18775 that will be searched automatically by the GNAT
18776 builder. These are the directories referenced in the @env{ADA_PROJECT_PATH}
18777 environment variable (@pxref{Importing Projects}), and also the default GNAT
18778 library location that can be queried with @command{gnatls -v} and is usually of
18779 the form $gnat_install_root/lib/gnat.
18780
18781 When project files are not an option, it is also possible, but not recommended,
18782 to install the library so that the sources needed to use the library are on the
18783 Ada source path and the ALI files & libraries be on the Ada Object path (see
18784 @ref{Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
18785 administrator can place general-purpose libraries in the default compiler
18786 paths, by specifying the libraries' location in the configuration files
18787 @file{ada_source_path} and @file{ada_object_path}. These configuration files
18788 must be located in the GNAT installation tree at the same place as the gcc spec
18789 file. The location of the gcc spec file can be determined as follows:
18790 @smallexample
18791 $ gcc -v
18792 @end smallexample
18793
18794 @noindent
18795 The configuration files mentioned above have a simple format: each line
18796 must contain one unique directory name.
18797 Those names are added to the corresponding path
18798 in their order of appearance in the file. The names can be either absolute
18799 or relative; in the latter case, they are relative to where theses files
18800 are located.
18801
18802 The files @file{ada_source_path} and @file{ada_object_path} might not be
18803 present in a
18804 GNAT installation, in which case, GNAT will look for its run-time library in
18805 the directories @file{adainclude} (for the sources) and @file{adalib} (for the
18806 objects and @file{ALI} files). When the files exist, the compiler does not
18807 look in @file{adainclude} and @file{adalib}, and thus the
18808 @file{ada_source_path} file
18809 must contain the location for the GNAT run-time sources (which can simply
18810 be @file{adainclude}). In the same way, the @file{ada_object_path} file must
18811 contain the location for the GNAT run-time objects (which can simply
18812 be @file{adalib}).
18813
18814 You can also specify a new default path to the run-time library at compilation
18815 time with the switch @option{--RTS=rts-path}. You can thus choose / change
18816 the run-time library you want your program to be compiled with. This switch is
18817 recognized by @command{gcc}, @command{gnatmake}, @command{gnatbind},
18818 @command{gnatls}, @command{gnatfind} and @command{gnatxref}.
18819
18820 It is possible to install a library before or after the standard GNAT
18821 library, by reordering the lines in the configuration files. In general, a
18822 library must be installed before the GNAT library if it redefines
18823 any part of it.
18824
18825 @node Using a library
18826 @subsection Using a library
18827
18828 @noindent Once again, the project facility greatly simplifies the use of
18829 libraries. In this context, using a library is just a matter of adding a
18830 @code{with} clause in the user project. For instance, to make use of the
18831 library @code{My_Lib} shown in examples in earlier sections, you can
18832 write:
18833
18834 @smallexample @c projectfile
18835 with "my_lib";
18836 project My_Proj is
18837   @dots{}
18838 end My_Proj;
18839 @end smallexample
18840
18841 Even if you have a third-party, non-Ada library, you can still use GNAT's
18842 Project Manager facility to provide a wrapper for it. For example, the
18843 following project, when @code{with}ed by your main project, will link with the
18844 third-party library @file{liba.a}:
18845
18846 @smallexample @c projectfile
18847 @group
18848 project Liba is
18849    for Externally_Built use "true";
18850    for Source_Files use ();
18851    for Library_Dir use "lib";
18852    for Library_Name use "a";
18853    for Library_Kind use "static";
18854 end Liba;
18855 @end group
18856 @end smallexample
18857 This is an alternative to the use of @code{pragma Linker_Options}. It is
18858 especially interesting in the context of systems with several interdependent
18859 static libraries where finding a proper linker order is not easy and best be
18860 left to the tools having visibility over project dependence information.
18861
18862 @noindent
18863 In order to use an Ada library manually, you need to make sure that this
18864 library is on both your source and object path
18865 (see @ref{Search Paths and the Run-Time Library (RTL)}
18866 and @ref{Search Paths for gnatbind}). Furthermore, when the objects are grouped
18867 in an archive or a shared library, you need to specify the desired
18868 library at link time.
18869
18870 For example, you can use the library @file{mylib} installed in
18871 @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
18872
18873 @smallexample
18874 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
18875   -largs -lmy_lib
18876 @end smallexample
18877
18878 @noindent
18879 This can be expressed more simply:
18880 @smallexample
18881 $ gnatmake my_appl
18882 @end smallexample
18883 @noindent
18884 when the following conditions are met:
18885 @itemize @bullet
18886 @item
18887 @file{/dir/my_lib_src} has been added by the user to the environment
18888 variable @env{ADA_INCLUDE_PATH}, or by the administrator to the file
18889 @file{ada_source_path}
18890 @item
18891 @file{/dir/my_lib_obj} has been added by the user to the environment
18892 variable @env{ADA_OBJECTS_PATH}, or by the administrator to the file
18893 @file{ada_object_path}
18894 @item
18895 a pragma @code{Linker_Options} has been added to one of the sources.
18896 For example:
18897
18898 @smallexample @c ada
18899 pragma Linker_Options ("-lmy_lib");
18900 @end smallexample
18901 @end itemize
18902
18903 @node Stand-alone Ada Libraries
18904 @section Stand-alone Ada Libraries
18905 @cindex Stand-alone library, building, using
18906
18907 @menu
18908 * Introduction to Stand-alone Libraries::
18909 * Building a Stand-alone Library::
18910 * Creating a Stand-alone Library to be used in a non-Ada context::
18911 * Restrictions in Stand-alone Libraries::
18912 @end menu
18913
18914 @node Introduction to Stand-alone Libraries
18915 @subsection Introduction to Stand-alone Libraries
18916
18917 @noindent
18918 A Stand-alone Library (abbreviated ``SAL'') is a library that contains the
18919 necessary code to
18920 elaborate the Ada units that are included in the library. In contrast with
18921 an ordinary library, which consists of all sources, objects and @file{ALI}
18922 files of the
18923 library, a SAL may specify a restricted subset of compilation units
18924 to serve as a library interface. In this case, the fully
18925 self-sufficient set of files will normally consist of an objects
18926 archive, the sources of interface units' specs, and the @file{ALI}
18927 files of interface units.
18928 If an interface spec contains a generic unit or an inlined subprogram,
18929 the body's
18930 source must also be provided; if the units that must be provided in the source
18931 form depend on other units, the source and @file{ALI} files of those must
18932 also be provided.
18933
18934 The main purpose of a SAL is to minimize the recompilation overhead of client
18935 applications when a new version of the library is installed. Specifically,
18936 if the interface sources have not changed, client applications do not need to
18937 be recompiled. If, furthermore, a SAL is provided in the shared form and its
18938 version, controlled by @code{Library_Version} attribute, is not changed,
18939 then the clients do not need to be relinked.
18940
18941 SALs also allow the library providers to minimize the amount of library source
18942 text exposed to the clients.  Such ``information hiding'' might be useful or
18943 necessary for various reasons.
18944
18945 Stand-alone libraries are also well suited to be used in an executable whose
18946 main routine is not written in Ada.
18947
18948 @node Building a Stand-alone Library
18949 @subsection Building a Stand-alone Library
18950
18951 @noindent
18952 GNAT's Project facility provides a simple way of building and installing
18953 stand-alone libraries; see @ref{Stand-alone Library Projects}.
18954 To be a Stand-alone Library Project, in addition to the two attributes
18955 that make a project a Library Project (@code{Library_Name} and
18956 @code{Library_Dir}; see @ref{Library Projects}), the attribute
18957 @code{Library_Interface} must be defined.  For example:
18958
18959 @smallexample @c projectfile
18960 @group
18961    for Library_Dir use "lib_dir";
18962    for Library_Name use "dummy";
18963    for Library_Interface use ("int1", "int1.child");
18964 @end group
18965 @end smallexample
18966
18967 @noindent
18968 Attribute @code{Library_Interface} has a non-empty string list value,
18969 each string in the list designating a unit contained in an immediate source
18970 of the project file.
18971
18972 When a Stand-alone Library is built, first the binder is invoked to build
18973 a package whose name depends on the library name
18974 (@file{^b~dummy.ads/b^B$DUMMY.ADS/B^} in the example above).
18975 This binder-generated package includes initialization and
18976 finalization procedures whose
18977 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
18978 in the example
18979 above). The object corresponding to this package is included in the library.
18980
18981 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
18982 calling of these procedures if a static SAL is built, or if a shared SAL
18983 is built
18984 with the project-level attribute @code{Library_Auto_Init} set to
18985 @code{"false"}.
18986
18987 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
18988 (those that are listed in attribute @code{Library_Interface}) are copied to
18989 the Library Directory. As a consequence, only the Interface Units may be
18990 imported from Ada units outside of the library. If other units are imported,
18991 the binding phase will fail.
18992
18993 The attribute @code{Library_Src_Dir} may be specified for a
18994 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
18995 single string value. Its value must be the path (absolute or relative to the
18996 project directory) of an existing directory. This directory cannot be the
18997 object directory or one of the source directories, but it can be the same as
18998 the library directory. The sources of the Interface
18999 Units of the library that are needed by an Ada client of the library will be
19000 copied to the designated directory, called the Interface Copy directory.
19001 These sources include the specs of the Interface Units, but they may also
19002 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
19003 are used, or when there is a generic unit in the spec. Before the sources
19004 are copied to the Interface Copy directory, an attempt is made to delete all
19005 files in the Interface Copy directory.
19006
19007 Building stand-alone libraries by hand is somewhat tedious, but for those
19008 occasions when it is necessary here are the steps that you need to perform:
19009 @itemize @bullet
19010 @item
19011 Compile all library sources.
19012
19013 @item
19014 Invoke the binder with the switch @option{-n} (No Ada main program),
19015 with all the @file{ALI} files of the interfaces, and
19016 with the switch @option{-L} to give specific names to the @code{init}
19017 and @code{final} procedures.  For example:
19018 @smallexample
19019   gnatbind -n int1.ali int2.ali -Lsal1
19020 @end smallexample
19021
19022 @item
19023 Compile the binder generated file:
19024 @smallexample
19025   gcc -c b~int2.adb
19026 @end smallexample
19027
19028 @item
19029 Link the dynamic library with all the necessary object files,
19030 indicating to the linker the names of the @code{init} (and possibly
19031 @code{final}) procedures for automatic initialization (and finalization).
19032 The built library should be placed in a directory different from
19033 the object directory.
19034
19035 @item
19036 Copy the @code{ALI} files of the interface to the library directory,
19037 add in this copy an indication that it is an interface to a SAL
19038 (i.e., add a word @option{SL} on the line in the @file{ALI} file that starts
19039 with letter ``P'') and make the modified copy of the @file{ALI} file
19040 read-only.
19041 @end itemize
19042
19043 @noindent
19044 Using SALs is not different from using other libraries
19045 (see @ref{Using a library}).
19046
19047 @node Creating a Stand-alone Library to be used in a non-Ada context
19048 @subsection Creating a Stand-alone Library to be used in a non-Ada context
19049
19050 @noindent
19051 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
19052 a non-Ada context.
19053
19054 The only extra step required is to ensure that library interface subprograms
19055 are compatible with the main program, by means of @code{pragma Export}
19056 or @code{pragma Convention}.
19057
19058 Here is an example of simple library interface for use with C main program:
19059
19060 @smallexample @c ada
19061 package Interface is
19062
19063    procedure Do_Something;
19064    pragma Export (C, Do_Something, "do_something");
19065
19066    procedure Do_Something_Else;
19067    pragma Export (C, Do_Something_Else, "do_something_else");
19068
19069 end Interface;
19070 @end smallexample
19071
19072 @noindent
19073 On the foreign language side, you must provide a ``foreign'' view of the
19074 library interface; remember that it should contain elaboration routines in
19075 addition to interface subprograms.
19076
19077 The example below shows the content of @code{mylib_interface.h} (note
19078 that there is no rule for the naming of this file, any name can be used)
19079 @smallexample
19080 /* the library elaboration procedure */
19081 extern void mylibinit (void);
19082
19083 /* the library finalization procedure */
19084 extern void mylibfinal (void);
19085
19086 /* the interface exported by the library */
19087 extern void do_something (void);
19088 extern void do_something_else (void);
19089 @end smallexample
19090
19091 @noindent
19092 Libraries built as explained above can be used from any program, provided
19093 that the elaboration procedures (named @code{mylibinit} in the previous
19094 example) are called before the library services are used. Any number of
19095 libraries can be used simultaneously, as long as the elaboration
19096 procedure of each library is called.
19097
19098 Below is an example of a C program that uses the @code{mylib} library.
19099
19100 @smallexample
19101 #include "mylib_interface.h"
19102
19103 int
19104 main (void)
19105 @{
19106    /* First, elaborate the library before using it */
19107    mylibinit ();
19108
19109    /* Main program, using the library exported entities */
19110    do_something ();
19111    do_something_else ();
19112
19113    /* Library finalization at the end of the program */
19114    mylibfinal ();
19115    return 0;
19116 @}
19117 @end smallexample
19118
19119 @noindent
19120 Note that invoking any library finalization procedure generated by
19121 @code{gnatbind} shuts down the Ada run-time environment.
19122 Consequently, the
19123 finalization of all Ada libraries must be performed at the end of the program.
19124 No call to these libraries or to the Ada run-time library should be made
19125 after the finalization phase.
19126
19127 @node Restrictions in Stand-alone Libraries
19128 @subsection Restrictions in Stand-alone Libraries
19129
19130 @noindent
19131 The pragmas listed below should be used with caution inside libraries,
19132 as they can create incompatibilities with other Ada libraries:
19133 @itemize @bullet
19134 @item pragma @code{Locking_Policy}
19135 @item pragma @code{Queuing_Policy}
19136 @item pragma @code{Task_Dispatching_Policy}
19137 @item pragma @code{Unreserve_All_Interrupts}
19138 @end itemize
19139
19140 @noindent
19141 When using a library that contains such pragmas, the user must make sure
19142 that all libraries use the same pragmas with the same values. Otherwise,
19143 @code{Program_Error} will
19144 be raised during the elaboration of the conflicting
19145 libraries. The usage of these pragmas and its consequences for the user
19146 should therefore be well documented.
19147
19148 Similarly, the traceback in the exception occurrence mechanism should be
19149 enabled or disabled in a consistent manner across all libraries.
19150 Otherwise, Program_Error will be raised during the elaboration of the
19151 conflicting libraries.
19152
19153 If the @code{Version} or @code{Body_Version}
19154 attributes are used inside a library, then you need to
19155 perform a @code{gnatbind} step that specifies all @file{ALI} files in all
19156 libraries, so that version identifiers can be properly computed.
19157 In practice these attributes are rarely used, so this is unlikely
19158 to be a consideration.
19159
19160 @node  Rebuilding the GNAT Run-Time Library
19161 @section Rebuilding the GNAT Run-Time Library
19162 @cindex GNAT Run-Time Library, rebuilding
19163 @cindex Building the GNAT Run-Time Library
19164 @cindex Rebuilding the GNAT Run-Time Library
19165 @cindex Run-Time Library, rebuilding
19166
19167 @noindent
19168 It may be useful to recompile the GNAT library in various contexts, the
19169 most important one being the use of partition-wide configuration pragmas
19170 such as @code{Normalize_Scalars}. A special Makefile called
19171 @code{Makefile.adalib} is provided to that effect and can be found in
19172 the directory containing the GNAT library. The location of this
19173 directory depends on the way the GNAT environment has been installed and can
19174 be determined by means of the command:
19175
19176 @smallexample
19177 $ gnatls -v
19178 @end smallexample
19179
19180 @noindent
19181 The last entry in the object search path usually contains the
19182 gnat library. This Makefile contains its own documentation and in
19183 particular the set of instructions needed to rebuild a new library and
19184 to use it.
19185
19186 @node Using the GNU make Utility
19187 @chapter Using the GNU @code{make} Utility
19188 @findex make
19189
19190 @noindent
19191 This chapter offers some examples of makefiles that solve specific
19192 problems. It does not explain how to write a makefile (@pxref{Top,, GNU
19193 make, make, GNU @code{make}}), nor does it try to replace the
19194 @command{gnatmake} utility (@pxref{The GNAT Make Program gnatmake}).
19195
19196 All the examples in this section are specific to the GNU version of
19197 make. Although @command{make} is a standard utility, and the basic language
19198 is the same, these examples use some advanced features found only in
19199 @code{GNU make}.
19200
19201 @menu
19202 * Using gnatmake in a Makefile::
19203 * Automatically Creating a List of Directories::
19204 * Generating the Command Line Switches::
19205 * Overcoming Command Line Length Limits::
19206 @end menu
19207
19208 @node Using gnatmake in a Makefile
19209 @section Using gnatmake in a Makefile
19210 @findex makefile
19211 @cindex GNU make
19212
19213 @noindent
19214 Complex project organizations can be handled in a very powerful way by
19215 using GNU make combined with gnatmake. For instance, here is a Makefile
19216 which allows you to build each subsystem of a big project into a separate
19217 shared library. Such a makefile allows you to significantly reduce the link
19218 time of very big applications while maintaining full coherence at
19219 each step of the build process.
19220
19221 The list of dependencies are handled automatically by
19222 @command{gnatmake}. The Makefile is simply used to call gnatmake in each of
19223 the appropriate directories.
19224
19225 Note that you should also read the example on how to automatically
19226 create the list of directories
19227 (@pxref{Automatically Creating a List of Directories})
19228 which might help you in case your project has a lot of subdirectories.
19229
19230 @smallexample
19231 @iftex
19232 @leftskip=0cm
19233 @font@heightrm=cmr8
19234 @heightrm
19235 @end iftex
19236 ## This Makefile is intended to be used with the following directory
19237 ## configuration:
19238 ##  - The sources are split into a series of csc (computer software components)
19239 ##    Each of these csc is put in its own directory.
19240 ##    Their name are referenced by the directory names.
19241 ##    They will be compiled into shared library (although this would also work
19242 ##    with static libraries
19243 ##  - The main program (and possibly other packages that do not belong to any
19244 ##    csc is put in the top level directory (where the Makefile is).
19245 ##       toplevel_dir __ first_csc  (sources) __ lib (will contain the library)
19246 ##                    \_ second_csc (sources) __ lib (will contain the library)
19247 ##                    \_ @dots{}
19248 ## Although this Makefile is build for shared library, it is easy to modify
19249 ## to build partial link objects instead (modify the lines with -shared and
19250 ## gnatlink below)
19251 ##
19252 ## With this makefile, you can change any file in the system or add any new
19253 ## file, and everything will be recompiled correctly (only the relevant shared
19254 ## objects will be recompiled, and the main program will be re-linked).
19255
19256 # The list of computer software component for your project. This might be
19257 # generated automatically.
19258 CSC_LIST=aa bb cc
19259
19260 # Name of the main program (no extension)
19261 MAIN=main
19262
19263 # If we need to build objects with -fPIC, uncomment the following line
19264 #NEED_FPIC=-fPIC
19265
19266 # The following variable should give the directory containing libgnat.so
19267 # You can get this directory through 'gnatls -v'. This is usually the last
19268 # directory in the Object_Path.
19269 GLIB=@dots{}
19270
19271 # The directories for the libraries
19272 # (This macro expands the list of CSC to the list of shared libraries, you
19273 # could simply use the expanded form:
19274 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
19275 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
19276
19277 $@{MAIN@}: objects $@{LIB_DIR@}
19278     gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
19279     gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
19280
19281 objects::
19282     # recompile the sources
19283     gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
19284
19285 # Note: In a future version of GNAT, the following commands will be simplified
19286 # by a new tool, gnatmlib
19287 $@{LIB_DIR@}:
19288     mkdir -p $@{dir $@@ @}
19289     cd $@{dir $@@ @} && gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
19290     cd $@{dir $@@ @} && cp -f ../*.ali .
19291
19292 # The dependencies for the modules
19293 # Note that we have to force the expansion of *.o, since in some cases
19294 # make won't be able to do it itself.
19295 aa/lib/libaa.so: $@{wildcard aa/*.o@}
19296 bb/lib/libbb.so: $@{wildcard bb/*.o@}
19297 cc/lib/libcc.so: $@{wildcard cc/*.o@}
19298
19299 # Make sure all of the shared libraries are in the path before starting the
19300 # program
19301 run::
19302     LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
19303
19304 clean::
19305     $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
19306     $@{RM@} $@{CSC_LIST:%=%/*.ali@}
19307     $@{RM@} $@{CSC_LIST:%=%/*.o@}
19308     $@{RM@} *.o *.ali $@{MAIN@}
19309 @end smallexample
19310
19311 @node Automatically Creating a List of Directories
19312 @section Automatically Creating a List of Directories
19313
19314 @noindent
19315 In most makefiles, you will have to specify a list of directories, and
19316 store it in a variable. For small projects, it is often easier to
19317 specify each of them by hand, since you then have full control over what
19318 is the proper order for these directories, which ones should be
19319 included.
19320
19321 However, in larger projects, which might involve hundreds of
19322 subdirectories, it might be more convenient to generate this list
19323 automatically.
19324
19325 The example below presents two methods. The first one, although less
19326 general, gives you more control over the list. It involves wildcard
19327 characters, that are automatically expanded by @command{make}. Its
19328 shortcoming is that you need to explicitly specify some of the
19329 organization of your project, such as for instance the directory tree
19330 depth, whether some directories are found in a separate tree, @enddots{}
19331
19332 The second method is the most general one. It requires an external
19333 program, called @command{find}, which is standard on all Unix systems. All
19334 the directories found under a given root directory will be added to the
19335 list.
19336
19337 @smallexample
19338 @iftex
19339 @leftskip=0cm
19340 @font@heightrm=cmr8
19341 @heightrm
19342 @end iftex
19343 # The examples below are based on the following directory hierarchy:
19344 # All the directories can contain any number of files
19345 # ROOT_DIRECTORY ->  a  ->  aa  ->  aaa
19346 #                       ->  ab
19347 #                       ->  ac
19348 #                ->  b  ->  ba  ->  baa
19349 #                       ->  bb
19350 #                       ->  bc
19351 # This Makefile creates a variable called DIRS, that can be reused any time
19352 # you need this list (see the other examples in this section)
19353
19354 # The root of your project's directory hierarchy
19355 ROOT_DIRECTORY=.
19356
19357 ####
19358 # First method: specify explicitly the list of directories
19359 # This allows you to specify any subset of all the directories you need.
19360 ####
19361
19362 DIRS := a/aa/ a/ab/ b/ba/
19363
19364 ####
19365 # Second method: use wildcards
19366 # Note that the argument(s) to wildcard below should end with a '/'.
19367 # Since wildcards also return file names, we have to filter them out
19368 # to avoid duplicate directory names.
19369 # We thus use make's @code{dir} and @code{sort} functions.
19370 # It sets DIRs to the following value (note that the directories aaa and baa
19371 # are not given, unless you change the arguments to wildcard).
19372 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
19373 ####
19374
19375 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
19376                     $@{ROOT_DIRECTORY@}/*/*/@}@}@}
19377
19378 ####
19379 # Third method: use an external program
19380 # This command is much faster if run on local disks, avoiding NFS slowdowns.
19381 # This is the most complete command: it sets DIRs to the following value:
19382 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
19383 ####
19384
19385 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
19386
19387 @end smallexample
19388
19389 @node Generating the Command Line Switches
19390 @section Generating the Command Line Switches
19391
19392 @noindent
19393 Once you have created the list of directories as explained in the
19394 previous section (@pxref{Automatically Creating a List of Directories}),
19395 you can easily generate the command line arguments to pass to gnatmake.
19396
19397 For the sake of completeness, this example assumes that the source path
19398 is not the same as the object path, and that you have two separate lists
19399 of directories.
19400
19401 @smallexample
19402 # see "Automatically creating a list of directories" to create
19403 # these variables
19404 SOURCE_DIRS=
19405 OBJECT_DIRS=
19406
19407 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
19408 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
19409
19410 all:
19411         gnatmake $@{GNATMAKE_SWITCHES@} main_unit
19412 @end smallexample
19413
19414 @node Overcoming Command Line Length Limits
19415 @section Overcoming Command Line Length Limits
19416
19417 @noindent
19418 One problem that might be encountered on big projects is that many
19419 operating systems limit the length of the command line. It is thus hard to give
19420 gnatmake the list of source and object directories.
19421
19422 This example shows how you can set up environment variables, which will
19423 make @command{gnatmake} behave exactly as if the directories had been
19424 specified on the command line, but have a much higher length limit (or
19425 even none on most systems).
19426
19427 It assumes that you have created a list of directories in your Makefile,
19428 using one of the methods presented in
19429 @ref{Automatically Creating a List of Directories}.
19430 For the sake of completeness, we assume that the object
19431 path (where the ALI files are found) is different from the sources patch.
19432
19433 Note a small trick in the Makefile below: for efficiency reasons, we
19434 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
19435 expanded immediately by @code{make}. This way we overcome the standard
19436 make behavior which is to expand the variables only when they are
19437 actually used.
19438
19439 On Windows, if you are using the standard Windows command shell, you must
19440 replace colons with semicolons in the assignments to these variables.
19441
19442 @smallexample
19443 @iftex
19444 @leftskip=0cm
19445 @font@heightrm=cmr8
19446 @heightrm
19447 @end iftex
19448 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECT_PATH.
19449 # This is the same thing as putting the -I arguments on the command line.
19450 # (the equivalent of using -aI on the command line would be to define
19451 #  only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECT_PATH).
19452 # You can of course have different values for these variables.
19453 #
19454 # Note also that we need to keep the previous values of these variables, since
19455 # they might have been set before running 'make' to specify where the GNAT
19456 # library is installed.
19457
19458 # see "Automatically creating a list of directories" to create these
19459 # variables
19460 SOURCE_DIRS=
19461 OBJECT_DIRS=
19462
19463 empty:=
19464 space:=$@{empty@} $@{empty@}
19465 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
19466 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
19467 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
19468 ADA_OBJECT_PATH += $@{OBJECT_LIST@}
19469 export ADA_INCLUDE_PATH
19470 export ADA_OBJECT_PATH
19471
19472 all:
19473         gnatmake main_unit
19474 @end smallexample
19475 @end ifclear
19476
19477 @node Memory Management Issues
19478 @chapter Memory Management Issues
19479
19480 @noindent
19481 This chapter describes some useful memory pools provided in the GNAT library
19482 and in particular the GNAT Debug Pool facility, which can be used to detect
19483 incorrect uses of access values (including ``dangling references'').
19484 @ifclear vms
19485 It also describes the @command{gnatmem} tool, which can be used to track down
19486 ``memory leaks''.
19487 @end ifclear
19488
19489 @menu
19490 * Some Useful Memory Pools::
19491 * The GNAT Debug Pool Facility::
19492 @ifclear vms
19493 * The gnatmem Tool::
19494 @end ifclear
19495 @end menu
19496
19497 @node Some Useful Memory Pools
19498 @section Some Useful Memory Pools
19499 @findex Memory Pool
19500 @cindex storage, pool
19501
19502 @noindent
19503 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
19504 storage pool. Allocations use the standard system call @code{malloc} while
19505 deallocations use the standard system call @code{free}. No reclamation is
19506 performed when the pool goes out of scope. For performance reasons, the
19507 standard default Ada allocators/deallocators do not use any explicit storage
19508 pools but if they did, they could use this storage pool without any change in
19509 behavior. That is why this storage pool is used  when the user
19510 manages to make the default implicit allocator explicit as in this example:
19511 @smallexample @c ada
19512    type T1 is access Something;
19513     -- no Storage pool is defined for T2
19514    type T2 is access Something_Else;
19515    for T2'Storage_Pool use T1'Storage_Pool;
19516    -- the above is equivalent to
19517    for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
19518 @end smallexample
19519
19520 @noindent
19521 The @code{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
19522 pool. The allocation strategy is similar to @code{Pool_Local}'s
19523 except that the all
19524 storage allocated with this pool is reclaimed when the pool object goes out of
19525 scope. This pool provides a explicit mechanism similar to the implicit one
19526 provided by several Ada 83 compilers for allocations performed through a local
19527 access type and whose purpose was to reclaim memory when exiting the
19528 scope of a given local access. As an example, the following program does not
19529 leak memory even though it does not perform explicit deallocation:
19530
19531 @smallexample @c ada
19532 with System.Pool_Local;
19533 procedure Pooloc1 is
19534    procedure Internal is
19535       type A is access Integer;
19536       X : System.Pool_Local.Unbounded_Reclaim_Pool;
19537       for A'Storage_Pool use X;
19538       v : A;
19539    begin
19540       for I in  1 .. 50 loop
19541          v := new Integer;
19542       end loop;
19543    end Internal;
19544 begin
19545    for I in  1 .. 100 loop
19546       Internal;
19547    end loop;
19548 end Pooloc1;
19549 @end smallexample
19550
19551 @noindent
19552 The @code{System.Pool_Size} package implements the Stack_Bounded_Pool used when
19553 @code{Storage_Size} is specified for an access type.
19554 The whole storage for the pool is
19555 allocated at once, usually on the stack at the point where the access type is
19556 elaborated. It is automatically reclaimed when exiting the scope where the
19557 access type is defined. This package is not intended to be used directly by the
19558 user and it is implicitly used for each such declaration:
19559
19560 @smallexample @c ada
19561    type T1 is access Something;
19562    for T1'Storage_Size use 10_000;
19563 @end smallexample
19564
19565 @node The GNAT Debug Pool Facility
19566 @section The GNAT Debug Pool Facility
19567 @findex Debug Pool
19568 @cindex storage, pool, memory corruption
19569
19570 @noindent
19571 The use of unchecked deallocation and unchecked conversion can easily
19572 lead to incorrect memory references. The problems generated by such
19573 references are usually difficult to tackle because the symptoms can be
19574 very remote from the origin of the problem. In such cases, it is
19575 very helpful to detect the problem as early as possible. This is the
19576 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
19577
19578 In order to use the GNAT specific debugging pool, the user must
19579 associate a debug pool object with each of the access types that may be
19580 related to suspected memory problems. See Ada Reference Manual 13.11.
19581 @smallexample @c ada
19582 type Ptr is access Some_Type;
19583 Pool : GNAT.Debug_Pools.Debug_Pool;
19584 for Ptr'Storage_Pool use Pool;
19585 @end smallexample
19586
19587 @noindent
19588 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
19589 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
19590 allow the user to redefine allocation and deallocation strategies. They
19591 also provide a checkpoint for each dereference, through the use of
19592 the primitive operation @code{Dereference} which is implicitly called at
19593 each dereference of an access value.
19594
19595 Once an access type has been associated with a debug pool, operations on
19596 values of the type may raise four distinct exceptions,
19597 which correspond to four potential kinds of memory corruption:
19598 @itemize @bullet
19599 @item
19600 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
19601 @item
19602 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
19603 @item
19604 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
19605 @item
19606 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
19607 @end itemize
19608
19609 @noindent
19610 For types associated with a Debug_Pool, dynamic allocation is performed using
19611 the standard GNAT allocation routine. References to all allocated chunks of
19612 memory are kept in an internal dictionary. Several deallocation strategies are
19613 provided, whereupon the user can choose to release the memory to the system,
19614 keep it allocated for further invalid access checks, or fill it with an easily
19615 recognizable pattern for debug sessions. The memory pattern is the old IBM
19616 hexadecimal convention: @code{16#DEADBEEF#}.
19617
19618 See the documentation in the file g-debpoo.ads for more information on the
19619 various strategies.
19620
19621 Upon each dereference, a check is made that the access value denotes a
19622 properly allocated memory location. Here is a complete example of use of
19623 @code{Debug_Pools}, that includes typical instances of  memory corruption:
19624 @smallexample @c ada
19625 @iftex
19626 @leftskip=0cm
19627 @end iftex
19628 with Gnat.Io; use Gnat.Io;
19629 with Unchecked_Deallocation;
19630 with Unchecked_Conversion;
19631 with GNAT.Debug_Pools;
19632 with System.Storage_Elements;
19633 with Ada.Exceptions; use Ada.Exceptions;
19634 procedure Debug_Pool_Test is
19635
19636    type T is access Integer;
19637    type U is access all T;
19638
19639    P : GNAT.Debug_Pools.Debug_Pool;
19640    for T'Storage_Pool use P;
19641
19642    procedure Free is new Unchecked_Deallocation (Integer, T);
19643    function UC is new Unchecked_Conversion (U, T);
19644    A, B : aliased T;
19645
19646    procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
19647
19648 begin
19649    Info (P);
19650    A := new Integer;
19651    B := new Integer;
19652    B := A;
19653    Info (P);
19654    Free (A);
19655    begin
19656       Put_Line (Integer'Image(B.all));
19657    exception
19658       when E : others => Put_Line ("raised: " & Exception_Name (E));
19659    end;
19660    begin
19661       Free (B);
19662    exception
19663       when E : others => Put_Line ("raised: " & Exception_Name (E));
19664    end;
19665    B := UC(A'Access);
19666    begin
19667       Put_Line (Integer'Image(B.all));
19668    exception
19669       when E : others => Put_Line ("raised: " & Exception_Name (E));
19670    end;
19671    begin
19672       Free (B);
19673    exception
19674       when E : others => Put_Line ("raised: " & Exception_Name (E));
19675    end;
19676    Info (P);
19677 end Debug_Pool_Test;
19678 @end smallexample
19679
19680 @noindent
19681 The debug pool mechanism provides the following precise diagnostics on the
19682 execution of this erroneous program:
19683 @smallexample
19684 Debug Pool info:
19685   Total allocated bytes :  0
19686   Total deallocated bytes :  0
19687   Current Water Mark:  0
19688   High Water Mark:  0
19689
19690 Debug Pool info:
19691   Total allocated bytes :  8
19692   Total deallocated bytes :  0
19693   Current Water Mark:  8
19694   High Water Mark:  8
19695
19696 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
19697 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
19698 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
19699 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
19700 Debug Pool info:
19701   Total allocated bytes :  8
19702   Total deallocated bytes :  4
19703   Current Water Mark:  4
19704   High Water Mark:  8
19705 @end smallexample
19706
19707 @ifclear vms
19708 @node The gnatmem Tool
19709 @section The @command{gnatmem} Tool
19710 @findex gnatmem
19711
19712 @noindent
19713 The @code{gnatmem} utility monitors dynamic allocation and
19714 deallocation activity in a program, and displays information about
19715 incorrect deallocations and possible sources of memory leaks.
19716 It is designed to work in association with a static runtime library
19717 only and in this context provides three types of information:
19718 @itemize @bullet
19719 @item
19720 General information concerning memory management, such as the total
19721 number of allocations and deallocations, the amount of allocated
19722 memory and the high water mark, i.e.@: the largest amount of allocated
19723 memory in the course of program execution.
19724
19725 @item
19726 Backtraces for all incorrect deallocations, that is to say deallocations
19727 which do not correspond to a valid allocation.
19728
19729 @item
19730 Information on each allocation that is potentially the origin of a memory
19731 leak.
19732 @end itemize
19733
19734 @menu
19735 * Running gnatmem::
19736 * Switches for gnatmem::
19737 * Example of gnatmem Usage::
19738 @end menu
19739
19740 @node Running gnatmem
19741 @subsection Running @code{gnatmem}
19742
19743 @noindent
19744 @code{gnatmem} makes use of the output created by the special version of
19745 allocation and deallocation routines that record call information. This
19746 allows to obtain accurate dynamic memory usage history at a minimal cost to
19747 the execution speed. Note however, that @code{gnatmem} is not supported on
19748 all platforms (currently, it is supported on AIX, HP-UX, GNU/Linux,
19749 Solaris and Windows NT/2000/XP (x86).
19750
19751 @noindent
19752 The @code{gnatmem} command has the form
19753
19754 @smallexample
19755    $ gnatmem @ovar{switches} user_program
19756 @end smallexample
19757
19758 @noindent
19759 The program must have been linked with the instrumented version of the
19760 allocation and deallocation routines. This is done by linking with the
19761 @file{libgmem.a} library. For correct symbolic backtrace information,
19762 the user program should be compiled with debugging options
19763 (see @ref{Switches for gcc}). For example to build @file{my_program}:
19764
19765 @smallexample
19766 $ gnatmake -g my_program -largs -lgmem
19767 @end smallexample
19768
19769 @noindent
19770 As library @file{libgmem.a} contains an alternate body for package
19771 @code{System.Memory}, @file{s-memory.adb} should not be compiled and linked
19772 when an executable is linked with library @file{libgmem.a}. It is then not
19773 recommended to use @command{gnatmake} with switch @option{^-a^/ALL_FILES^}.
19774
19775 @noindent
19776 When @file{my_program} is executed, the file @file{gmem.out} is produced.
19777 This file contains information about all allocations and deallocations
19778 performed by the program. It is produced by the instrumented allocations and
19779 deallocations routines and will be used by @code{gnatmem}.
19780
19781 In order to produce symbolic backtrace information for allocations and
19782 deallocations performed by the GNAT run-time library, you need to use a
19783 version of that library that has been compiled with the @option{-g} switch
19784 (see @ref{Rebuilding the GNAT Run-Time Library}).
19785
19786 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
19787 examine. If the location of @file{gmem.out} file was not explicitly supplied by
19788 @option{-i} switch, gnatmem will assume that this file can be found in the
19789 current directory. For example, after you have executed @file{my_program},
19790 @file{gmem.out} can be analyzed by @code{gnatmem} using the command:
19791
19792 @smallexample
19793 $ gnatmem my_program
19794 @end smallexample
19795
19796 @noindent
19797 This will produce the output with the following format:
19798
19799 *************** debut cc
19800 @smallexample
19801 $ gnatmem my_program
19802
19803 Global information
19804 ------------------
19805    Total number of allocations        :  45
19806    Total number of deallocations      :   6
19807    Final Water Mark (non freed mem)   :  11.29 Kilobytes
19808    High Water Mark                    :  11.40 Kilobytes
19809
19810 .
19811 .
19812 .
19813 Allocation Root # 2
19814 -------------------
19815  Number of non freed allocations    :  11
19816  Final Water Mark (non freed mem)   :   1.16 Kilobytes
19817  High Water Mark                    :   1.27 Kilobytes
19818  Backtrace                          :
19819    my_program.adb:23 my_program.alloc
19820 .
19821 .
19822 .
19823 @end smallexample
19824
19825 The first block of output gives general information. In this case, the
19826 Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
19827 Unchecked_Deallocation routine occurred.
19828
19829 @noindent
19830 Subsequent paragraphs display  information on all allocation roots.
19831 An allocation root is a specific point in the execution of the program
19832 that generates some dynamic allocation, such as a ``@code{@b{new}}''
19833 construct. This root is represented by an execution backtrace (or subprogram
19834 call stack). By default the backtrace depth for allocations roots is 1, so
19835 that a root corresponds exactly to a source location. The backtrace can
19836 be made deeper, to make the root more specific.
19837
19838 @node Switches for gnatmem
19839 @subsection Switches for @code{gnatmem}
19840
19841 @noindent
19842 @code{gnatmem} recognizes the following switches:
19843
19844 @table @option
19845
19846 @item -q
19847 @cindex @option{-q} (@code{gnatmem})
19848 Quiet. Gives the minimum output needed to identify the origin of the
19849 memory leaks. Omits statistical information.
19850
19851 @item @var{N}
19852 @cindex @var{N} (@code{gnatmem})
19853 N is an integer literal (usually between 1 and 10) which controls the
19854 depth of the backtraces defining allocation root. The default value for
19855 N is 1. The deeper the backtrace, the more precise the localization of
19856 the root. Note that the total number of roots can depend on this
19857 parameter. This parameter must be specified @emph{before} the name of the
19858 executable to be analyzed, to avoid ambiguity.
19859
19860 @item -b n
19861 @cindex @option{-b} (@code{gnatmem})
19862 This switch has the same effect as just depth parameter.
19863
19864 @item -i @var{file}
19865 @cindex @option{-i} (@code{gnatmem})
19866 Do the @code{gnatmem} processing starting from @file{file}, rather than
19867 @file{gmem.out} in the current directory.
19868
19869 @item -m n
19870 @cindex @option{-m} (@code{gnatmem})
19871 This switch causes @code{gnatmem} to mask the allocation roots that have less
19872 than n leaks. The default value is 1. Specifying the value of 0 will allow to
19873 examine even the roots that didn't result in leaks.
19874
19875 @item -s order
19876 @cindex @option{-s} (@code{gnatmem})
19877 This switch causes @code{gnatmem} to sort the allocation roots according to the
19878 specified order of sort criteria, each identified by a single letter. The
19879 currently supported criteria are @code{n, h, w} standing respectively for
19880 number of unfreed allocations, high watermark, and final watermark
19881 corresponding to a specific root. The default order is @code{nwh}.
19882
19883 @end table
19884
19885 @node Example of gnatmem Usage
19886 @subsection Example of @code{gnatmem} Usage
19887
19888 @noindent
19889 The following example shows the use of @code{gnatmem}
19890 on a simple memory-leaking program.
19891 Suppose that we have the following Ada program:
19892
19893 @smallexample @c ada
19894 @group
19895 @cartouche
19896 with Unchecked_Deallocation;
19897 procedure Test_Gm is
19898
19899    type T is array (1..1000) of Integer;
19900    type Ptr is access T;
19901    procedure Free is new Unchecked_Deallocation (T, Ptr);
19902    A : Ptr;
19903
19904    procedure My_Alloc is
19905    begin
19906       A := new T;
19907    end My_Alloc;
19908
19909    procedure My_DeAlloc is
19910       B : Ptr := A;
19911    begin
19912       Free (B);
19913    end My_DeAlloc;
19914
19915 begin
19916    My_Alloc;
19917    for I in 1 .. 5 loop
19918       for J in I .. 5 loop
19919          My_Alloc;
19920       end loop;
19921       My_Dealloc;
19922    end loop;
19923 end;
19924 @end cartouche
19925 @end group
19926 @end smallexample
19927
19928 @noindent
19929 The program needs to be compiled with debugging option and linked with
19930 @code{gmem} library:
19931
19932 @smallexample
19933 $ gnatmake -g test_gm -largs -lgmem
19934 @end smallexample
19935
19936 @noindent
19937 Then we execute the program as usual:
19938
19939 @smallexample
19940 $ test_gm
19941 @end smallexample
19942
19943 @noindent
19944 Then @code{gnatmem} is invoked simply with
19945 @smallexample
19946 $ gnatmem test_gm
19947 @end smallexample
19948
19949 @noindent
19950 which produces the following output (result may vary on different platforms):
19951
19952 @smallexample
19953 Global information
19954 ------------------
19955    Total number of allocations        :  18
19956    Total number of deallocations      :   5
19957    Final Water Mark (non freed mem)   :  53.00 Kilobytes
19958    High Water Mark                    :  56.90 Kilobytes
19959
19960 Allocation Root # 1
19961 -------------------
19962  Number of non freed allocations    :  11
19963  Final Water Mark (non freed mem)   :  42.97 Kilobytes
19964  High Water Mark                    :  46.88 Kilobytes
19965  Backtrace                          :
19966    test_gm.adb:11 test_gm.my_alloc
19967
19968 Allocation Root # 2
19969 -------------------
19970  Number of non freed allocations    :   1
19971  Final Water Mark (non freed mem)   :  10.02 Kilobytes
19972  High Water Mark                    :  10.02 Kilobytes
19973  Backtrace                          :
19974    s-secsta.adb:81 system.secondary_stack.ss_init
19975
19976 Allocation Root # 3
19977 -------------------
19978  Number of non freed allocations    :   1
19979  Final Water Mark (non freed mem)   :  12 Bytes
19980  High Water Mark                    :  12 Bytes
19981  Backtrace                          :
19982    s-secsta.adb:181 system.secondary_stack.ss_init
19983 @end smallexample
19984
19985 @noindent
19986 Note that the GNAT run time contains itself a certain number of
19987 allocations that have no  corresponding deallocation,
19988 as shown here for root #2 and root
19989 #3. This is a normal behavior when the number of non-freed allocations
19990 is one, it allocates dynamic data structures that the run time needs for
19991 the complete lifetime of the program. Note also that there is only one
19992 allocation root in the user program with a single line back trace:
19993 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
19994 program shows that 'My_Alloc' is called at 2 different points in the
19995 source (line 21 and line 24). If those two allocation roots need to be
19996 distinguished, the backtrace depth parameter can be used:
19997
19998 @smallexample
19999 $ gnatmem 3 test_gm
20000 @end smallexample
20001
20002 @noindent
20003 which will give the following output:
20004
20005 @smallexample
20006 Global information
20007 ------------------
20008    Total number of allocations        :  18
20009    Total number of deallocations      :   5
20010    Final Water Mark (non freed mem)   :  53.00 Kilobytes
20011    High Water Mark                    :  56.90 Kilobytes
20012
20013 Allocation Root # 1
20014 -------------------
20015  Number of non freed allocations    :  10
20016  Final Water Mark (non freed mem)   :  39.06 Kilobytes
20017  High Water Mark                    :  42.97 Kilobytes
20018  Backtrace                          :
20019    test_gm.adb:11 test_gm.my_alloc
20020    test_gm.adb:24 test_gm
20021    b_test_gm.c:52 main
20022
20023 Allocation Root # 2
20024 -------------------
20025  Number of non freed allocations    :   1
20026  Final Water Mark (non freed mem)   :  10.02 Kilobytes
20027  High Water Mark                    :  10.02 Kilobytes
20028  Backtrace                          :
20029    s-secsta.adb:81  system.secondary_stack.ss_init
20030    s-secsta.adb:283 <system__secondary_stack___elabb>
20031    b_test_gm.c:33   adainit
20032
20033 Allocation Root # 3
20034 -------------------
20035  Number of non freed allocations    :   1
20036  Final Water Mark (non freed mem)   :   3.91 Kilobytes
20037  High Water Mark                    :   3.91 Kilobytes
20038  Backtrace                          :
20039    test_gm.adb:11 test_gm.my_alloc
20040    test_gm.adb:21 test_gm
20041    b_test_gm.c:52 main
20042
20043 Allocation Root # 4
20044 -------------------
20045  Number of non freed allocations    :   1
20046  Final Water Mark (non freed mem)   :  12 Bytes
20047  High Water Mark                    :  12 Bytes
20048  Backtrace                          :
20049    s-secsta.adb:181 system.secondary_stack.ss_init
20050    s-secsta.adb:283 <system__secondary_stack___elabb>
20051    b_test_gm.c:33   adainit
20052 @end smallexample
20053
20054 @noindent
20055 The allocation root #1 of the first example has been split in 2 roots #1
20056 and #3 thanks to the more precise associated backtrace.
20057
20058 @end ifclear
20059
20060 @node Stack Related Facilities
20061 @chapter Stack Related Facilities
20062
20063 @noindent
20064 This chapter describes some useful tools associated with stack
20065 checking and analysis. In
20066 particular, it deals with dynamic and static stack usage measurements.
20067
20068 @menu
20069 * Stack Overflow Checking::
20070 * Static Stack Usage Analysis::
20071 * Dynamic Stack Usage Analysis::
20072 @end menu
20073
20074 @node Stack Overflow Checking
20075 @section Stack Overflow Checking
20076 @cindex Stack Overflow Checking
20077 @cindex -fstack-check
20078
20079 @noindent
20080 For most operating systems, @command{gcc} does not perform stack overflow
20081 checking by default. This means that if the main environment task or
20082 some other task exceeds the available stack space, then unpredictable
20083 behavior will occur. Most native systems offer some level of protection by
20084 adding a guard page at the end of each task stack. This mechanism is usually
20085 not enough for dealing properly with stack overflow situations because
20086 a large local variable could ``jump'' above the guard page.
20087 Furthermore, when the
20088 guard page is hit, there may not be any space left on the stack for executing
20089 the exception propagation code. Enabling stack checking avoids
20090 such situations.
20091
20092 To activate stack checking, compile all units with the gcc option
20093 @option{-fstack-check}. For example:
20094
20095 @smallexample
20096 gcc -c -fstack-check package1.adb
20097 @end smallexample
20098
20099 @noindent
20100 Units compiled with this option will generate extra instructions to check
20101 that any use of the stack (for procedure calls or for declaring local
20102 variables in declare blocks) does not exceed the available stack space.
20103 If the space is exceeded, then a @code{Storage_Error} exception is raised.
20104
20105 For declared tasks, the stack size is controlled by the size
20106 given in an applicable @code{Storage_Size} pragma or by the value specified
20107 at bind time with @option{-d} (@pxref{Switches for gnatbind}) or is set to
20108 the default size as defined in the GNAT runtime otherwise.
20109
20110 For the environment task, the stack size depends on
20111 system defaults and is unknown to the compiler. Stack checking
20112 may still work correctly if a fixed
20113 size stack is allocated, but this cannot be guaranteed.
20114 @ifclear vms
20115 To ensure that a clean exception is signalled for stack
20116 overflow, set the environment variable
20117 @env{GNAT_STACK_LIMIT} to indicate the maximum
20118 stack area that can be used, as in:
20119 @cindex GNAT_STACK_LIMIT
20120
20121 @smallexample
20122 SET GNAT_STACK_LIMIT 1600
20123 @end smallexample
20124
20125 @noindent
20126 The limit is given in kilobytes, so the above declaration would
20127 set the stack limit of the environment task to 1.6 megabytes.
20128 Note that the only purpose of this usage is to limit the amount
20129 of stack used by the environment task. If it is necessary to
20130 increase the amount of stack for the environment task, then this
20131 is an operating systems issue, and must be addressed with the
20132 appropriate operating systems commands.
20133 @end ifclear
20134 @ifset vms
20135 To have a fixed size stack in the environment task, the stack must be put
20136 in the P0 address space and its size specified.  Use these switches to
20137 create a p0 image:
20138
20139 @smallexample
20140 gnatmake my_progs -largs "-Wl,--opt=STACK=4000,/p0image"
20141 @end smallexample
20142
20143 @noindent
20144 The quotes are required to keep case.  The number after @samp{STACK=} is the
20145 size of the environmental task stack in pagelets (512 bytes).  In this example
20146 the stack size is about 2 megabytes.
20147
20148 @noindent
20149 A consequence of the @option{/p0image} qualifier is also to makes RMS buffers
20150 be placed in P0 space.  Refer to @cite{HP OpenVMS Linker Utility Manual} for
20151 more details about the @option{/p0image} qualifier and the @option{stack}
20152 option.
20153 @end ifset
20154
20155 @node Static Stack Usage Analysis
20156 @section Static Stack Usage Analysis
20157 @cindex Static Stack Usage Analysis
20158 @cindex -fstack-usage
20159
20160 @noindent
20161 A unit compiled with @option{-fstack-usage} will generate an extra file
20162 that specifies
20163 the maximum amount of stack used, on a per-function basis.
20164 The file has the same
20165 basename as the target object file with a @file{.su} extension.
20166 Each line of this file is made up of three fields:
20167
20168 @itemize
20169 @item
20170 The name of the function.
20171 @item
20172 A number of bytes.
20173 @item
20174 One or more qualifiers: @code{static}, @code{dynamic}, @code{bounded}.
20175 @end itemize
20176
20177 The second field corresponds to the size of the known part of the function
20178 frame.
20179
20180 The qualifier @code{static} means that the function frame size
20181 is purely static.
20182 It usually means that all local variables have a static size.
20183 In this case, the second field is a reliable measure of the function stack
20184 utilization.
20185
20186 The qualifier @code{dynamic} means that the function frame size is not static.
20187 It happens mainly when some local variables have a dynamic size. When this
20188 qualifier appears alone, the second field is not a reliable measure
20189 of the function stack analysis. When it is qualified with  @code{bounded}, it
20190 means that the second field is a reliable maximum of the function stack
20191 utilization.
20192
20193 @node Dynamic Stack Usage Analysis
20194 @section Dynamic Stack Usage Analysis
20195
20196 @noindent
20197 It is possible to measure the maximum amount of stack used by a task, by
20198 adding a switch to @command{gnatbind}, as:
20199
20200 @smallexample
20201 $ gnatbind -u0 file
20202 @end smallexample
20203
20204 @noindent
20205 With this option, at each task termination, its stack usage is  output on
20206 @file{stderr}.
20207 It is not always convenient to output the stack usage when the program
20208 is still running. Hence, it is possible to delay this output until program
20209 termination. for a given number of tasks specified as the argument of the
20210 @option{-u} option. For instance:
20211
20212 @smallexample
20213 $ gnatbind -u100 file
20214 @end smallexample
20215
20216 @noindent
20217 will buffer the stack usage information of the first 100 tasks to terminate and
20218 output this info at program termination. Results are displayed in four
20219 columns:
20220
20221 @noindent
20222 Index | Task Name | Stack Size | Actual Use [min - max]
20223
20224 @noindent
20225 where:
20226
20227 @table @emph
20228 @item Index
20229 is a number associated with each task.
20230
20231 @item Task Name
20232 is the name of the task analyzed.
20233
20234 @item Stack Size
20235 is the maximum size for the stack.
20236
20237 @item Actual Use
20238 is the measure done by the stack analyzer. In order to prevent overflow,
20239 the stack is not entirely analyzed, and it's not possible to know exactly how
20240 much has actually been used. The real amount of stack used is between the min
20241 and max values.
20242
20243 @end table
20244
20245 @noindent
20246 The environment task stack, e.g., the stack that contains the main unit, is
20247 only processed when the environment variable GNAT_STACK_LIMIT is set.
20248
20249
20250 @c *********************************
20251 @c *            GNATCHECK          *
20252 @c *********************************
20253 @node Verifying Properties Using gnatcheck
20254 @chapter Verifying Properties Using @command{gnatcheck}
20255 @findex gnatcheck
20256 @cindex @command{gnatcheck}
20257
20258 @noindent
20259 The @command{gnatcheck} tool is an ASIS-based utility that checks properties
20260 of Ada source files according to a given set of semantic rules.
20261 @cindex ASIS
20262
20263 In order to check compliance with a given rule, @command{gnatcheck} has to
20264 semantically analyze the Ada sources.
20265 Therefore, checks can only be performed on
20266 legal Ada units. Moreover, when a unit depends semantically upon units located
20267 outside the current directory, the source search path has to be provided when
20268 calling @command{gnatcheck}, either through a specified project file or
20269 through @command{gnatcheck} switches as described below.
20270
20271 A number of rules are predefined in @command{gnatcheck} and are described
20272 later in this chapter.
20273 You can also add new rules, by modifying the @command{gnatcheck} code and
20274 rebuilding the tool. In order to add a simple rule making some local checks,
20275 a small amount of straightforward ASIS-based programming is usually needed.
20276
20277 Project support for @command{gnatcheck} is provided by the GNAT
20278 driver (see @ref{The GNAT Driver and Project Files}).
20279
20280 Invoking @command{gnatcheck} on the command line has the form:
20281
20282 @smallexample
20283 $ gnatcheck @ovar{switches}  @{@var{filename}@}
20284       @r{[}^-files^/FILES^=@{@var{arg_list_filename}@}@r{]}
20285       @r{[}-cargs @var{gcc_switches}@r{]} @r{[}-rules @var{rule_options}@r{]}
20286 @end smallexample
20287
20288 @noindent
20289 where
20290 @itemize @bullet
20291 @item
20292 @var{switches} specify the general tool options
20293
20294 @item
20295 Each @var{filename} is the name (including the extension) of a source
20296 file to process. ``Wildcards'' are allowed, and
20297 the file name may contain path information.
20298
20299 @item
20300 Each @var{arg_list_filename} is the name (including the extension) of a text
20301 file containing the names of the source files to process, separated by spaces
20302 or line breaks.
20303
20304 @item
20305 @var{gcc_switches} is a list of switches for
20306 @command{gcc}. They will be passed on to all compiler invocations made by
20307 @command{gnatcheck} to generate the ASIS trees. Here you can provide
20308 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
20309 and use the @option{-gnatec} switch to set the configuration file.
20310
20311 @item
20312 @var{rule_options} is a list of options for controlling a set of
20313 rules to be checked by @command{gnatcheck} (@pxref{gnatcheck Rule Options}).
20314 @end itemize
20315
20316 @noindent
20317 Either a @file{@var{filename}} or an @file{@var{arg_list_filename}} must be supplied.
20318
20319 @menu
20320 * Format of the Report File::
20321 * General gnatcheck Switches::
20322 * gnatcheck Rule Options::
20323 * Adding the Results of Compiler Checks to gnatcheck Output::
20324 * Project-Wide Checks::
20325 * Predefined Rules::
20326 @end menu
20327
20328 @node Format of the Report File
20329 @section Format of the Report File
20330 @cindex Report file (for @code{gnatcheck})
20331
20332 @noindent
20333 The @command{gnatcheck} tool outputs on @file{stdout} all messages concerning
20334 rule violations.
20335 It also creates, in the current
20336 directory, a text file named @file{^gnatcheck.out^GNATCHECK.OUT^} that
20337 contains the complete report of the last gnatcheck run. This report contains:
20338 @itemize @bullet
20339 @item a list of the Ada source files being checked,
20340 @item a list of enabled and disabled rules,
20341 @item a list of the diagnostic messages, ordered in three different ways
20342 and collected in three separate
20343 sections. Section 1 contains the raw list of diagnostic messages. It
20344 corresponds to the output going to @file{stdout}. Section 2 contains
20345 messages ordered by rules.
20346 Section 3 contains messages ordered by source files.
20347 @end itemize
20348
20349 @node General gnatcheck Switches
20350 @section General @command{gnatcheck} Switches
20351
20352 @noindent
20353 The following switches control the general @command{gnatcheck} behavior
20354
20355 @table @option
20356 @c !sort!
20357 @cindex @option{^-a^/ALL^} (@command{gnatcheck})
20358 @item ^-a^/ALL^
20359 Process all units including those with read-only ALI files such as
20360 those from GNAT Run-Time library.
20361
20362 @ifclear vms
20363 @ignore
20364 @cindex @option{-d} (@command{gnatcheck})
20365 @item -d
20366 Debug mode
20367 @end ignore
20368
20369 @cindex @option{-dd} (@command{gnatcheck})
20370 @item -dd
20371 Progress indicator mode (for use in GPS)
20372 @end ifclear
20373
20374 @cindex @option{^-h^/HELP^} (@command{gnatcheck})
20375 @item ^-h^/HELP^
20376 List the predefined and user-defined rules. For more details see
20377 @ref{Predefined Rules}.
20378
20379 @cindex @option{^-l^/LOCS^} (@command{gnatcheck})
20380 @item ^-l^/LOCS^
20381 Use full source locations references in the report file. For a construct from
20382 a generic instantiation a full source location is a chain from the location
20383 of this construct in the generic unit to the place where this unit is
20384 instantiated.
20385
20386 @cindex @option{^-m^/DIAGNOSTIC_LIMIT^} (@command{gnatcheck})
20387 @item ^-m@i{nnn}^/DIAGNOSTIC_LIMIT=@i{nnn}^
20388 Maximum number of diagnoses to be sent to Stdout, @i{nnn} from o@dots{}1000,
20389 the default value is 500. Zero means that there is no limitation on
20390 the number of diagnostic messages to be printed into Stdout.
20391
20392 @cindex @option{^-q^/QUIET^} (@command{gnatcheck})
20393 @item ^-q^/QUIET^
20394 Quiet mode. All the diagnoses about rule violations are placed in the
20395 @command{gnatcheck} report file only, without duplicating in @file{stdout}.
20396
20397 @cindex @option{^-s^/SHORT^} (@command{gnatcheck})
20398 @item ^-s^/SHORT^
20399 Short format of the report file (no version information, no list of applied
20400 rules, no list of checked sources is included)
20401
20402 @cindex @option{^-s1^/COMPILER_STYLE^} (@command{gnatcheck})
20403 @item ^-s1^/COMPILER_STYLE^
20404 Include the compiler-style section in the report file
20405
20406 @cindex @option{^-s2^/BY_RULES^} (@command{gnatcheck})
20407 @item ^-s2^/BY_RULES^
20408 Include the section containing diagnoses ordered by rules in the report file
20409
20410 @cindex @option{^-s3^/BY_FILES_BY_RULES^} (@command{gnatcheck})
20411 @item ^-s3^/BY_FILES_BY_RULES^
20412 Include the section containing diagnoses ordered by files and then by rules
20413 in the report file
20414
20415 @cindex @option{^-v^/VERBOSE^} (@command{gnatcheck})
20416 @item ^-v^/VERBOSE^
20417 Verbose mode; @command{gnatcheck} generates version information and then
20418 a trace of sources being processed.
20419
20420 @end table
20421
20422 @noindent
20423 Note that if any of the options @option{^-s1^/COMPILER_STYLE^},
20424 @option{^-s2^/BY_RULES^} or
20425 @option{^-s3^/BY_FILES_BY_RULES^} is specified,
20426 then the  @command{gnatcheck} report file will only contain sections
20427 explicitly denoted by these options.
20428
20429 @node gnatcheck Rule Options
20430 @section @command{gnatcheck} Rule Options
20431
20432 @noindent
20433 The following options control the processing performed by
20434 @command{gnatcheck}.
20435
20436 @table @option
20437 @cindex @option{+ALL} (@command{gnatcheck})
20438 @item +ALL
20439 Turn all the rule checks ON.
20440
20441 @cindex @option{-ALL} (@command{gnatcheck})
20442 @item -ALL
20443 Turn all the rule checks OFF.
20444
20445 @cindex @option{+R} (@command{gnatcheck})
20446 @item +R@var{rule_id}@r{[}:@var{param}@r{]}
20447 Turn on the check for a specified rule with the specified parameter, if any.
20448 @var{rule_id} must be the identifier of one of the currently implemented rules
20449 (use @option{^-h^/HELP^} for the list of implemented rules). Rule identifiers
20450 are not case-sensitive. The @var{param} item must
20451 be a string representing a valid parameter(s) for the specified rule.
20452 If it contains any space characters then this string must be enclosed in
20453 quotation marks.
20454
20455 @cindex @option{-R} (@command{gnatcheck})
20456 @item -R@var{rule_id}@r{[}:@var{param}@r{]}
20457 Turn off the check for a specified rule with the specified parameter, if any.
20458
20459 @cindex @option{-from} (@command{gnatcheck})
20460 @item -from=@var{rule_option_filename}
20461 Read the rule options from the text file @var{rule_option_filename}, referred as
20462 ``rule file'' below.
20463
20464 @end table
20465
20466 @noindent
20467 The default behavior is that all the rule checks are disabled.
20468
20469 A rule file is a text file containing a set of rule options.
20470 @cindex Rule file (for @code{gnatcheck})
20471 The file may contain empty lines and Ada-style comments (comment
20472 lines and end-of-line comments). The rule file has free format; that is,
20473 you do not have to start a new rule option on a new line.
20474
20475 A rule file may contain other @option{-from=@var{rule_option_filename}}
20476 options, each such option being replaced with the content of the
20477 corresponding rule file during the rule files processing. In case a
20478 cycle is detected (that is, @file{@var{rule_file_1}} reads rule options
20479 from @file{@var{rule_file_2}}, and @file{@var{rule_file_2}} reads
20480 (directly or indirectly) rule options from @file{@var{rule_file_1}}),
20481 the processing of rule files is interrupted and a part of their content
20482 is ignored.
20483
20484
20485 @node Adding the Results of Compiler Checks to gnatcheck Output
20486 @section Adding the Results of Compiler Checks to @command{gnatcheck} Output
20487
20488 @noindent
20489 The @command{gnatcheck} tool can include in the generated diagnostic messages
20490 and in
20491 the report file the results of the checks performed by the compiler. Though
20492 disabled by default, this effect may be obtained by using @option{+R} with
20493 the following rule identifiers and parameters:
20494
20495 @table @option
20496 @item Restrictions
20497 To record restrictions violations (that are performed by the compiler if the
20498 pragma @code{Restrictions} or @code{Restriction_Warnings} are given),
20499 use the rule named
20500 @code{Restrictions} with the same parameters as pragma
20501 @code{Restrictions} or @code{Restriction_Warnings}.
20502
20503 @item Style_Checks
20504 To record compiler style checks(@pxref{Style Checking}), use the rule named
20505 @code{Style_Checks}. A parameter of this rule can be either @code{All_Checks},
20506 which enables all the standard style checks that corresponds to @option{-gnatyy}
20507 GNAT style check option, or a string that has exactly the same
20508 structure and semantics as the @code{string_LITERAL} parameter of GNAT pragma
20509 @code{Style_Checks} (for further information about this pragma,
20510 @pxref{Pragma Style_Checks,,, gnat_rm, GNAT Reference Manual}).
20511
20512 @item Warnings
20513 To record compiler warnings (@pxref{Warning Message Control}), use the rule
20514 named @code{Warnings} with a parameter that is a valid
20515 @i{static_string_expression} argument of GNAT pragma @code{Warnings}
20516 (for further information about this pragma, @pxref{Pragma Warnings,,,
20517 gnat_rm, GNAT Reference Manual}). Note, that in case of gnatcheck
20518 's' parameter, that corresponds to the GNAT @option{-gnatws} option, disables
20519 all the specific warnings, but not suppresses the warning mode,
20520 and 'e' parameter, corresponding to @option{-gnatwe} that means
20521 "treat warnings as errors", does not have any effect.
20522
20523 @end table
20524
20525 To disable a specific restriction check, use @code{-RStyle_Checks} gnatcheck
20526 option with the corresponding restriction name as a parameter. @code{-R} is
20527 not available for @code{Style_Checks} and @code{Warnings} options, to disable
20528 warnings and style checks, use the corresponding warning and style options.
20529
20530 @node Project-Wide Checks
20531 @section Project-Wide Checks
20532 @cindex Project-wide checks (for @command{gnatcheck})
20533
20534 @noindent
20535 In order to perform checks on all units of a given project, you can use
20536 the GNAT driver along with the @option{-P} option:
20537 @smallexample
20538    gnat check -Pproj -rules -from=my_rules
20539 @end smallexample
20540
20541 @noindent
20542 If the project @code{proj} depends upon other projects, you can perform
20543 checks on the project closure using the @option{-U} option:
20544 @smallexample
20545    gnat check -Pproj -U -rules -from=my_rules
20546 @end smallexample
20547
20548 @noindent
20549 Finally, if not all the units are relevant to a particular main
20550 program in the project closure, you can perform checks for the set
20551 of units needed to create a given main program (unit closure) using
20552 the @option{-U} option followed by the name of the main unit:
20553 @smallexample
20554    gnat check -Pproj -U main -rules -from=my_rules
20555 @end smallexample
20556
20557
20558 @node Predefined Rules
20559 @section Predefined Rules
20560 @cindex Predefined rules (for @command{gnatcheck})
20561
20562 @ignore
20563 @c (Jan 2007) Since the global rules are still under development and are not
20564 @c documented, there is no point in explaining the difference between
20565 @c global and local rules
20566 @noindent
20567 A rule in @command{gnatcheck} is either local or global.
20568 A @emph{local rule} is a rule that applies to a well-defined section
20569 of a program and that can be checked by analyzing only this section.
20570 A @emph{global rule} requires analysis of some global properties of the
20571 whole program (mostly related to the program call graph).
20572 As of @value{NOW}, the implementation of global rules should be
20573 considered to be at a preliminary stage. You can use the
20574 @option{+GLOBAL} option to enable all the global rules, and the
20575 @option{-GLOBAL} rule option to disable all the global rules.
20576
20577 All the global rules in the list below are
20578 so indicated by marking them ``GLOBAL''.
20579 This +GLOBAL and -GLOBAL options are not
20580 included in the list of gnatcheck options above, because at the moment they
20581 are considered as a temporary debug options.
20582
20583 @command{gnatcheck} performs rule checks for generic
20584 instances only for global rules.  This limitation may be relaxed in a later
20585 release.
20586 @end ignore
20587
20588 @noindent
20589 The following subsections document the rules implemented in
20590 @command{gnatcheck}.
20591 The subsection title is the same as the rule identifier, which may be
20592 used as a parameter of the @option{+R} or @option{-R} options.
20593
20594
20595 @menu
20596 * Abstract_Type_Declarations::
20597 * Anonymous_Arrays::
20598 * Anonymous_Subtypes::
20599 * Blocks::
20600 * Boolean_Relational_Operators::
20601 @ignore
20602 * Ceiling_Violations::
20603 @end ignore
20604 * Controlled_Type_Declarations::
20605 * Declarations_In_Blocks::
20606 * Default_Parameters::
20607 * Discriminated_Records::
20608 * Enumeration_Ranges_In_CASE_Statements::
20609 * Exceptions_As_Control_Flow::
20610 * EXIT_Statements_With_No_Loop_Name::
20611 * Expanded_Loop_Exit_Names::
20612 * Explicit_Full_Discrete_Ranges::
20613 * Float_Equality_Checks::
20614 * Forbidden_Pragmas::
20615 * Function_Style_Procedures::
20616 * Generics_In_Subprograms::
20617 * GOTO_Statements::
20618 * Implicit_IN_Mode_Parameters::
20619 * Implicit_SMALL_For_Fixed_Point_Types::
20620 * Improperly_Located_Instantiations::
20621 * Improper_Returns::
20622 * Library_Level_Subprograms::
20623 * Local_Packages::
20624 @ignore
20625 * Improperly_Called_Protected_Entries::
20626 @end ignore
20627 * Metrics::
20628 * Misnamed_Identifiers::
20629 * Multiple_Entries_In_Protected_Definitions::
20630 * Name_Clashes::
20631 * Non_Qualified_Aggregates::
20632 * Non_Short_Circuit_Operators::
20633 * Non_SPARK_Attributes::
20634 * Non_Tagged_Derived_Types::
20635 * Non_Visible_Exceptions::
20636 * Numeric_Literals::
20637 * OTHERS_In_Aggregates::
20638 * OTHERS_In_CASE_Statements::
20639 * OTHERS_In_Exception_Handlers::
20640 * Outer_Loop_Exits::
20641 * Overloaded_Operators::
20642 * Overly_Nested_Control_Structures::
20643 * Parameters_Out_Of_Order::
20644 * Positional_Actuals_For_Defaulted_Generic_Parameters::
20645 * Positional_Actuals_For_Defaulted_Parameters::
20646 * Positional_Components::
20647 * Positional_Generic_Parameters::
20648 * Positional_Parameters::
20649 * Predefined_Numeric_Types::
20650 * Raising_External_Exceptions::
20651 * Raising_Predefined_Exceptions::
20652 * Separate_Numeric_Error_Handlers::
20653 @ignore
20654 * Recursion::
20655 * Side_Effect_Functions::
20656 @end ignore
20657 * Slices::
20658 * Unassigned_OUT_Parameters::
20659 * Uncommented_BEGIN_In_Package_Bodies::
20660 * Unconstrained_Array_Returns::
20661 * Universal_Ranges::
20662 * Unnamed_Blocks_And_Loops::
20663 @ignore
20664 * Unused_Subprograms::
20665 @end ignore
20666 * USE_PACKAGE_Clauses::
20667 * Volatile_Objects_Without_Address_Clauses::
20668 @end menu
20669
20670
20671 @node Abstract_Type_Declarations
20672 @subsection @code{Abstract_Type_Declarations}
20673 @cindex @code{Abstract_Type_Declarations} rule (for @command{gnatcheck})
20674
20675 @noindent
20676 Flag all declarations of abstract types. For an abstract private
20677 type, both the private and full type declarations are flagged.
20678
20679 This rule has no parameters.
20680
20681
20682 @node Anonymous_Arrays
20683 @subsection @code{Anonymous_Arrays}
20684 @cindex @code{Anonymous_Arrays} rule (for @command{gnatcheck})
20685
20686 @noindent
20687 Flag all anonymous array type definitions (by Ada semantics these can only
20688 occur in object declarations).
20689
20690 This rule has no parameters.
20691
20692 @node Anonymous_Subtypes
20693 @subsection @code{Anonymous_Subtypes}
20694 @cindex @code{Anonymous_Subtypes} rule (for @command{gnatcheck})
20695
20696 @noindent
20697 Flag all uses of anonymous subtypes. A use of an anonymous subtype is
20698 any instance of a subtype indication with a constraint, other than one
20699 that occurs immediately within a subtype declaration. Any use of a range
20700 other than as a constraint used immediately within a subtype declaration
20701 is considered as an anonymous subtype.
20702
20703 An effect of this rule is that @code{for} loops such as the following are
20704 flagged (since @code{1..N} is formally a ``range''):
20705
20706 @smallexample @c ada
20707 for I in 1 .. N loop
20708    @dots{}
20709 end loop;
20710 @end smallexample
20711
20712 @noindent
20713 Declaring an explicit subtype solves the problem:
20714
20715 @smallexample @c ada
20716 subtype S is Integer range 1..N;
20717 @dots{}
20718 for I in S loop
20719    @dots{}
20720 end loop;
20721 @end smallexample
20722
20723 @noindent
20724 This rule has no parameters.
20725
20726 @node Blocks
20727 @subsection @code{Blocks}
20728 @cindex @code{Blocks} rule (for @command{gnatcheck})
20729
20730 @noindent
20731 Flag each block statement.
20732
20733 This rule has no parameters.
20734
20735 @node Boolean_Relational_Operators
20736 @subsection @code{Boolean_Relational_Operators}
20737 @cindex @code{Boolean_Relational_Operators} rule (for @command{gnatcheck})
20738
20739 @noindent
20740 Flag each call to a predefined relational operator (``<'', ``>'', ``<='',
20741 ``>='', ``='' and ``/='') for the predefined Boolean type.
20742 (This rule is useful in enforcing the SPARK language restrictions.)
20743
20744 Calls to predefined relational operators of any type derived from
20745 @code{Standard.Boolean} are not detected.  Calls to user-defined functions
20746 with these designators, and uses of operators that are renamings
20747 of the predefined relational operators for @code{Standard.Boolean},
20748 are likewise not detected.
20749
20750 This rule has no parameters.
20751
20752 @ignore
20753 @node Ceiling_Violations
20754 @subsection @code{Ceiling_Violations} (under construction, GLOBAL)
20755 @cindex @code{Ceiling_Violations} rule (for @command{gnatcheck})
20756
20757 @noindent
20758 Flag invocations of a protected operation by a task whose priority exceeds
20759 the protected object's ceiling.
20760
20761 As of @value{NOW}, this rule has the following limitations:
20762
20763 @itemize @bullet
20764
20765 @item
20766  We consider only pragmas Priority and Interrupt_Priority as means to define
20767   a task/protected operation priority. We do not consider the effect of using
20768   Ada.Dynamic_Priorities.Set_Priority procedure;
20769
20770 @item
20771  We consider only base task priorities, and no priority inheritance. That is,
20772   we do not make a difference between calls issued during task activation and
20773   execution of the sequence of statements from task body;
20774
20775 @item
20776  Any situation when the priority of protected operation caller is set by a
20777   dynamic expression (that is, the corresponding Priority or
20778   Interrupt_Priority pragma has a non-static expression as an argument) we
20779   treat as a priority inconsistency (and, therefore, detect this situation).
20780 @end itemize
20781
20782 @noindent
20783 At the moment the notion of the main subprogram is not implemented in
20784 gnatcheck, so any pragma Priority in a library level subprogram body (in case
20785 if this subprogram can be a main subprogram of a partition) changes the
20786 priority of an environment task. So if we have more then one such pragma in
20787 the set of processed sources, the pragma that is processed last, defines the
20788 priority of an environment task.
20789
20790 This rule has no parameters.
20791 @end ignore
20792
20793 @node Controlled_Type_Declarations
20794 @subsection @code{Controlled_Type_Declarations}
20795 @cindex @code{Controlled_Type_Declarations} rule (for @command{gnatcheck})
20796
20797 @noindent
20798 Flag all declarations of controlled types. A declaration of a private type
20799 is flagged if its full declaration declares a controlled type. A declaration
20800 of a derived type is flagged if its ancestor type is controlled. Subtype
20801 declarations are not checked. A declaration of a type that itself is not a
20802 descendant of a type declared in @code{Ada.Finalization} but has a controlled
20803 component is not checked.
20804
20805 This rule has no parameters.
20806
20807
20808
20809 @node Declarations_In_Blocks
20810 @subsection @code{Declarations_In_Blocks}
20811 @cindex @code{Declarations_In_Blocks} rule (for @command{gnatcheck})
20812
20813 @noindent
20814 Flag all block statements containing local declarations. A @code{declare}
20815 block with an empty @i{declarative_part} or with a @i{declarative part}
20816 containing only pragmas and/or @code{use} clauses is not flagged.
20817
20818 This rule has no parameters.
20819
20820
20821 @node Default_Parameters
20822 @subsection @code{Default_Parameters}
20823 @cindex @code{Default_Parameters} rule (for @command{gnatcheck})
20824
20825 @noindent
20826 Flag all default expressions for subprogram parameters. Parameter
20827 declarations of formal and generic subprograms are also checked.
20828
20829 This rule has no parameters.
20830
20831
20832 @node Discriminated_Records
20833 @subsection @code{Discriminated_Records}
20834 @cindex @code{Discriminated_Records} rule (for @command{gnatcheck})
20835
20836 @noindent
20837 Flag all declarations of record types with discriminants. Only the
20838 declarations of record and record extension types are checked. Incomplete,
20839 formal, private, derived and private extension type declarations are not
20840 checked. Task and protected type declarations also are not checked.
20841
20842 This rule has no parameters.
20843
20844
20845 @node Enumeration_Ranges_In_CASE_Statements
20846 @subsection @code{Enumeration_Ranges_In_CASE_Statements}
20847 @cindex @code{Enumeration_Ranges_In_CASE_Statements} (for @command{gnatcheck})
20848
20849 @noindent
20850 Flag each use of a range of enumeration literals as a choice in a
20851 @code{case} statement.
20852 All forms for specifying a range (explicit ranges
20853 such as @code{A .. B}, subtype marks and @code{'Range} attributes) are flagged.
20854 An enumeration range is
20855 flagged even if contains exactly one enumeration value or no values at all. A
20856 type derived from an enumeration type is considered as an enumeration type.
20857
20858 This rule helps prevent maintenance problems arising from adding an
20859 enumeration value to a type and having it implicitly handled by an existing
20860 @code{case} statement with an enumeration range that includes the new literal.
20861
20862 This rule has no parameters.
20863
20864
20865 @node Exceptions_As_Control_Flow
20866 @subsection @code{Exceptions_As_Control_Flow}
20867 @cindex @code{Exceptions_As_Control_Flow} (for @command{gnatcheck})
20868
20869 @noindent
20870 Flag each place where an exception is explicitly raised and handled in the
20871 same subprogram body. A @code{raise} statement in an exception handler,
20872 package body, task body or entry body is not flagged.
20873
20874 The rule has no parameters.
20875
20876 @node EXIT_Statements_With_No_Loop_Name
20877 @subsection @code{EXIT_Statements_With_No_Loop_Name}
20878 @cindex @code{EXIT_Statements_With_No_Loop_Name} (for @command{gnatcheck})
20879
20880 @noindent
20881 Flag each @code{exit} statement that does not specify the name of the loop
20882 being exited.
20883
20884 The rule has no parameters.
20885
20886
20887 @node Expanded_Loop_Exit_Names
20888 @subsection @code{Expanded_Loop_Exit_Names}
20889 @cindex @code{Expanded_Loop_Exit_Names} rule (for @command{gnatcheck})
20890
20891 @noindent
20892 Flag all expanded loop names in @code{exit} statements.
20893
20894 This rule has no parameters.
20895
20896 @node Explicit_Full_Discrete_Ranges
20897 @subsection @code{Explicit_Full_Discrete_Ranges}
20898 @cindex @code{Explicit_Full_Discrete_Ranges} rule (for @command{gnatcheck})
20899
20900 @noindent
20901 Flag each discrete range that has the form @code{A'First .. A'Last}.
20902
20903 This rule has no parameters.
20904
20905 @node Float_Equality_Checks
20906 @subsection @code{Float_Equality_Checks}
20907 @cindex @code{Float_Equality_Checks} rule (for @command{gnatcheck})
20908
20909 @noindent
20910 Flag all calls to the predefined equality operations for floating-point types.
20911 Both ``@code{=}'' and ``@code{/=}'' operations are checked.
20912 User-defined equality operations are not flagged, nor are ``@code{=}''
20913 and ``@code{/=}'' operations for fixed-point types.
20914
20915 This rule has no parameters.
20916
20917
20918 @node Forbidden_Pragmas
20919 @subsection @code{Forbidden_Pragmas}
20920 @cindex @code{Forbidden_Pragmas} rule (for @command{gnatcheck})
20921
20922 @noindent
20923 Flag each use of the specified pragmas.  The pragmas to be detected
20924 are named in the rule's  parameters.
20925
20926 This rule has the following parameters:
20927
20928 @itemize @bullet
20929 @item For the @option{+R} option
20930
20931 @table @asis
20932 @item @emph{Pragma_Name}
20933 Adds the specified pragma to the set of pragmas to be
20934 checked and sets the checks for all the specified pragmas
20935 ON. @emph{Pragma_Name} is treated as a name of a pragma. If it
20936 does not correspond to any pragma name defined in the Ada
20937 standard or to the name of a GNAT-specific pragma defined
20938 in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference
20939 Manual}, it is treated as the name of unknown pragma.
20940
20941 @item @code{GNAT}
20942 All the GNAT-specific pragmas are detected; this sets
20943 the checks for all the specified pragmas ON.
20944
20945 @item @code{ALL}
20946 All pragmas are detected; this sets the rule ON.
20947 @end table
20948
20949 @item For the @option{-R} option
20950 @table @asis
20951 @item @emph{Pragma_Name}
20952 Removes the specified pragma from the set of pragmas to be
20953 checked without affecting checks for
20954 other pragmas. @emph{Pragma_Name} is treated as a name
20955 of a pragma. If it does not correspond to any pragma
20956 defined in the Ada standard or to any name defined in
20957 @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
20958 this option is treated as turning OFF detection of all unknown pragmas.
20959
20960 @item GNAT
20961 Turn OFF detection of all GNAT-specific pragmas
20962
20963 @item ALL
20964 Clear the list of the pragmas to be detected and
20965 turn the rule OFF.
20966 @end table
20967 @end itemize
20968
20969 @noindent
20970 Parameters are not case sensitive. If @emph{Pragma_Name} does not have
20971 the syntax of an Ada identifier and therefore can not be considered
20972 as a pragma name, a diagnostic message is generated and the corresponding
20973 parameter is ignored.
20974
20975 When more then one parameter is given in the same rule option, the parameters
20976 must be separated by a comma.
20977
20978 If more then one option for this rule is specified for the @command{gnatcheck}
20979 call, a new option overrides the previous one(s).
20980
20981 The @option{+R} option with no parameters turns the rule ON with the set of
20982 pragmas to be detected defined by the previous rule options.
20983 (By default this set is empty, so if the only option specified for the rule is
20984 @option{+RForbidden_Pragmas} (with
20985 no parameter), then the rule is enabled, but it does not detect anything).
20986 The @option{-R} option with no parameter turns the rule OFF, but it does not
20987 affect the set of pragmas to be detected.
20988
20989
20990
20991
20992 @node Function_Style_Procedures
20993 @subsection @code{Function_Style_Procedures}
20994 @cindex @code{Function_Style_Procedures} rule (for @command{gnatcheck})
20995
20996 @noindent
20997 Flag each procedure that can be rewritten as a function. A procedure can be
20998 converted into a function if it has exactly one parameter of mode @code{out}
20999 and no parameters of mode @code{in out}. Procedure declarations,
21000 formal procedure declarations, and generic procedure declarations are always
21001 checked. Procedure
21002 bodies and body stubs are flagged only if they do not have corresponding
21003 separate declarations. Procedure renamings and procedure instantiations are
21004 not flagged.
21005
21006 If a procedure can be rewritten as a function, but its @code{out} parameter is
21007 of a limited type, it is not flagged.
21008
21009 Protected procedures are not flagged. Null procedures also are not flagged.
21010
21011 This rule has no parameters.
21012
21013
21014 @node Generics_In_Subprograms
21015 @subsection @code{Generics_In_Subprograms}
21016 @cindex @code{Generics_In_Subprograms} rule (for @command{gnatcheck})
21017
21018 @noindent
21019 Flag each declaration of a generic unit in a subprogram. Generic
21020 declarations in the bodies of generic subprograms are also flagged.
21021 A generic unit nested in another generic unit is not flagged.
21022 If a generic unit is
21023 declared in a local package that is declared in a subprogram body, the
21024 generic unit is flagged.
21025
21026 This rule has no parameters.
21027
21028
21029 @node GOTO_Statements
21030 @subsection @code{GOTO_Statements}
21031 @cindex @code{GOTO_Statements} rule (for @command{gnatcheck})
21032
21033 @noindent
21034 Flag each occurrence of a @code{goto} statement.
21035
21036 This rule has no parameters.
21037
21038
21039 @node Implicit_IN_Mode_Parameters
21040 @subsection @code{Implicit_IN_Mode_Parameters}
21041 @cindex @code{Implicit_IN_Mode_Parameters} rule (for @command{gnatcheck})
21042
21043 @noindent
21044 Flag each occurrence of a formal parameter with an implicit @code{in} mode.
21045 Note that @code{access} parameters, although they technically behave
21046 like @code{in} parameters, are not flagged.
21047
21048 This rule has no parameters.
21049
21050
21051 @node Implicit_SMALL_For_Fixed_Point_Types
21052 @subsection @code{Implicit_SMALL_For_Fixed_Point_Types}
21053 @cindex @code{Implicit_SMALL_For_Fixed_Point_Types} rule (for @command{gnatcheck})
21054
21055 @noindent
21056 Flag each fixed point type declaration that lacks an explicit
21057 representation  clause to define its @code{'Small} value.
21058 Since @code{'Small} can be  defined only for ordinary fixed point types,
21059 decimal fixed point type declarations are not checked.
21060
21061 This rule has no parameters.
21062
21063
21064 @node Improperly_Located_Instantiations
21065 @subsection @code{Improperly_Located_Instantiations}
21066 @cindex @code{Improperly_Located_Instantiations} rule (for @command{gnatcheck})
21067
21068 @noindent
21069 Flag all generic instantiations in library-level package specs
21070 (including library generic packages) and in all subprogram bodies.
21071
21072 Instantiations in task and entry bodies are not flagged. Instantiations in the
21073 bodies of protected subprograms are flagged.
21074
21075 This rule has no parameters.
21076
21077
21078
21079 @node Improper_Returns
21080 @subsection @code{Improper_Returns}
21081 @cindex @code{Improper_Returns} rule (for @command{gnatcheck})
21082
21083 @noindent
21084 Flag each explicit @code{return} statement in procedures, and
21085 multiple @code{return} statements in functions.
21086 Diagnostic messages are generated for all @code{return} statements
21087 in a procedure (thus each procedure must be written so that it
21088 returns implicitly at the end of its statement part),
21089 and for all @code{return} statements in a function after the first one.
21090 This rule supports the stylistic convention that each subprogram
21091 should have no more than one point of normal return.
21092
21093 This rule has no parameters.
21094
21095
21096 @node Library_Level_Subprograms
21097 @subsection @code{Library_Level_Subprograms}
21098 @cindex @code{Library_Level_Subprograms} rule (for @command{gnatcheck})
21099
21100 @noindent
21101 Flag all library-level subprograms (including generic subprogram instantiations).
21102
21103 This rule has no parameters.
21104
21105
21106 @node Local_Packages
21107 @subsection @code{Local_Packages}
21108 @cindex @code{Local_Packages} rule (for @command{gnatcheck})
21109
21110 @noindent
21111 Flag all local packages declared in package and generic package
21112 specs.
21113 Local packages in bodies are not flagged.
21114
21115 This rule has no parameters.
21116
21117 @ignore
21118 @node Improperly_Called_Protected_Entries
21119 @subsection @code{Improperly_Called_Protected_Entries} (under construction, GLOBAL)
21120 @cindex @code{Improperly_Called_Protected_Entries} rule (for @command{gnatcheck})
21121
21122 @noindent
21123 Flag each protected entry that can be called from more than one task.
21124
21125 This rule has no parameters.
21126 @end ignore
21127
21128 @node Metrics
21129 @subsection @code{Metrics}
21130 @cindex @code{Metrics} rule (for @command{gnatcheck})
21131
21132 @noindent
21133 There is a set of checks based on computing a metric value and comparing the
21134 result with the specified upper (or lower, depending on a specific metric)
21135 value specified for a given metric. A construct is flagged if a given metric
21136 is applicable (can be computed) for it and the computed value is greater
21137 then (lover then) the specified upper (lower) bound.
21138
21139 The name of any metric-based rule consists of the prefix @code{Metrics_}
21140 followed by the name of the corresponding metric (see the table below).
21141 For @option{+R} option, each metric-based rule has a numeric parameter
21142 specifying the bound (integer or real, depending on a metric), @option{-R}
21143 option for metric rules does not have a parameter.
21144
21145 The following table shows the metric names for that the corresponding
21146 metrics-based checks are supported by gnatcheck, including the
21147 constraint that must be satisfied by the bound that is specified for the check
21148 and what bound - upper (U) or lower (L) - should be specified.
21149
21150 @multitable {@code{Cyclomatic_Complexity}}{Cyclomatic complexity}{Positive integer}
21151 @ifnothtml
21152 @headitem Check Name @tab Description @tab Bounds Value
21153 @end ifnothtml
21154 @ifhtml
21155 @item @b{Check Name} @tab @b{Description} @tab @b{Bounds Value}
21156 @end ifhtml
21157 @c Above conditional code is workaround to bug in texi2html (Feb 2008)
21158 @item @code{Essential_Complexity} @tab Essential complexity @tab Positive integer (U)
21159 @item @code{Cyclomatic_Complexity} @tab Cyclomatic complexity @tab Positive integer (U)
21160 @item @code{LSLOC} @tab Logical Source Lines of Code @tab Positive integer (U)
21161 @end multitable
21162
21163 @noindent
21164 The meaning and the computed values for all these metrics are exactly
21165 the same as for the corresponding metrics in @command{gnatmetric}.
21166
21167 @emph{Example:} the rule
21168 @smallexample
21169 +RMetrics_Cyclomatic_Complexity : 7
21170 @end smallexample
21171 @noindent
21172 means that all bodies with cyclomatic complexity exceeding 7 will be flagged.
21173
21174 To turn OFF the check for cyclomatic complexity metric, use the following option:
21175 @smallexample
21176 -RMetrics_Cyclomatic_Complexity
21177 @end smallexample
21178
21179 @node Misnamed_Identifiers
21180 @subsection @code{Misnamed_Identifiers}
21181 @cindex @code{Misnamed_Identifiers} rule (for @command{gnatcheck})
21182
21183 @noindent
21184 Flag the declaration of each identifier that does not have a suffix
21185 corresponding to the kind of entity being declared.
21186 The following declarations are checked:
21187
21188 @itemize @bullet
21189 @item
21190 type declarations
21191
21192 @item
21193 constant declarations (but not number declarations)
21194
21195 @item
21196 package renaming declarations (but not generic package renaming
21197 declarations)
21198 @end itemize
21199
21200 @noindent
21201 This rule may have parameters. When used without parameters, the rule enforces
21202 the following checks:
21203
21204 @itemize @bullet
21205 @item
21206 type-defining names end with @code{_T}, unless the type is an access type,
21207 in which case the suffix must be @code{_A}
21208 @item
21209 constant names end with @code{_C}
21210 @item
21211 names defining package renamings end with @code{_R}
21212 @end itemize
21213
21214 @noindent
21215 For a private or incomplete type declaration the following checks are
21216 made for the defining name suffix:
21217
21218 @itemize @bullet
21219 @item
21220 For an incomplete type declaration: if the corresponding full type
21221 declaration is available, the defining identifier from the full type
21222 declaration is checked, but the defining identifier from the incomplete type
21223 declaration is not; otherwise the defining identifier from the incomplete
21224 type declaration is checked against the suffix specified for type
21225 declarations.
21226
21227 @item
21228 For a private type declaration (including private extensions),  the defining
21229 identifier from the private type declaration is checked against the type
21230 suffix (even if the corresponding full declaration is an access type
21231 declaration), and the defining identifier from the corresponding full type
21232 declaration is not checked.
21233 @end itemize
21234
21235 @noindent
21236 For a deferred constant, the defining name in the corresponding full constant
21237 declaration is not checked.
21238
21239 Defining names of formal types are not checked.
21240
21241 The rule may have the following parameters:
21242
21243 @itemize @bullet
21244 @item
21245 For the @option{+R} option:
21246 @table @code
21247 @item Default
21248 Sets the default listed above for all the names to be checked.
21249
21250 @item Type_Suffix=@emph{string}
21251 Specifies the suffix for a type name.
21252
21253 @item Access_Suffix=@emph{string}
21254 Specifies the suffix for an access type name. If
21255 this parameter is set, it overrides for access
21256 types the suffix set by the @code{Type_Suffix} parameter.
21257
21258 @item Constant_Suffix=@emph{string}
21259 Specifies the suffix for a constant name.
21260
21261 @item Renaming_Suffix=@emph{string}
21262 Specifies the suffix for a package renaming name.
21263 @end table
21264
21265 @item
21266 For the @option{-R} option:
21267 @table @code
21268 @item All_Suffixes
21269 Remove all the suffixes specified for the
21270 identifier suffix checks, whether by default or
21271 as specified by other rule parameters. All the
21272 checks for this rule are disabled as a result.
21273
21274 @item Type_Suffix
21275 Removes the suffix specified for types. This
21276 disables checks for types but does not disable
21277 any other checks for this rule (including the
21278 check for access type names if @code{Access_Suffix} is
21279 set).
21280
21281 @item Access_Suffix
21282 Removes the suffix specified for access types.
21283 This disables checks for access type names but
21284 does not disable any other checks for this rule.
21285 If @code{Type_Suffix} is set, access type names are
21286 checked as ordinary type names.
21287
21288 @item Constant_Suffix
21289 Removes the suffix specified for constants. This
21290 disables checks for constant names but does not
21291 disable any other checks for this rule.
21292
21293 @item Renaming_Suffix
21294 Removes the suffix specified for package
21295 renamings. This disables checks for package
21296 renamings but does not disable any other checks
21297 for this rule.
21298 @end table
21299 @end itemize
21300
21301 @noindent
21302 If more than one parameter is used, parameters must be separated by commas.
21303
21304 If more than one  option is specified for the @command{gnatcheck} invocation,
21305 a new option overrides the previous one(s).
21306
21307 The @option{+RMisnamed_Identifiers} option (with no parameter) enables
21308 checks for all the
21309 name suffixes specified by previous options used for this rule.
21310
21311 The @option{-RMisnamed_Identifiers} option (with no parameter) disables
21312 all the checks but keeps
21313 all the suffixes specified by previous options used for this rule.
21314
21315 The @emph{string} value must be a valid suffix for an Ada identifier (after
21316 trimming all the leading and trailing space characters, if any).
21317 Parameters are not case sensitive, except the @emph{string} part.
21318
21319 If any error is detected in a rule parameter, the parameter is ignored.
21320 In such a case the options that are set for the rule are not
21321 specified.
21322
21323
21324
21325 @node Multiple_Entries_In_Protected_Definitions
21326 @subsection @code{Multiple_Entries_In_Protected_Definitions}
21327 @cindex @code{Multiple_Entries_In_Protected_Definitions} rule (for @command{gnatcheck})
21328
21329 @noindent
21330 Flag each protected definition (i.e., each protected object/type declaration)
21331 that defines more than one entry.
21332 Diagnostic messages are generated for all the entry declarations
21333 except the first one. An entry family is counted as one entry. Entries from
21334 the private part of the protected definition are also checked.
21335
21336 This rule has no parameters.
21337
21338 @node Name_Clashes
21339 @subsection @code{Name_Clashes}
21340 @cindex @code{Name_Clashes} rule (for @command{gnatcheck})
21341
21342 @noindent
21343 Check that certain names are not used as defining identifiers. To activate
21344 this rule, you need to supply a reference to the dictionary file(s) as a rule
21345 parameter(s) (more then one dictionary file can be specified). If no
21346 dictionary file is set, this rule will not cause anything to be flagged.
21347 Only defining occurrences, not references, are checked.
21348 The check is not case-sensitive.
21349
21350 This rule is enabled by default, but without setting any corresponding
21351 dictionary file(s); thus the default effect is to do no checks.
21352
21353 A dictionary file is a plain text file. The maximum line length for this file
21354 is 1024 characters.  If the line is longer then this limit, extra characters
21355 are ignored.
21356
21357 Each line can be either an empty line, a comment line, or a line containing
21358 a list of identifiers separated by space or HT characters.
21359 A comment is an Ada-style comment (from @code{--} to end-of-line).
21360 Identifiers must follow the Ada syntax for identifiers.
21361 A line containing one or more identifiers may end with a comment.
21362
21363 @node Non_Qualified_Aggregates
21364 @subsection @code{Non_Qualified_Aggregates}
21365 @cindex @code{Non_Qualified_Aggregates} rule (for @command{gnatcheck})
21366
21367 @noindent
21368 Flag each non-qualified aggregate.
21369 A non-qualified aggregate is an
21370 aggregate that is not the expression of a qualified expression. A
21371 string literal is not considered an aggregate, but an array
21372 aggregate of a string type is considered as a normal aggregate.
21373 Aggregates of anonymous array types are not flagged.
21374
21375 This rule has no parameters.
21376
21377
21378 @node Non_Short_Circuit_Operators
21379 @subsection @code{Non_Short_Circuit_Operators}
21380 @cindex @code{Non_Short_Circuit_Operators} rule (for @command{gnatcheck})
21381
21382 @noindent
21383 Flag all calls to predefined @code{and} and @code{or} operators for
21384 any boolean type. Calls to
21385 user-defined @code{and} and @code{or} and to operators defined by renaming
21386 declarations are not flagged. Calls to predefined @code{and} and @code{or}
21387 operators for modular types or boolean array types are not flagged.
21388
21389 This rule has no parameters.
21390
21391
21392
21393 @node Non_SPARK_Attributes
21394 @subsection @code{Non_SPARK_Attributes}
21395 @cindex @code{Non_SPARK_Attributes} rule (for @command{gnatcheck})
21396
21397 @noindent
21398 The SPARK language defines the following subset of Ada 95 attribute
21399 designators as those that can be used in SPARK programs. The use of
21400 any other attribute is flagged.
21401
21402 @itemize @bullet
21403 @item @code{'Adjacent}
21404 @item @code{'Aft}
21405 @item @code{'Base}
21406 @item @code{'Ceiling}
21407 @item @code{'Component_Size}
21408 @item @code{'Compose}
21409 @item @code{'Copy_Sign}
21410 @item @code{'Delta}
21411 @item @code{'Denorm}
21412 @item @code{'Digits}
21413 @item @code{'Exponent}
21414 @item @code{'First}
21415 @item @code{'Floor}
21416 @item @code{'Fore}
21417 @item @code{'Fraction}
21418 @item @code{'Last}
21419 @item @code{'Leading_Part}
21420 @item @code{'Length}
21421 @item @code{'Machine}
21422 @item @code{'Machine_Emax}
21423 @item @code{'Machine_Emin}
21424 @item @code{'Machine_Mantissa}
21425 @item @code{'Machine_Overflows}
21426 @item @code{'Machine_Radix}
21427 @item @code{'Machine_Rounds}
21428 @item @code{'Max}
21429 @item @code{'Min}
21430 @item @code{'Model}
21431 @item @code{'Model_Emin}
21432 @item @code{'Model_Epsilon}
21433 @item @code{'Model_Mantissa}
21434 @item @code{'Model_Small}
21435 @item @code{'Modulus}
21436 @item @code{'Pos}
21437 @item @code{'Pred}
21438 @item @code{'Range}
21439 @item @code{'Remainder}
21440 @item @code{'Rounding}
21441 @item @code{'Safe_First}
21442 @item @code{'Safe_Last}
21443 @item @code{'Scaling}
21444 @item @code{'Signed_Zeros}
21445 @item @code{'Size}
21446 @item @code{'Small}
21447 @item @code{'Succ}
21448 @item @code{'Truncation}
21449 @item @code{'Unbiased_Rounding}
21450 @item @code{'Val}
21451 @item @code{'Valid}
21452 @end itemize
21453
21454 @noindent
21455 This rule has no parameters.
21456
21457
21458 @node Non_Tagged_Derived_Types
21459 @subsection @code{Non_Tagged_Derived_Types}
21460 @cindex @code{Non_Tagged_Derived_Types} rule (for @command{gnatcheck})
21461
21462 @noindent
21463 Flag all derived type declarations that do not have a record extension part.
21464
21465 This rule has no parameters.
21466
21467
21468
21469 @node Non_Visible_Exceptions
21470 @subsection @code{Non_Visible_Exceptions}
21471 @cindex @code{Non_Visible_Exceptions} rule (for @command{gnatcheck})
21472
21473 @noindent
21474 Flag constructs leading to the possibility of propagating an exception
21475 out of the scope in which the exception is declared.
21476 Two cases are detected:
21477
21478 @itemize @bullet
21479 @item
21480 An exception declaration in a subprogram body, task body or block
21481 statement is flagged if the body or statement does not contain a handler for
21482 that exception or a handler with an @code{others} choice.
21483
21484 @item
21485 A @code{raise} statement in an exception handler of a subprogram body,
21486 task body or block statement is flagged if it (re)raises a locally
21487 declared exception.  This may occur under the following circumstances:
21488 @itemize @minus
21489 @item
21490 it explicitly raises a locally declared exception, or
21491 @item
21492 it does not specify an exception name (i.e., it is simply @code{raise;})
21493 and the enclosing handler contains a locally declared exception in its
21494 exception choices.
21495 @end itemize
21496 @end itemize
21497
21498 @noindent
21499 Renamings of local exceptions are not flagged.
21500
21501 This rule has no parameters.
21502
21503
21504 @node Numeric_Literals
21505 @subsection @code{Numeric_Literals}
21506 @cindex @code{Numeric_Literals} rule (for @command{gnatcheck})
21507
21508 @noindent
21509 Flag each use of a numeric literal in an index expression, and in any
21510 circumstance except for the following:
21511
21512 @itemize @bullet
21513 @item
21514 a literal occurring in the initialization expression for a constant
21515 declaration or a named number declaration, or
21516
21517 @item
21518 an integer literal that is less than or equal to a value
21519 specified by the @option{N} rule parameter.
21520 @end itemize
21521
21522 @noindent
21523 This rule may have the following parameters for the @option{+R} option:
21524
21525 @table @asis
21526 @item @emph{N}
21527 @emph{N} is an integer literal used as the maximal value that is not flagged
21528 (i.e., integer literals not exceeding this value are allowed)
21529
21530 @item @code{ALL}
21531 All integer literals are flagged
21532 @end table
21533
21534 @noindent
21535 If no parameters are set, the maximum unflagged value is 1.
21536
21537 The last specified check limit (or the fact that there is no limit at
21538 all) is used when multiple @option{+R} options appear.
21539
21540 The @option{-R} option for this rule has no parameters.
21541 It disables the rule but retains the last specified maximum unflagged value.
21542 If the @option{+R} option subsequently appears, this value is used as the
21543 threshold for the check.
21544
21545
21546 @node OTHERS_In_Aggregates
21547 @subsection @code{OTHERS_In_Aggregates}
21548 @cindex @code{OTHERS_In_Aggregates} rule (for @command{gnatcheck})
21549
21550 @noindent
21551 Flag each use of an @code{others} choice in extension aggregates.
21552 In record and array aggregates, an @code{others} choice is flagged unless
21553 it is used to refer to all components, or to all but one component.
21554
21555 If, in case of a named array aggregate, there are two associations, one
21556 with an @code{others} choice and another with a discrete range, the
21557 @code{others} choice is flagged even if the discrete range specifies
21558 exactly one component; for example, @code{(1..1 => 0, others => 1)}.
21559
21560 This rule has no parameters.
21561
21562 @node OTHERS_In_CASE_Statements
21563 @subsection @code{OTHERS_In_CASE_Statements}
21564 @cindex @code{OTHERS_In_CASE_Statements} rule (for @command{gnatcheck})
21565
21566 @noindent
21567 Flag any use of an @code{others} choice in a @code{case} statement.
21568
21569 This rule has no parameters.
21570
21571 @node OTHERS_In_Exception_Handlers
21572 @subsection @code{OTHERS_In_Exception_Handlers}
21573 @cindex @code{OTHERS_In_Exception_Handlers} rule (for @command{gnatcheck})
21574
21575 @noindent
21576 Flag any use of an @code{others} choice in an exception handler.
21577
21578 This rule has no parameters.
21579
21580
21581 @node Outer_Loop_Exits
21582 @subsection @code{Outer_Loop_Exits}
21583 @cindex @code{Outer_Loop_Exits} rule (for @command{gnatcheck})
21584
21585 @noindent
21586 Flag each @code{exit} statement containing a loop name that is not the name
21587 of the immediately enclosing @code{loop} statement.
21588
21589 This rule has no parameters.
21590
21591
21592 @node Overloaded_Operators
21593 @subsection @code{Overloaded_Operators}
21594 @cindex @code{Overloaded_Operators} rule (for @command{gnatcheck})
21595
21596 @noindent
21597 Flag each function declaration that overloads an operator symbol.
21598 A function body is checked only if the body does not have a
21599 separate spec. Formal functions are also checked. For a
21600 renaming declaration, only renaming-as-declaration is checked
21601
21602 This rule has no parameters.
21603
21604
21605 @node Overly_Nested_Control_Structures
21606 @subsection @code{Overly_Nested_Control_Structures}
21607 @cindex @code{Overly_Nested_Control_Structures} rule (for @command{gnatcheck})
21608
21609 @noindent
21610 Flag each control structure whose nesting level exceeds the value provided
21611 in the rule parameter.
21612
21613 The control structures checked are the following:
21614
21615 @itemize @bullet
21616 @item    @code{if} statement
21617 @item    @code{case} statement
21618 @item    @code{loop} statement
21619 @item    Selective accept statement
21620 @item    Timed entry call statement
21621 @item    Conditional entry call
21622 @item    Asynchronous select statement
21623 @end itemize
21624
21625 @noindent
21626 The rule has the following parameter for the @option{+R} option:
21627
21628 @table @emph
21629 @item N
21630 Positive integer specifying the maximal control structure nesting
21631 level that is not flagged
21632 @end table
21633
21634 @noindent
21635 If the parameter for the @option{+R} option is not specified or
21636 if it is not a positive integer, @option{+R} option is ignored.
21637
21638 If more then one  option is specified for the gnatcheck call, the later option and
21639 new parameter override the previous one(s).
21640
21641
21642 @node Parameters_Out_Of_Order
21643 @subsection @code{Parameters_Out_Of_Order}
21644 @cindex @code{Parameters_Out_Of_Order} rule (for @command{gnatcheck})
21645
21646 @noindent
21647 Flag each subprogram and entry declaration whose formal parameters are not
21648 ordered according to the following scheme:
21649
21650 @itemize @bullet
21651
21652 @item @code{in} and @code{access} parameters first,
21653 then @code{in out} parameters,
21654 and then @code{out} parameters;
21655
21656 @item for @code{in} mode, parameters with default initialization expressions
21657 occur last
21658 @end itemize
21659
21660 @noindent
21661 Only the first violation of the described order is flagged.
21662
21663 The following constructs are checked:
21664
21665 @itemize @bullet
21666 @item   subprogram declarations (including null procedures);
21667 @item   generic subprogram declarations;
21668 @item   formal subprogram declarations;
21669 @item   entry declarations;
21670 @item   subprogram bodies and subprogram body stubs that do not
21671 have separate specifications
21672 @end itemize
21673
21674 @noindent
21675 Subprogram renamings are not checked.
21676
21677 This rule has no parameters.
21678
21679
21680 @node Positional_Actuals_For_Defaulted_Generic_Parameters
21681 @subsection @code{Positional_Actuals_For_Defaulted_Generic_Parameters}
21682 @cindex @code{Positional_Actuals_For_Defaulted_Generic_Parameters} rule (for @command{gnatcheck})
21683
21684 @noindent
21685 Flag each generic actual parameter corresponding to a generic formal
21686 parameter with a default initialization, if positional notation is used.
21687
21688 This rule has no parameters.
21689
21690 @node Positional_Actuals_For_Defaulted_Parameters
21691 @subsection @code{Positional_Actuals_For_Defaulted_Parameters}
21692 @cindex @code{Positional_Actuals_For_Defaulted_Parameters} rule (for @command{gnatcheck})
21693
21694 @noindent
21695 Flag each actual parameter to a subprogram or entry call where the
21696 corresponding formal parameter has a default expression, if positional
21697 notation is used.
21698
21699 This rule has no parameters.
21700
21701 @node Positional_Components
21702 @subsection @code{Positional_Components}
21703 @cindex @code{Positional_Components} rule (for @command{gnatcheck})
21704
21705 @noindent
21706 Flag each array, record and extension aggregate that includes positional
21707 notation.
21708
21709 This rule has no parameters.
21710
21711
21712 @node Positional_Generic_Parameters
21713 @subsection @code{Positional_Generic_Parameters}
21714 @cindex @code{Positional_Generic_Parameters} rule (for @command{gnatcheck})
21715
21716 @noindent
21717 Flag each instantiation using positional parameter notation.
21718
21719 This rule has no parameters.
21720
21721
21722 @node Positional_Parameters
21723 @subsection @code{Positional_Parameters}
21724 @cindex @code{Positional_Parameters} rule (for @command{gnatcheck})
21725
21726 @noindent
21727 Flag each subprogram or entry call using positional parameter notation,
21728 except for the following:
21729
21730 @itemize @bullet
21731 @item
21732 Invocations of prefix or infix operators are not flagged
21733 @item
21734 If the called subprogram or entry has only one formal parameter,
21735 the call is not flagged;
21736 @item
21737 If a subprogram call uses the @emph{Object.Operation} notation, then
21738 @itemize @minus
21739 @item
21740 the first parameter (that is, @emph{Object}) is not flagged;
21741 @item
21742 if the called subprogram has only two parameters, the second parameter
21743 of the call is not flagged;
21744 @end itemize
21745 @end itemize
21746
21747 @noindent
21748 This rule has no parameters.
21749
21750
21751
21752
21753 @node Predefined_Numeric_Types
21754 @subsection @code{Predefined_Numeric_Types}
21755 @cindex @code{Predefined_Numeric_Types} rule (for @command{gnatcheck})
21756
21757 @noindent
21758 Flag each explicit use of the name of any numeric type or subtype defined
21759 in package @code{Standard}.
21760
21761 The rationale for this rule is to detect when the
21762 program may depend on platform-specific characteristics of the implementation
21763 of the predefined numeric types. Note that this rule is over-pessimistic;
21764 for example, a program that uses @code{String} indexing
21765 likely needs a variable of type @code{Integer}.
21766 Another example is the flagging of predefined numeric types with explicit
21767 constraints:
21768
21769 @smallexample @c ada
21770     subtype My_Integer is Integer range Left .. Right;
21771     Vy_Var : My_Integer;
21772 @end smallexample
21773
21774 @noindent
21775 This rule detects only numeric types and subtypes defined in
21776 @code{Standard}. The use of numeric types and subtypes defined in other
21777 predefined packages (such as @code{System.Any_Priority} or
21778 @code{Ada.Text_IO.Count}) is not flagged
21779
21780 This rule has no parameters.
21781
21782
21783
21784 @node Raising_External_Exceptions
21785 @subsection @code{Raising_External_Exceptions}
21786 @cindex @code{Raising_External_Exceptions} rule (for @command{gnatcheck})
21787
21788 @noindent
21789 Flag any @code{raise} statement, in a program unit declared in a library
21790 package or in a generic library package, for an exception that is
21791 neither a predefined exception nor an exception that is also declared (or
21792 renamed) in the visible part of the package.
21793
21794 This rule has no parameters.
21795
21796
21797
21798 @node Raising_Predefined_Exceptions
21799 @subsection @code{Raising_Predefined_Exceptions}
21800 @cindex @code{Raising_Predefined_Exceptions} rule (for @command{gnatcheck})
21801
21802 @noindent
21803 Flag each @code{raise} statement that raises a predefined exception
21804 (i.e., one of the exceptions @code{Constraint_Error}, @code{Numeric_Error},
21805 @code{Program_Error}, @code{Storage_Error}, or @code{Tasking_Error}).
21806
21807 This rule has no parameters.
21808
21809 @node Separate_Numeric_Error_Handlers
21810 @subsection @code{Separate_Numeric_Error_Handlers}
21811 @cindex @code{Separate_Numeric_Error_Handlers} rule (for @command{gnatcheck})
21812
21813 @noindent
21814 Flags each exception handler that contains a choice for
21815 the predefined @code{Constraint_Error} exception, but does not contain
21816 the choice for the predefined @code{Numeric_Error} exception, or
21817 that contains the choice for @code{Numeric_Error}, but does not contain the
21818 choice for @code{Constraint_Error}.
21819
21820 This rule has no parameters.
21821
21822 @ignore
21823 @node Recursion
21824 @subsection @code{Recursion} (under construction, GLOBAL)
21825 @cindex @code{Recursion} rule (for @command{gnatcheck})
21826
21827 @noindent
21828 Flag recursive subprograms (cycles in the call graph). Declarations, and not
21829 calls, of recursive subprograms are detected.
21830
21831 This rule has no parameters.
21832 @end ignore
21833
21834 @ignore
21835 @node Side_Effect_Functions
21836 @subsection @code{Side_Effect_Functions} (under construction, GLOBAL)
21837 @cindex @code{Side_Effect_Functions} rule (for @command{gnatcheck})
21838
21839 @noindent
21840 Flag functions with side effects.
21841
21842 We define a side effect as changing any data object that is not local for the
21843 body of this function.
21844
21845 At the moment, we do NOT consider a side effect any input-output operations
21846 (changing a state or a content of any file).
21847
21848 We do not consider protected functions for this rule (???)
21849
21850 There are the following sources of side effect:
21851
21852 @enumerate
21853 @item Explicit (or direct) side-effect:
21854
21855 @itemize @bullet
21856 @item
21857 direct assignment to a non-local variable;
21858
21859 @item
21860 direct call to an entity that is known to change some data object that is
21861      not local for the body of this function (Note, that if F1 calls F2 and F2
21862      does have a side effect, this does not automatically mean that F1 also
21863      have a side effect, because it may be the case that F2 is declared in
21864      F1's body and it changes some data object that is global for F2, but
21865      local for F1);
21866 @end itemize
21867
21868 @item Indirect side-effect:
21869 @itemize @bullet
21870 @item
21871 Subprogram calls implicitly issued by:
21872 @itemize @bullet
21873 @item
21874 computing initialization expressions from type declarations as a part
21875          of object elaboration or allocator evaluation;
21876 @item
21877 computing implicit parameters of subprogram or entry calls or generic
21878          instantiations;
21879 @end itemize
21880
21881 @item
21882 activation of a task that change some non-local data object (directly or
21883      indirectly);
21884
21885 @item
21886 elaboration code of a package that is a result of a package instantiation;
21887
21888 @item
21889 controlled objects;
21890 @end itemize
21891
21892 @item Situations when we can suspect a side-effect, but the full static check
21893 is either impossible or too hard:
21894 @itemize @bullet
21895 @item
21896 assignment to access variables or to the objects pointed by access
21897      variables;
21898
21899 @item
21900 call to a subprogram pointed by access-to-subprogram value
21901
21902 @item
21903 dispatching calls;
21904 @end itemize
21905 @end enumerate
21906
21907 @noindent
21908 This rule has no parameters.
21909 @end ignore
21910
21911 @node Slices
21912 @subsection @code{Slices}
21913 @cindex @code{Slices} rule (for @command{gnatcheck})
21914
21915 @noindent
21916 Flag all uses of array slicing
21917
21918 This rule has no parameters.
21919
21920
21921 @node Unassigned_OUT_Parameters
21922 @subsection @code{Unassigned_OUT_Parameters}
21923 @cindex @code{Unassigned_OUT_Parameters} rule (for @command{gnatcheck})
21924
21925 @noindent
21926 Flags procedures' @code{out} parameters that are not assigned, and
21927 identifies the contexts in which the assignments are missing.
21928
21929 An @code{out} parameter is flagged in the statements in the procedure
21930 body's handled sequence of statements (before the procedure body's
21931 @code{exception} part, if any) if this sequence of statements contains
21932 no assignments to the parameter.
21933
21934 An @code{out} parameter is flagged in an exception handler in the exception
21935 part of the procedure body's handled sequence of statements if the handler
21936 contains no assignment to the parameter.
21937
21938 Bodies of generic procedures are also considered.
21939
21940 The following are treated as assignments to an @code{out} parameter:
21941
21942 @itemize @bullet
21943 @item
21944 an assignment statement, with the parameter or some component as the target;
21945
21946 @item
21947 passing the parameter (or one of its components) as an @code{out} or
21948 @code{in out} parameter.
21949 @end itemize
21950
21951 @noindent
21952 This rule does not have any parameters.
21953
21954
21955
21956 @node Uncommented_BEGIN_In_Package_Bodies
21957 @subsection @code{Uncommented_BEGIN_In_Package_Bodies}
21958 @cindex @code{Uncommented_BEGIN_In_Package_Bodies} rule (for @command{gnatcheck})
21959
21960 @noindent
21961 Flags each package body with declarations and a statement part that does not
21962 include a trailing comment on the line containing the @code{begin} keyword;
21963 this trailing comment needs to specify the package name and nothing else.
21964 The @code{begin} is not flagged if the package body does not
21965 contain any declarations.
21966
21967 If the @code{begin} keyword is placed on the
21968 same line as the last declaration or the first statement, it is flagged
21969 independently of whether the line contains a trailing comment. The
21970 diagnostic message is attached to the line containing the first statement.
21971
21972 This rule has no parameters.
21973
21974
21975 @node Unconstrained_Array_Returns
21976 @subsection @code{Unconstrained_Array_Returns}
21977 @cindex @code{Unconstrained_Array_Returns} rule (for @command{gnatcheck})
21978
21979 @noindent
21980 Flag each function returning an unconstrained array. Function declarations,
21981 function bodies (and body stubs) having no separate specifications,
21982 and generic function instantiations are checked.
21983 Generic function declarations, function calls and function renamings are
21984 not checked.
21985
21986 This rule has no parameters.
21987
21988 @node Universal_Ranges
21989 @subsection @code{Universal_Ranges}
21990 @cindex @code{Universal_Ranges} rule (for @command{gnatcheck})
21991
21992 @noindent
21993 Flag discrete ranges that are a part of an index constraint, constrained
21994 array definition, or @code{for}-loop parameter specification, and whose bounds
21995 are both of type @i{universal_integer}. Ranges that have at least one
21996 bound of a specific type (such as @code{1 .. N}, where @code{N} is a variable
21997 or an expression of non-universal type) are not flagged.
21998
21999 This rule has no parameters.
22000
22001
22002 @node Unnamed_Blocks_And_Loops
22003 @subsection @code{Unnamed_Blocks_And_Loops}
22004 @cindex @code{Unnamed_Blocks_And_Loops} rule (for @command{gnatcheck})
22005
22006 @noindent
22007 Flag each unnamed block statement and loop statement.
22008
22009 The rule has no parameters.
22010
22011
22012
22013 @ignore
22014 @node Unused_Subprograms
22015 @subsection @code{Unused_Subprograms} (under construction, GLOBAL)
22016 @cindex @code{Unused_Subprograms} rule (for @command{gnatcheck})
22017
22018 @noindent
22019 Flag all unused subprograms.
22020
22021 This rule has no parameters.
22022 @end ignore
22023
22024
22025
22026
22027 @node USE_PACKAGE_Clauses
22028 @subsection @code{USE_PACKAGE_Clauses}
22029 @cindex @code{USE_PACKAGE_Clauses} rule (for @command{gnatcheck})
22030
22031 @noindent
22032 Flag all @code{use} clauses for packages; @code{use type} clauses are
22033 not flagged.
22034
22035 This rule has no parameters.
22036
22037
22038
22039 @node Volatile_Objects_Without_Address_Clauses
22040 @subsection @code{Volatile_Objects_Without_Address_Clauses}
22041 @cindex @code{Volatile_Objects_Without_Address_Clauses} rule (for @command{gnatcheck})
22042
22043 @noindent
22044 Flag each volatile object that does not have an address clause.
22045
22046 The following check is made: if the pragma @code{Volatile} is applied to a
22047 data object or to its type, then an address clause must
22048 be supplied for this object.
22049
22050 This rule does not check the components of data objects,
22051 array components that are volatile as a result of the pragma
22052 @code{Volatile_Components}, or objects that are volatile because
22053 they are atomic as a result of pragmas @code{Atomic} or
22054 @code{Atomic_Components}.
22055
22056 Only variable declarations, and not constant declarations, are checked.
22057
22058 This rule has no parameters.
22059
22060
22061 @c *********************************
22062 @node Creating Sample Bodies Using gnatstub
22063 @chapter Creating Sample Bodies Using @command{gnatstub}
22064 @findex gnatstub
22065
22066 @noindent
22067 @command{gnatstub} creates body stubs, that is, empty but compilable bodies
22068 for library unit declarations.
22069
22070 Note: to invoke @code{gnatstub} with a project file, use the @code{gnat}
22071 driver (see @ref{The GNAT Driver and Project Files}).
22072
22073 To create a body stub, @command{gnatstub} has to compile the library
22074 unit declaration. Therefore, bodies can be created only for legal
22075 library units. Moreover, if a library unit depends semantically upon
22076 units located outside the current directory, you have to provide
22077 the source search path when calling @command{gnatstub}, see the description
22078 of @command{gnatstub} switches below.
22079
22080 By default, all the program unit body stubs generated by @code{gnatstub}
22081 raise the predefined @code{Program_Error} exception, which will catch
22082 accidental calls of generated stubs. This behavior can be changed with
22083 option @option{^--no-exception^/NO_EXCEPTION^} (see below).
22084
22085 @menu
22086 * Running gnatstub::
22087 * Switches for gnatstub::
22088 @end menu
22089
22090 @node Running gnatstub
22091 @section Running @command{gnatstub}
22092
22093 @noindent
22094 @command{gnatstub} has the command-line interface of the form
22095
22096 @smallexample
22097 $ gnatstub @ovar{switches} @var{filename} @ovar{directory}
22098 @end smallexample
22099
22100 @noindent
22101 where
22102 @table @var
22103 @item filename
22104 is the name of the source file that contains a library unit declaration
22105 for which a body must be created. The file name may contain the path
22106 information.
22107 The file name does not have to follow the GNAT file name conventions. If the
22108 name
22109 does not follow GNAT file naming conventions, the name of the body file must
22110 be provided
22111 explicitly as the value of the @option{^-o^/BODY=^@var{body-name}} option.
22112 If the file name follows the GNAT file naming
22113 conventions and the name of the body file is not provided,
22114 @command{gnatstub}
22115 creates the name
22116 of the body file from the argument file name by replacing the @file{.ads}
22117 suffix
22118 with the @file{.adb} suffix.
22119
22120 @item directory
22121 indicates the directory in which the body stub is to be placed (the default
22122 is the
22123 current directory)
22124
22125 @item switches
22126 is an optional sequence of switches as described in the next section
22127 @end table
22128
22129 @node Switches for gnatstub
22130 @section Switches for @command{gnatstub}
22131
22132 @table @option
22133 @c !sort!
22134
22135 @item ^-f^/FULL^
22136 @cindex @option{^-f^/FULL^} (@command{gnatstub})
22137 If the destination directory already contains a file with the name of the
22138 body file
22139 for the argument spec file, replace it with the generated body stub.
22140
22141 @item ^-hs^/HEADER=SPEC^
22142 @cindex @option{^-hs^/HEADER=SPEC^} (@command{gnatstub})
22143 Put the comment header (i.e., all the comments preceding the
22144 compilation unit) from the source of the library unit declaration
22145 into the body stub.
22146
22147 @item ^-hg^/HEADER=GENERAL^
22148 @cindex @option{^-hg^/HEADER=GENERAL^} (@command{gnatstub})
22149 Put a sample comment header into the body stub.
22150
22151 @item ^--header-file=@var{filename}^/FROM_HEADER_FILE=@var{filename}^
22152 @cindex @option{^--header-file^/FROM_HEADER_FILE=^} (@command{gnatstub})
22153 Use the content of the file as the comment header for a generated body stub.
22154
22155 @ifclear vms
22156 @item -IDIR
22157 @cindex @option{-IDIR} (@command{gnatstub})
22158 @itemx -I-
22159 @cindex @option{-I-} (@command{gnatstub})
22160 @end ifclear
22161 @ifset vms
22162 @item /NOCURRENT_DIRECTORY
22163 @cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub})
22164 @end ifset
22165 ^These switches have ^This switch has^ the same meaning as in calls to
22166 @command{gcc}.
22167 ^They define ^It defines ^ the source search path in the call to
22168 @command{gcc} issued
22169 by @command{gnatstub} to compile an argument source file.
22170
22171 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE=^@var{PATH}
22172 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatstub})
22173 This switch has the same meaning as in calls to @command{gcc}.
22174 It defines the additional configuration file to be passed to the call to
22175 @command{gcc} issued
22176 by @command{gnatstub} to compile an argument source file.
22177
22178 @item ^-gnatyM^/MAX_LINE_LENGTH=^@var{n}
22179 @cindex @option{^-gnatyM^/MAX_LINE_LENGTH^} (@command{gnatstub})
22180 (@var{n} is a non-negative integer). Set the maximum line length in the
22181 body stub to @var{n}; the default is 79. The maximum value that can be
22182 specified is 32767. Note that in the special case of configuration
22183 pragma files, the maximum is always 32767 regardless of whether or
22184 not this switch appears.
22185
22186 @item ^-gnaty^/STYLE_CHECKS=^@var{n}
22187 @cindex @option{^-gnaty^/STYLE_CHECKS=^} (@command{gnatstub})
22188 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
22189 the generated body sample to @var{n}.
22190 The default indentation is 3.
22191
22192 @item ^-gnatyo^/ORDERED_SUBPROGRAMS^
22193 @cindex @option{^-gnato^/ORDERED_SUBPROGRAMS^} (@command{gnatstub})
22194 Order local bodies alphabetically. (By default local bodies are ordered
22195 in the same way as the corresponding local specs in the argument spec file.)
22196
22197 @item ^-i^/INDENTATION=^@var{n}
22198 @cindex @option{^-i^/INDENTATION^} (@command{gnatstub})
22199 Same as @option{^-gnaty^/STYLE_CHECKS=^@var{n}}
22200
22201 @item ^-k^/TREE_FILE=SAVE^
22202 @cindex @option{^-k^/TREE_FILE=SAVE^} (@command{gnatstub})
22203 Do not remove the tree file (i.e., the snapshot of the compiler internal
22204 structures used by @command{gnatstub}) after creating the body stub.
22205
22206 @item ^-l^/LINE_LENGTH=^@var{n}
22207 @cindex @option{^-l^/LINE_LENGTH^} (@command{gnatstub})
22208 Same as @option{^-gnatyM^/MAX_LINE_LENGTH=^@var{n}}
22209
22210 @item ^--no-exception^/NO_EXCEPTION^
22211 @cindex @option{^--no-exception^/NO_EXCEPTION^} (@command{gnatstub})
22212 Avoind raising PROGRAM_ERROR in the generated bodies of program unit stubs.
22213 This is not always possible for function stubs.
22214
22215 @item ^-o ^/BODY=^@var{body-name}
22216 @cindex @option{^-o^/BODY^} (@command{gnatstub})
22217 Body file name.  This should be set if the argument file name does not
22218 follow
22219 the GNAT file naming
22220 conventions. If this switch is omitted the default name for the body will be
22221 obtained
22222 from the argument file name according to the GNAT file naming conventions.
22223
22224 @item ^-q^/QUIET^
22225 @cindex @option{^-q^/QUIET^} (@command{gnatstub})
22226 Quiet mode: do not generate a confirmation when a body is
22227 successfully created, and do not generate a message when a body is not
22228 required for an
22229 argument unit.
22230
22231 @item ^-r^/TREE_FILE=REUSE^
22232 @cindex @option{^-r^/TREE_FILE=REUSE^} (@command{gnatstub})
22233 Reuse the tree file (if it exists) instead of creating it.  Instead of
22234 creating the tree file for the library unit declaration, @command{gnatstub}
22235 tries to find it in the current directory and use it for creating
22236 a body. If the tree file is not found, no body is created. This option
22237 also implies @option{^-k^/SAVE^}, whether or not
22238 the latter is set explicitly.
22239
22240 @item ^-t^/TREE_FILE=OVERWRITE^
22241 @cindex @option{^-t^/TREE_FILE=OVERWRITE^} (@command{gnatstub})
22242 Overwrite the existing tree file.  If the current directory already
22243 contains the file which, according to the GNAT file naming rules should
22244 be considered as a tree file for the argument source file,
22245 @command{gnatstub}
22246 will refuse to create the tree file needed to create a sample body
22247 unless this option is set.
22248
22249 @item ^-v^/VERBOSE^
22250 @cindex @option{^-v^/VERBOSE^} (@command{gnatstub})
22251 Verbose mode: generate version information.
22252
22253 @end table
22254
22255 @c *********************************
22256 @node Generating Ada Bindings for C and C++ headers
22257 @chapter Generating Ada Bindings for C and C++ headers
22258 @findex binding
22259
22260 @noindent
22261 GNAT now comes with a new experimental binding generator for C and C++
22262 headers which is intended to do 95% of the tedious work of generating
22263 Ada specs from C or C++ header files. Note that this still is a work in
22264 progress, not designed to generate 100% correct Ada specs.
22265
22266 Note that the code generated is using the Ada 2005 syntax, which makes it
22267 easier to inteface with other languages than previous versions of Ada.
22268
22269 @menu
22270 * Running the binding generator::
22271 * Generating bindings for C++ headers::
22272 * Switches::
22273 @end menu
22274
22275 @node Running the binding generator
22276 @section Running the binding generator
22277
22278 @noindent
22279 The binding generator is part of the @command{gcc} compiler and can be
22280 invoked via the @option{-fdump-ada-spec} switch, which will generate Ada
22281 spec files for the header files specified on the command line, and all
22282 header files needed by these files transitivitely. For example:
22283
22284 @smallexample
22285 $ g++ -c -fdump-ada-spec -C /usr/include/time.h
22286 $ gcc -c -gnat05 *.ads
22287 @end smallexample
22288
22289 will generate, under GNU/Linux, the following files: @file{bits_time_h.ads},
22290 @code{bits_types_h.ads}, @code{stddef_h.ads}, @code{time_h.ads} which
22291 correspond to the files @file{/usr/include/time.h},
22292 @file{/usr/include/bits/time.h}, etc@dots{}, and will then compile in Ada 2005
22293 mode these Ada specs.
22294
22295 The @code{-C} switch tells @command{gcc} to extract comments from headers,
22296 and will attempt to generate corresponding Ada comments.
22297
22298 If you want to generate a single Ada file and not the transitive closure, you
22299 can use instead the @option{-fdump-ada-spec-slim} switch.
22300
22301 Note that we recommend when possible to use the @command{g++} driver to
22302 generate bindings, even for most C headers, since this will in general
22303 generate better Ada specs. For generating bindings for C++ headers, it is
22304 mandatory to use the @command{g++} command, or @command{gcc -x c++} which
22305 is equivalent in this case. If @command{g++} cannot work on your C headers
22306 because of incompatibilities between C and C++, then you can fallback to
22307 @command{gcc} instead.
22308
22309 For an example of better bindings generated from the C++ front-end,
22310 the name of the parameters (when available) are actually ignored by the C
22311 front-end. Consider the following C header:
22312
22313 @smallexample
22314 extern void foo (int variable);
22315 @end smallexample
22316
22317 with the C front-end, @code{variable} is ignored, and the above is handled as:
22318
22319 @smallexample
22320 extern void foo (int);
22321 @end smallexample
22322
22323 generating a generic:
22324
22325 @smallexample
22326 procedure foo (param1 : int);
22327 @end smallexample
22328
22329 with the C++ front-end, the name is available, and we generate:
22330
22331 @smallexample
22332 procedure foo (variable : int);
22333 @end smallexample
22334
22335 In some cases, the generated bindings will be more complete or more meaningful
22336 when defining some macros, which you can do via the @option{-D} switch. this
22337 is for example the case with @file{Xlib.h} under GNU/Linux:
22338
22339 @smallexample
22340 g++ -c -fdump-ada-spec -DXLIB_ILLEGAL_ACCESS -C /usr/include/X11/Xlib.h
22341 @end smallexample
22342
22343 The above will generate more complete bindings than a straight call without
22344 the @option{-DXLIB_ILLEGAL_ACCESS} switch.
22345
22346 In other cases, it is not possible to parse a header file in a stand alone
22347 manner, because other include files need to be included first. In this
22348 case, the solution is to create a small header file including the needed
22349 @code{#include} and possible @code{#define} directives. For example, to
22350 generate Ada bindings for @file{readline/readlin.h}, you need to first
22351 include @file{stdio.h}, so you can create a file with the following two
22352 lines in e.g. @file{readline1.h}:
22353
22354 @smallexample
22355 #include <stdio.h>
22356 #include <readline/readline.h>
22357 @end smallexample
22358
22359 and then generate Ada bindings from this file:
22360
22361 @smallexample
22362 $ g++ -c -fdump-ada-spec readline1.h
22363 @end smallexample
22364
22365 @node Generating bindings for C++ headers
22366 @section Generating bindings for C++ headers
22367
22368 @noindent
22369 Generating bindings for C++ headers is done using the same options, always
22370 with the @command{g++} compiler.
22371
22372 In this mode, C++ classes will be mapped to Ada tagged types, constructors
22373 will be mapped using the @code{CPP_Constructor} pragma, and when possible,
22374 multiple inheritance of abstract classes will be mapped to Ada interfaces
22375 (@xref{Interfacing to C++,,,gnat_rm, GNAT Reference Manual}, for additional
22376 information on interfacing to C++).
22377
22378 @node Switches
22379 @section Switches
22380
22381 @table @option
22382 @item -fdump-ada-spec
22383 @cindex @option{-fdump-ada-spec} (@command{gcc})
22384 Generate Ada spec files for the given header files transitively (including
22385 all header files that these headers depend upon).
22386
22387 @item -fdump-ada-spec-slim
22388 @cindex @option{-fdump-ada-spec-slim} (@command{gcc})
22389 Generate Ada spec files for the header files specified on the command line
22390 only.
22391
22392 @item -C
22393 @item @option{-C} (@command{gcc})
22394 Extract comments from headers and generate Ada comments in the Ada spec files.
22395 @end table
22396
22397 @node Other Utility Programs
22398 @chapter Other Utility Programs
22399
22400 @noindent
22401 This chapter discusses some other utility programs available in the Ada
22402 environment.
22403
22404 @menu
22405 * Using Other Utility Programs with GNAT::
22406 * The External Symbol Naming Scheme of GNAT::
22407 * Converting Ada Files to html with gnathtml::
22408 * Installing gnathtml::
22409 @ifset vms
22410 * LSE::
22411 * Profiling::
22412 @end ifset
22413 @end menu
22414
22415 @node Using Other Utility Programs with GNAT
22416 @section Using Other Utility Programs with GNAT
22417
22418 @noindent
22419 The object files generated by GNAT are in standard system format and in
22420 particular the debugging information uses this format. This means
22421 programs generated by GNAT can be used with existing utilities that
22422 depend on these formats.
22423
22424 @ifclear vms
22425 In general, any utility program that works with C will also often work with
22426 Ada programs generated by GNAT. This includes software utilities such as
22427 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
22428 as Purify.
22429 @end ifclear
22430
22431 @node The External Symbol Naming Scheme of GNAT
22432 @section The External Symbol Naming Scheme of GNAT
22433
22434 @noindent
22435 In order to interpret the output from GNAT, when using tools that are
22436 originally intended for use with other languages, it is useful to
22437 understand the conventions used to generate link names from the Ada
22438 entity names.
22439
22440 All link names are in all lowercase letters. With the exception of library
22441 procedure names, the mechanism used is simply to use the full expanded
22442 Ada name with dots replaced by double underscores. For example, suppose
22443 we have the following package spec:
22444
22445 @smallexample @c ada
22446 @group
22447 @cartouche
22448 package QRS is
22449    MN : Integer;
22450 end QRS;
22451 @end cartouche
22452 @end group
22453 @end smallexample
22454
22455 @noindent
22456 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
22457 the corresponding link name is @code{qrs__mn}.
22458 @findex Export
22459 Of course if a @code{pragma Export} is used this may be overridden:
22460
22461 @smallexample @c ada
22462 @group
22463 @cartouche
22464 package Exports is
22465    Var1 : Integer;
22466    pragma Export (Var1, C, External_Name => "var1_name");
22467    Var2 : Integer;
22468    pragma Export (Var2, C, Link_Name => "var2_link_name");
22469 end Exports;
22470 @end cartouche
22471 @end group
22472 @end smallexample
22473
22474 @noindent
22475 In this case, the link name for @var{Var1} is whatever link name the
22476 C compiler would assign for the C function @var{var1_name}. This typically
22477 would be either @var{var1_name} or @var{_var1_name}, depending on operating
22478 system conventions, but other possibilities exist. The link name for
22479 @var{Var2} is @var{var2_link_name}, and this is not operating system
22480 dependent.
22481
22482 @findex _main
22483 One exception occurs for library level procedures. A potential ambiguity
22484 arises between the required name @code{_main} for the C main program,
22485 and the name we would otherwise assign to an Ada library level procedure
22486 called @code{Main} (which might well not be the main program).
22487
22488 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
22489 names. So if we have a library level procedure such as
22490
22491 @smallexample @c ada
22492 @group
22493 @cartouche
22494 procedure Hello (S : String);
22495 @end cartouche
22496 @end group
22497 @end smallexample
22498
22499 @noindent
22500 the external name of this procedure will be @var{_ada_hello}.
22501
22502
22503 @node Converting Ada Files to html with gnathtml
22504 @section Converting Ada Files to HTML with @code{gnathtml}
22505
22506 @noindent
22507 This @code{Perl} script allows Ada source files to be browsed using
22508 standard Web browsers. For installation procedure, see the section
22509 @xref{Installing gnathtml}.
22510
22511 Ada reserved keywords are highlighted in a bold font and Ada comments in
22512 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
22513 switch to suppress the generation of cross-referencing information, user
22514 defined variables and types will appear in a different color; you will
22515 be able to click on any identifier and go to its declaration.
22516
22517 The command line is as follow:
22518 @smallexample
22519 $ perl gnathtml.pl @ovar{^switches^options^} @var{ada-files}
22520 @end smallexample
22521
22522 @noindent
22523 You can pass it as many Ada files as you want. @code{gnathtml} will generate
22524 an html file for every ada file, and a global file called @file{index.htm}.
22525 This file is an index of every identifier defined in the files.
22526
22527 The available ^switches^options^ are the following ones:
22528
22529 @table @option
22530 @item -83
22531 @cindex @option{-83} (@code{gnathtml})
22532 Only the Ada 83 subset of keywords will be highlighted.
22533
22534 @item -cc @var{color}
22535 @cindex @option{-cc} (@code{gnathtml})
22536 This option allows you to change the color used for comments. The default
22537 value is green. The color argument can be any name accepted by html.
22538
22539 @item -d
22540 @cindex @option{-d} (@code{gnathtml})
22541 If the Ada files depend on some other files (for instance through
22542 @code{with} clauses, the latter files will also be converted to html.
22543 Only the files in the user project will be converted to html, not the files
22544 in the run-time library itself.
22545
22546 @item -D
22547 @cindex @option{-D} (@code{gnathtml})
22548 This command is the same as @option{-d} above, but @command{gnathtml} will
22549 also look for files in the run-time library, and generate html files for them.
22550
22551 @item -ext @var{extension}
22552 @cindex @option{-ext} (@code{gnathtml})
22553 This option allows you to change the extension of the generated HTML files.
22554 If you do not specify an extension, it will default to @file{htm}.
22555
22556 @item -f
22557 @cindex @option{-f} (@code{gnathtml})
22558 By default, gnathtml will generate html links only for global entities
22559 ('with'ed units, global variables and types,@dots{}).  If you specify
22560 @option{-f} on the command line, then links will be generated for local
22561 entities too.
22562
22563 @item -l @var{number}
22564 @cindex @option{-l} (@code{gnathtml})
22565 If this ^switch^option^ is provided and @var{number} is not 0, then
22566 @code{gnathtml} will number the html files every @var{number} line.
22567
22568 @item -I @var{dir}
22569 @cindex @option{-I} (@code{gnathtml})
22570 Specify a directory to search for library files (@file{.ALI} files) and
22571 source files. You can provide several -I switches on the command line,
22572 and the directories will be parsed in the order of the command line.
22573
22574 @item -o @var{dir}
22575 @cindex @option{-o} (@code{gnathtml})
22576 Specify the output directory for html files. By default, gnathtml will
22577 saved the generated html files in a subdirectory named @file{html/}.
22578
22579 @item -p @var{file}
22580 @cindex @option{-p} (@code{gnathtml})
22581 If you are using Emacs and the most recent Emacs Ada mode, which provides
22582 a full Integrated Development Environment for compiling, checking,
22583 running and debugging applications, you may use @file{.gpr} files
22584 to give the directories where Emacs can find sources and object files.
22585
22586 Using this ^switch^option^, you can tell gnathtml to use these files.
22587 This allows you to get an html version of your application, even if it
22588 is spread over multiple directories.
22589
22590 @item -sc @var{color}
22591 @cindex @option{-sc} (@code{gnathtml})
22592 This ^switch^option^ allows you to change the color used for symbol
22593 definitions.
22594 The default value is red. The color argument can be any name accepted by html.
22595
22596 @item -t @var{file}
22597 @cindex @option{-t} (@code{gnathtml})
22598 This ^switch^option^ provides the name of a file. This file contains a list of
22599 file names to be converted, and the effect is exactly as though they had
22600 appeared explicitly on the command line. This
22601 is the recommended way to work around the command line length limit on some
22602 systems.
22603
22604 @end table
22605
22606 @node Installing gnathtml
22607 @section Installing @code{gnathtml}
22608
22609 @noindent
22610 @code{Perl} needs to be installed on your machine to run this script.
22611 @code{Perl} is freely available for almost every architecture and
22612 Operating System via the Internet.
22613
22614 On Unix systems, you  may want to modify  the  first line of  the script
22615 @code{gnathtml},  to explicitly  tell  the Operating  system  where Perl
22616 is. The syntax of this line is:
22617 @smallexample
22618 #!full_path_name_to_perl
22619 @end smallexample
22620
22621 @noindent
22622 Alternatively, you may run the script using the following command line:
22623
22624 @smallexample
22625 $ perl gnathtml.pl @ovar{switches} @var{files}
22626 @end smallexample
22627
22628 @ifset vms
22629 @node LSE
22630 @section LSE
22631 @findex LSE
22632
22633 @noindent
22634 The GNAT distribution provides an Ada 95 template for the HP Language
22635 Sensitive Editor (LSE), a component of DECset. In order to
22636 access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
22637
22638 @node Profiling
22639 @section Profiling
22640 @findex PCA
22641
22642 @noindent
22643 GNAT supports The HP Performance Coverage Analyzer (PCA), a component
22644 of DECset. To use it proceed as outlined under ``HELP PCA'', except for running
22645 the collection phase with the /DEBUG qualifier.
22646
22647 @smallexample
22648 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
22649 $ DEFINE LIB$DEBUG PCA$COLLECTOR
22650 $ RUN/DEBUG <PROGRAM_NAME>
22651 @end smallexample
22652 @noindent
22653 @end ifset
22654
22655 @ifclear vms
22656 @c ******************************
22657 @node Code Coverage and Profiling
22658 @chapter Code Coverage and Profiling
22659 @cindex Code Coverage
22660 @cindex Profiling
22661
22662 @noindent
22663 This chapter describes how to use @code{gcov} - coverage testing tool - and
22664 @code{gprof} - profiler tool - on your Ada programs.
22665
22666 @menu
22667 * Code Coverage of Ada Programs using gcov::
22668 * Profiling an Ada Program using gprof::
22669 @end menu
22670
22671 @node Code Coverage of Ada Programs using gcov
22672 @section Code Coverage of Ada Programs using gcov
22673 @cindex gcov
22674 @cindex -fprofile-arcs
22675 @cindex -ftest-coverage
22676 @cindex -coverage
22677 @cindex Code Coverage
22678
22679 @noindent
22680 @code{gcov} is a test coverage program: it analyzes the execution of a given
22681 program on selected tests, to help you determine the portions of the program
22682 that are still untested.
22683
22684 @code{gcov} is part of the GCC suite, and is described in detail in the GCC
22685 User's Guide. You can refer to this documentation for a more complete
22686 description.
22687
22688 This chapter provides a quick startup guide, and
22689 details some Gnat-specific features.
22690
22691 @menu
22692 * Quick startup guide::
22693 * Gnat specifics::
22694 @end menu
22695
22696 @node Quick startup guide
22697 @subsection Quick startup guide
22698
22699 In order to perform coverage analysis of a program using @code{gcov}, 3
22700 steps are needed:
22701
22702 @itemize @bullet
22703 @item
22704 Code instrumentation during the compilation process
22705 @item
22706 Execution of the instrumented program
22707 @item
22708 Execution of the @code{gcov} tool to generate the result.
22709 @end itemize
22710
22711 The code instrumentation needed by gcov is created at the object level:
22712 The source code is not modified in any way, because the instrumentation code is
22713 inserted by gcc during the compilation process. To compile your code with code
22714 coverage activated, you need to recompile your whole project using the
22715 switches
22716 @code{-fprofile-arcs} and @code{-ftest-coverage}, and link it using
22717 @code{-fprofile-arcs}.
22718
22719 @smallexample
22720 $ gnatmake -P my_project.gpr -f -cargs -fprofile-arcs -ftest-coverage \
22721    -largs -fprofile-arcs
22722 @end smallexample
22723
22724 This compilation process will create @file{.gcno} files together with
22725 the usual object files.
22726
22727 Once the program is compiled with coverage instrumentation, you can
22728 run it as many times as needed - on portions of a test suite for
22729 example. The first execution will produce @file{.gcda} files at the
22730 same location as the @file{.gcno} files.  The following executions
22731 will update those files, so that a cumulative result of the covered
22732 portions of the program is generated.
22733
22734 Finally, you need to call the @code{gcov} tool. The different options of
22735 @code{gcov} are available in the GCC User's Guide, section 'Invoking gcov'.
22736
22737 This will create annotated source files with a @file{.gcov} extension:
22738 @file{my_main.adb} file will be analysed in @file{my_main.adb.gcov}.
22739
22740 @node Gnat specifics
22741 @subsection Gnat specifics
22742
22743 Because Ada semantics, portions of the source code may be shared among
22744 several object files. This is the case for example when generics are
22745 involved, when inlining is active  or when declarations generate  initialisation
22746 calls. In order to take
22747 into account this shared code, you need to call @code{gcov} on all
22748 source files of the tested program at once.
22749
22750 The list of source files might exceed the system's maximum command line
22751 length. In order to bypass this limitation, a new mechanism has been
22752 implemented in @code{gcov}: you can now list all your project's files into a
22753 text file, and provide this file to gcov as a parameter,  preceded by a @@
22754 (e.g. @samp{gcov @@mysrclist.txt}).
22755
22756 Note that on AIX compiling a static library with @code{-fprofile-arcs} is
22757 not supported as there can be unresolved symbols during the final link.
22758
22759 @node Profiling an Ada Program using gprof
22760 @section Profiling an Ada Program using gprof
22761 @cindex gprof
22762 @cindex -pg
22763 @cindex Profiling
22764
22765 @noindent
22766 This section is not meant to be an exhaustive documentation of @code{gprof}.
22767 Full documentation for it can be found in the GNU Profiler User's Guide
22768 documentation that is part of this GNAT distribution.
22769
22770 Profiling a program helps determine the parts of a program that are executed
22771 most often, and are therefore the most time-consuming.
22772
22773 @code{gprof} is the standard GNU profiling tool; it has been enhanced to
22774 better handle Ada programs and multitasking.
22775 It is currently supported on the following platforms
22776 @itemize @bullet
22777 @item
22778 linux x86/x86_64
22779 @item
22780 solaris sparc/sparc64/x86
22781 @item
22782 windows x86
22783 @end itemize
22784
22785 @noindent
22786 In order to profile a program using @code{gprof}, 3 steps are needed:
22787
22788 @itemize @bullet
22789 @item
22790 Code instrumentation, requiring a full recompilation of the project with the
22791 proper switches.
22792 @item
22793 Execution of the program under the analysis conditions, i.e. with the desired
22794 input.
22795 @item
22796 Analysis of the results using the @code{gprof} tool.
22797 @end itemize
22798
22799 @noindent
22800 The following sections detail the different steps, and indicate how
22801 to interpret the results:
22802 @menu
22803 * Compilation for profiling::
22804 * Program execution::
22805 * Running gprof::
22806 * Interpretation of profiling results::
22807 @end menu
22808
22809 @node Compilation for profiling
22810 @subsection Compilation for profiling
22811 @cindex -pg
22812 @cindex Profiling
22813
22814 In order to profile a program the first step is to tell the compiler
22815 to generate the necessary profiling information. The compiler switch to be used
22816 is @code{-pg}, which must be added to other compilation switches. This
22817 switch needs to be specified both during compilation and link stages, and can
22818 be specified once when using gnatmake:
22819
22820 @smallexample
22821 gnatmake -f -pg -P my_project
22822 @end smallexample
22823
22824 @noindent
22825 Note that only the objects that were compiled with the @samp{-pg} switch will be
22826 profiled; if you need to profile your whole project, use the
22827 @samp{-f} gnatmake switch to force full recompilation.
22828
22829 @node Program execution
22830 @subsection Program execution
22831
22832 @noindent
22833 Once the program has been compiled for profiling, you can run it as usual.
22834
22835 The only constraint imposed by profiling is that the program must terminate
22836 normally. An interrupted program (via a Ctrl-C, kill, etc.) will not be
22837 properly analyzed.
22838
22839 Once the program completes execution, a data file called @file{gmon.out} is
22840 generated in the directory where the program was launched from. If this file
22841 already exists, it will be overwritten.
22842
22843 @node Running gprof
22844 @subsection Running gprof
22845
22846 @noindent
22847 The @code{gprof} tool is called as follow:
22848
22849 @smallexample
22850 gprof my_prog gmon.out
22851 @end smallexample
22852
22853 @noindent
22854 or simpler:
22855
22856 @smallexample
22857 gprof my_prog
22858 @end smallexample
22859
22860 @noindent
22861 The complete form of the gprof command line is the following:
22862
22863 @smallexample
22864 gprof [^switches^options^] [executable [data-file]]
22865 @end smallexample
22866
22867 @noindent
22868 @code{gprof} supports numerous ^switch^options^. The order of these
22869 ^switch^options^ does not matter. The full list of options can be found in
22870 the GNU Profiler User's Guide documentation that comes with this documentation.
22871
22872 The following is the subset of those switches that is most relevant:
22873
22874 @table @option
22875
22876 @item --demangle[=@var{style}]
22877 @itemx --no-demangle
22878 @cindex @option{--demangle} (@code{gprof})
22879 These options control whether symbol names should be demangled when
22880 printing output.  The default is to demangle C++ symbols.  The
22881 @code{--no-demangle} option may be used to turn off demangling. Different
22882 compilers have different mangling styles.  The optional demangling style
22883 argument can be used to choose an appropriate demangling style for your
22884 compiler, in particular Ada symbols generated by GNAT can be demangled using
22885 @code{--demangle=gnat}.
22886
22887 @item -e @var{function_name}
22888 @cindex @option{-e} (@code{gprof})
22889 The @samp{-e @var{function}} option tells @code{gprof} not to print
22890 information about the function @var{function_name} (and its
22891 children@dots{}) in the call graph.  The function will still be listed
22892 as a child of any functions that call it, but its index number will be
22893 shown as @samp{[not printed]}.  More than one @samp{-e} option may be
22894 given; only one @var{function_name} may be indicated with each @samp{-e}
22895 option.
22896
22897 @item -E @var{function_name}
22898 @cindex @option{-E} (@code{gprof})
22899 The @code{-E @var{function}} option works like the @code{-e} option, but
22900 execution time spent in the function (and children who were not called from
22901 anywhere else), will not be used to compute the percentages-of-time for
22902 the call graph.  More than one @samp{-E} option may be given; only one
22903 @var{function_name} may be indicated with each @samp{-E} option.
22904
22905 @item -f @var{function_name}
22906 @cindex @option{-f} (@code{gprof})
22907 The @samp{-f @var{function}} option causes @code{gprof} to limit the
22908 call graph to the function @var{function_name} and its children (and
22909 their children@dots{}).  More than one @samp{-f} option may be given;
22910 only one @var{function_name} may be indicated with each @samp{-f}
22911 option.
22912
22913 @item -F @var{function_name}
22914 @cindex @option{-F} (@code{gprof})
22915 The @samp{-F @var{function}} option works like the @code{-f} option, but
22916 only time spent in the function and its children (and their
22917 children@dots{}) will be used to determine total-time and
22918 percentages-of-time for the call graph.  More than one @samp{-F} option
22919 may be given; only one @var{function_name} may be indicated with each
22920 @samp{-F} option.  The @samp{-F} option overrides the @samp{-E} option.
22921
22922 @end table
22923
22924 @node Interpretation of profiling results
22925 @subsection Interpretation of profiling results
22926
22927 @noindent
22928
22929 The results of the profiling analysis are represented by two arrays: the
22930 'flat profile' and the 'call graph'. Full documentation of those outputs
22931 can be found in the GNU Profiler User's Guide.
22932
22933 The flat profile shows the time spent in each function of the program, and how
22934 many time it has been called. This allows you to locate easily the most
22935 time-consuming functions.
22936
22937 The call graph shows, for each subprogram, the subprograms that call it,
22938 and the subprograms that it calls. It also provides an estimate of the time
22939 spent in each of those callers/called subprograms.
22940 @end ifclear
22941
22942 @c ******************************
22943 @node Running and Debugging Ada Programs
22944 @chapter Running and Debugging Ada Programs
22945 @cindex Debugging
22946
22947 @noindent
22948 This chapter discusses how to debug Ada programs.
22949 @ifset vms
22950 It applies to GNAT on the Alpha OpenVMS platform;
22951 for I64 OpenVMS please refer to the @cite{OpenVMS Debugger Manual},
22952 since HP has implemented Ada support in the OpenVMS debugger on I64.
22953 @end ifset
22954
22955 An incorrect Ada program may be handled in three ways by the GNAT compiler:
22956
22957 @enumerate
22958 @item
22959 The illegality may be a violation of the static semantics of Ada. In
22960 that case GNAT diagnoses the constructs in the program that are illegal.
22961 It is then a straightforward matter for the user to modify those parts of
22962 the program.
22963
22964 @item
22965 The illegality may be a violation of the dynamic semantics of Ada. In
22966 that case the program compiles and executes, but may generate incorrect
22967 results, or may terminate abnormally with some exception.
22968
22969 @item
22970 When presented with a program that contains convoluted errors, GNAT
22971 itself may terminate abnormally without providing full diagnostics on
22972 the incorrect user program.
22973 @end enumerate
22974
22975 @menu
22976 * The GNAT Debugger GDB::
22977 * Running GDB::
22978 * Introduction to GDB Commands::
22979 * Using Ada Expressions::
22980 * Calling User-Defined Subprograms::
22981 * Using the Next Command in a Function::
22982 * Ada Exceptions::
22983 * Ada Tasks::
22984 * Debugging Generic Units::
22985 * GNAT Abnormal Termination or Failure to Terminate::
22986 * Naming Conventions for GNAT Source Files::
22987 * Getting Internal Debugging Information::
22988 * Stack Traceback::
22989 @end menu
22990
22991 @cindex Debugger
22992 @findex gdb
22993
22994 @node The GNAT Debugger GDB
22995 @section The GNAT Debugger GDB
22996
22997 @noindent
22998 @code{GDB} is a general purpose, platform-independent debugger that
22999 can be used to debug mixed-language programs compiled with @command{gcc},
23000 and in particular is capable of debugging Ada programs compiled with
23001 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
23002 complex Ada data structures.
23003
23004 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
23005 @ifset vms
23006 located in the GNU:[DOCS] directory,
23007 @end ifset
23008 for full details on the usage of @code{GDB}, including a section on
23009 its usage on programs. This manual should be consulted for full
23010 details. The section that follows is a brief introduction to the
23011 philosophy and use of @code{GDB}.
23012
23013 When GNAT programs are compiled, the compiler optionally writes debugging
23014 information into the generated object file, including information on
23015 line numbers, and on declared types and variables. This information is
23016 separate from the generated code. It makes the object files considerably
23017 larger, but it does not add to the size of the actual executable that
23018 will be loaded into memory, and has no impact on run-time performance. The
23019 generation of debug information is triggered by the use of the
23020 ^-g^/DEBUG^ switch in the @command{gcc} or @command{gnatmake} command
23021 used to carry out the compilations. It is important to emphasize that
23022 the use of these options does not change the generated code.
23023
23024 The debugging information is written in standard system formats that
23025 are used by many tools, including debuggers and profilers. The format
23026 of the information is typically designed to describe C types and
23027 semantics, but GNAT implements a translation scheme which allows full
23028 details about Ada types and variables to be encoded into these
23029 standard C formats. Details of this encoding scheme may be found in
23030 the file exp_dbug.ads in the GNAT source distribution. However, the
23031 details of this encoding are, in general, of no interest to a user,
23032 since @code{GDB} automatically performs the necessary decoding.
23033
23034 When a program is bound and linked, the debugging information is
23035 collected from the object files, and stored in the executable image of
23036 the program. Again, this process significantly increases the size of
23037 the generated executable file, but it does not increase the size of
23038 the executable program itself. Furthermore, if this program is run in
23039 the normal manner, it runs exactly as if the debug information were
23040 not present, and takes no more actual memory.
23041
23042 However, if the program is run under control of @code{GDB}, the
23043 debugger is activated.  The image of the program is loaded, at which
23044 point it is ready to run.  If a run command is given, then the program
23045 will run exactly as it would have if @code{GDB} were not present. This
23046 is a crucial part of the @code{GDB} design philosophy.  @code{GDB} is
23047 entirely non-intrusive until a breakpoint is encountered.  If no
23048 breakpoint is ever hit, the program will run exactly as it would if no
23049 debugger were present. When a breakpoint is hit, @code{GDB} accesses
23050 the debugging information and can respond to user commands to inspect
23051 variables, and more generally to report on the state of execution.
23052
23053 @c **************
23054 @node Running GDB
23055 @section Running GDB
23056
23057 @noindent
23058 This section describes how to initiate the debugger.
23059 @c The above sentence is really just filler, but it was otherwise
23060 @c clumsy to get the first paragraph nonindented given the conditional
23061 @c nature of the description
23062
23063 @ifclear vms
23064 The debugger can be launched from a @code{GPS} menu or
23065 directly from the command line. The description below covers the latter use.
23066 All the commands shown can be used in the @code{GPS} debug console window,
23067 but there are usually more GUI-based ways to achieve the same effect.
23068 @end ifclear
23069
23070 The command to run @code{GDB} is
23071
23072 @smallexample
23073 $ ^gdb program^GDB PROGRAM^
23074 @end smallexample
23075
23076 @noindent
23077 where @code{^program^PROGRAM^} is the name of the executable file. This
23078 activates the debugger and results in a prompt for debugger commands.
23079 The simplest command is simply @code{run}, which causes the program to run
23080 exactly as if the debugger were not present. The following section
23081 describes some of the additional commands that can be given to @code{GDB}.
23082
23083 @c *******************************
23084 @node Introduction to GDB Commands
23085 @section Introduction to GDB Commands
23086
23087 @noindent
23088 @code{GDB} contains a large repertoire of commands.  @xref{Top,,
23089 Debugging with GDB, gdb, Debugging with GDB},
23090 @ifset vms
23091 located in the GNU:[DOCS] directory,
23092 @end ifset
23093 for extensive documentation on the use
23094 of these commands, together with examples of their use. Furthermore,
23095 the command @command{help} invoked from within GDB activates a simple help
23096 facility which summarizes the available commands and their options.
23097 In this section we summarize a few of the most commonly
23098 used commands to give an idea of what @code{GDB} is about. You should create
23099 a simple program with debugging information and experiment with the use of
23100 these @code{GDB} commands on the program as you read through the
23101 following section.
23102
23103 @table @code
23104 @item set args @var{arguments}
23105 The @var{arguments} list above is a list of arguments to be passed to
23106 the program on a subsequent run command, just as though the arguments
23107 had been entered on a normal invocation of the program. The @code{set args}
23108 command is not needed if the program does not require arguments.
23109
23110 @item run
23111 The @code{run} command causes execution of the program to start from
23112 the beginning. If the program is already running, that is to say if
23113 you are currently positioned at a breakpoint, then a prompt will ask
23114 for confirmation that you want to abandon the current execution and
23115 restart.
23116
23117 @item breakpoint @var{location}
23118 The breakpoint command sets a breakpoint, that is to say a point at which
23119 execution will halt and @code{GDB} will await further
23120 commands. @var{location} is
23121 either a line number within a file, given in the format @code{file:linenumber},
23122 or it is the name of a subprogram. If you request that a breakpoint be set on
23123 a subprogram that is overloaded, a prompt will ask you to specify on which of
23124 those subprograms you want to breakpoint. You can also
23125 specify that all of them should be breakpointed. If the program is run
23126 and execution encounters the breakpoint, then the program
23127 stops and @code{GDB} signals that the breakpoint was encountered by
23128 printing the line of code before which the program is halted.
23129
23130 @item breakpoint exception @var{name}
23131 A special form of the breakpoint command which breakpoints whenever
23132 exception @var{name} is raised.
23133 If @var{name} is omitted,
23134 then a breakpoint will occur when any exception is raised.
23135
23136 @item print @var{expression}
23137 This will print the value of the given expression. Most simple
23138 Ada expression formats are properly handled by @code{GDB}, so the expression
23139 can contain function calls, variables, operators, and attribute references.
23140
23141 @item continue
23142 Continues execution following a breakpoint, until the next breakpoint or the
23143 termination of the program.
23144
23145 @item step
23146 Executes a single line after a breakpoint. If the next statement
23147 is a subprogram call, execution continues into (the first statement of)
23148 the called subprogram.
23149
23150 @item next
23151 Executes a single line. If this line is a subprogram call, executes and
23152 returns from the call.
23153
23154 @item list
23155 Lists a few lines around the current source location. In practice, it
23156 is usually more convenient to have a separate edit window open with the
23157 relevant source file displayed. Successive applications of this command
23158 print subsequent lines. The command can be given an argument which is a
23159 line number, in which case it displays a few lines around the specified one.
23160
23161 @item backtrace
23162 Displays a backtrace of the call chain. This command is typically
23163 used after a breakpoint has occurred, to examine the sequence of calls that
23164 leads to the current breakpoint. The display includes one line for each
23165 activation record (frame) corresponding to an active subprogram.
23166
23167 @item up
23168 At a breakpoint, @code{GDB} can display the values of variables local
23169 to the current frame. The command @code{up} can be used to
23170 examine the contents of other active frames, by moving the focus up
23171 the stack, that is to say from callee to caller, one frame at a time.
23172
23173 @item down
23174 Moves the focus of @code{GDB} down from the frame currently being
23175 examined to the frame of its callee (the reverse of the previous command),
23176
23177 @item frame @var{n}
23178 Inspect the frame with the given number. The value 0 denotes the frame
23179 of the current breakpoint, that is to say the top of the call stack.
23180
23181 @end table
23182
23183 @noindent
23184 The above list is a very short introduction to the commands that
23185 @code{GDB} provides. Important additional capabilities, including conditional
23186 breakpoints, the ability to execute command sequences on a breakpoint,
23187 the ability to debug at the machine instruction level and many other
23188 features are described in detail in @ref{Top,, Debugging with GDB, gdb,
23189 Debugging with GDB}.  Note that most commands can be abbreviated
23190 (for example, c for continue, bt for backtrace).
23191
23192 @node Using Ada Expressions
23193 @section Using Ada Expressions
23194 @cindex Ada expressions
23195
23196 @noindent
23197 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
23198 extensions. The philosophy behind the design of this subset is
23199
23200 @itemize @bullet
23201 @item
23202 That @code{GDB} should provide basic literals and access to operations for
23203 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
23204 leaving more sophisticated computations to subprograms written into the
23205 program (which therefore may be called from @code{GDB}).
23206
23207 @item
23208 That type safety and strict adherence to Ada language restrictions
23209 are not particularly important to the @code{GDB} user.
23210
23211 @item
23212 That brevity is important to the @code{GDB} user.
23213 @end itemize
23214
23215 @noindent
23216 Thus, for brevity, the debugger acts as if there were
23217 implicit @code{with} and @code{use} clauses in effect for all user-written
23218 packages, thus making it unnecessary to fully qualify most names with
23219 their packages, regardless of context. Where this causes ambiguity,
23220 @code{GDB} asks the user's intent.
23221
23222 For details on the supported Ada syntax, see @ref{Top,, Debugging with
23223 GDB, gdb, Debugging with GDB}.
23224
23225 @node Calling User-Defined Subprograms
23226 @section Calling User-Defined Subprograms
23227
23228 @noindent
23229 An important capability of @code{GDB} is the ability to call user-defined
23230 subprograms while debugging. This is achieved simply by entering
23231 a subprogram call statement in the form:
23232
23233 @smallexample
23234 call subprogram-name (parameters)
23235 @end smallexample
23236
23237 @noindent
23238 The keyword @code{call} can be omitted in the normal case where the
23239 @code{subprogram-name} does not coincide with any of the predefined
23240 @code{GDB} commands.
23241
23242 The effect is to invoke the given subprogram, passing it the
23243 list of parameters that is supplied. The parameters can be expressions and
23244 can include variables from the program being debugged. The
23245 subprogram must be defined
23246 at the library level within your program, and @code{GDB} will call the
23247 subprogram within the environment of your program execution (which
23248 means that the subprogram is free to access or even modify variables
23249 within your program).
23250
23251 The most important use of this facility is in allowing the inclusion of
23252 debugging routines that are tailored to particular data structures
23253 in your program. Such debugging routines can be written to provide a suitably
23254 high-level description of an abstract type, rather than a low-level dump
23255 of its physical layout. After all, the standard
23256 @code{GDB print} command only knows the physical layout of your
23257 types, not their abstract meaning. Debugging routines can provide information
23258 at the desired semantic level and are thus enormously useful.
23259
23260 For example, when debugging GNAT itself, it is crucial to have access to
23261 the contents of the tree nodes used to represent the program internally.
23262 But tree nodes are represented simply by an integer value (which in turn
23263 is an index into a table of nodes).
23264 Using the @code{print} command on a tree node would simply print this integer
23265 value, which is not very useful. But the PN routine (defined in file
23266 treepr.adb in the GNAT sources) takes a tree node as input, and displays
23267 a useful high level representation of the tree node, which includes the
23268 syntactic category of the node, its position in the source, the integers
23269 that denote descendant nodes and parent node, as well as varied
23270 semantic information. To study this example in more detail, you might want to
23271 look at the body of the PN procedure in the stated file.
23272
23273 @node Using the Next Command in a Function
23274 @section Using the Next Command in a Function
23275
23276 @noindent
23277 When you use the @code{next} command in a function, the current source
23278 location will advance to the next statement as usual. A special case
23279 arises in the case of a @code{return} statement.
23280
23281 Part of the code for a return statement is the ``epilog'' of the function.
23282 This is the code that returns to the caller. There is only one copy of
23283 this epilog code, and it is typically associated with the last return
23284 statement in the function if there is more than one return. In some
23285 implementations, this epilog is associated with the first statement
23286 of the function.
23287
23288 The result is that if you use the @code{next} command from a return
23289 statement that is not the last return statement of the function you
23290 may see a strange apparent jump to the last return statement or to
23291 the start of the function. You should simply ignore this odd jump.
23292 The value returned is always that from the first return statement
23293 that was stepped through.
23294
23295 @node Ada Exceptions
23296 @section Breaking on Ada Exceptions
23297 @cindex Exceptions
23298
23299 @noindent
23300 You can set breakpoints that trip when your program raises
23301 selected exceptions.
23302
23303 @table @code
23304 @item break exception
23305 Set a breakpoint that trips whenever (any task in the) program raises
23306 any exception.
23307
23308 @item break exception @var{name}
23309 Set a breakpoint that trips whenever (any task in the) program raises
23310 the exception @var{name}.
23311
23312 @item break exception unhandled
23313 Set a breakpoint that trips whenever (any task in the) program raises an
23314 exception for which there is no handler.
23315
23316 @item info exceptions
23317 @itemx info exceptions @var{regexp}
23318 The @code{info exceptions} command permits the user to examine all defined
23319 exceptions within Ada programs. With a regular expression, @var{regexp}, as
23320 argument, prints out only those exceptions whose name matches @var{regexp}.
23321 @end table
23322
23323 @node Ada Tasks
23324 @section Ada Tasks
23325 @cindex Tasks
23326
23327 @noindent
23328 @code{GDB} allows the following task-related commands:
23329
23330 @table @code
23331 @item info tasks
23332 This command shows a list of current Ada tasks, as in the following example:
23333
23334 @smallexample
23335 @iftex
23336 @leftskip=0cm
23337 @end iftex
23338 (gdb) info tasks
23339   ID       TID P-ID   Thread Pri State                 Name
23340    1   8088000   0   807e000  15 Child Activation Wait main_task
23341    2   80a4000   1   80ae000  15 Accept/Select Wait    b
23342    3   809a800   1   80a4800  15 Child Activation Wait a
23343 *  4   80ae800   3   80b8000  15 Running               c
23344 @end smallexample
23345
23346 @noindent
23347 In this listing, the asterisk before the first task indicates it to be the
23348 currently running task. The first column lists the task ID that is used
23349 to refer to tasks in the following commands.
23350
23351 @item break @var{linespec} task @var{taskid}
23352 @itemx break @var{linespec} task @var{taskid} if @dots{}
23353 @cindex Breakpoints and tasks
23354 These commands are like the @code{break @dots{} thread @dots{}}.
23355 @var{linespec} specifies source lines.
23356
23357 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
23358 to specify that you only want @code{GDB} to stop the program when a
23359 particular Ada task reaches this breakpoint. @var{taskid} is one of the
23360 numeric task identifiers assigned by @code{GDB}, shown in the first
23361 column of the @samp{info tasks} display.
23362
23363 If you do not specify @samp{task @var{taskid}} when you set a
23364 breakpoint, the breakpoint applies to @emph{all} tasks of your
23365 program.
23366
23367 You can use the @code{task} qualifier on conditional breakpoints as
23368 well; in this case, place @samp{task @var{taskid}} before the
23369 breakpoint condition (before the @code{if}).
23370
23371 @item task @var{taskno}
23372 @cindex Task switching
23373
23374 This command allows to switch to the task referred by @var{taskno}. In
23375 particular, This allows to browse the backtrace of the specified
23376 task. It is advised to switch back to the original task before
23377 continuing execution otherwise the scheduling of the program may be
23378 perturbed.
23379 @end table
23380
23381 @noindent
23382 For more detailed information on the tasking support,
23383 see @ref{Top,, Debugging with GDB, gdb, Debugging with GDB}.
23384
23385 @node Debugging Generic Units
23386 @section Debugging Generic Units
23387 @cindex Debugging Generic Units
23388 @cindex Generics
23389
23390 @noindent
23391 GNAT always uses code expansion for generic instantiation. This means that
23392 each time an instantiation occurs, a complete copy of the original code is
23393 made, with appropriate substitutions of formals by actuals.
23394
23395 It is not possible to refer to the original generic entities in
23396 @code{GDB}, but it is always possible to debug a particular instance of
23397 a generic, by using the appropriate expanded names. For example, if we have
23398
23399 @smallexample @c ada
23400 @group
23401 @cartouche
23402 procedure g is
23403
23404    generic package k is
23405       procedure kp (v1 : in out integer);
23406    end k;
23407
23408    package body k is
23409       procedure kp (v1 : in out integer) is
23410       begin
23411          v1 := v1 + 1;
23412       end kp;
23413    end k;
23414
23415    package k1 is new k;
23416    package k2 is new k;
23417
23418    var : integer := 1;
23419
23420 begin
23421    k1.kp (var);
23422    k2.kp (var);
23423    k1.kp (var);
23424    k2.kp (var);
23425 end;
23426 @end cartouche
23427 @end group
23428 @end smallexample
23429
23430 @noindent
23431 Then to break on a call to procedure kp in the k2 instance, simply
23432 use the command:
23433
23434 @smallexample
23435 (gdb) break g.k2.kp
23436 @end smallexample
23437
23438 @noindent
23439 When the breakpoint occurs, you can step through the code of the
23440 instance in the normal manner and examine the values of local variables, as for
23441 other units.
23442
23443 @node GNAT Abnormal Termination or Failure to Terminate
23444 @section GNAT Abnormal Termination or Failure to Terminate
23445 @cindex GNAT Abnormal Termination or Failure to Terminate
23446
23447 @noindent
23448 When presented with programs that contain serious errors in syntax
23449 or semantics,
23450 GNAT may on rare occasions  experience problems in operation, such
23451 as aborting with a
23452 segmentation fault or illegal memory access, raising an internal
23453 exception, terminating abnormally, or failing to terminate at all.
23454 In such cases, you can activate
23455 various features of GNAT that can help you pinpoint the construct in your
23456 program that is the likely source of the problem.
23457
23458 The following strategies are presented in increasing order of
23459 difficulty, corresponding to your experience in using GNAT and your
23460 familiarity with compiler internals.
23461
23462 @enumerate
23463 @item
23464 Run @command{gcc} with the @option{-gnatf}. This first
23465 switch causes all errors on a given line to be reported. In its absence,
23466 only the first error on a line is displayed.
23467
23468 The @option{-gnatdO} switch causes errors to be displayed as soon as they
23469 are encountered, rather than after compilation is terminated. If GNAT
23470 terminates prematurely or goes into an infinite loop, the last error
23471 message displayed may help to pinpoint the culprit.
23472
23473 @item
23474 Run @command{gcc} with the @option{^-v (verbose)^/VERBOSE^} switch. In this
23475 mode, @command{gcc} produces ongoing information about the progress of the
23476 compilation and provides the name of each procedure as code is
23477 generated. This switch allows you to find which Ada procedure was being
23478 compiled when it encountered a code generation problem.
23479
23480 @item
23481 @cindex @option{-gnatdc} switch
23482 Run @command{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
23483 switch that does for the front-end what @option{^-v^VERBOSE^} does
23484 for the back end. The system prints the name of each unit,
23485 either a compilation unit or nested unit, as it is being analyzed.
23486 @item
23487 Finally, you can start
23488 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
23489 front-end of GNAT, and can be run independently (normally it is just
23490 called from @command{gcc}). You can use @code{gdb} on @code{gnat1} as you
23491 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
23492 @code{where} command is the first line of attack; the variable
23493 @code{lineno} (seen by @code{print lineno}), used by the second phase of
23494 @code{gnat1} and by the @command{gcc} backend, indicates the source line at
23495 which the execution stopped, and @code{input_file name} indicates the name of
23496 the source file.
23497 @end enumerate
23498
23499 @node Naming Conventions for GNAT Source Files
23500 @section Naming Conventions for GNAT Source Files
23501
23502 @noindent
23503 In order to examine the workings of the GNAT system, the following
23504 brief description of its organization may be helpful:
23505
23506 @itemize @bullet
23507 @item
23508 Files with prefix @file{^sc^SC^} contain the lexical scanner.
23509
23510 @item
23511 All files prefixed with @file{^par^PAR^} are components of the parser. The
23512 numbers correspond to chapters of the Ada Reference Manual. For example,
23513 parsing of select statements can be found in @file{par-ch9.adb}.
23514
23515 @item
23516 All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
23517 numbers correspond to chapters of the Ada standard. For example, all
23518 issues involving context clauses can be found in @file{sem_ch10.adb}. In
23519 addition, some features of the language require sufficient special processing
23520 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
23521 dynamic dispatching, etc.
23522
23523 @item
23524 All files prefixed with @file{^exp^EXP^} perform normalization and
23525 expansion of the intermediate representation (abstract syntax tree, or AST).
23526 these files use the same numbering scheme as the parser and semantics files.
23527 For example, the construction of record initialization procedures is done in
23528 @file{exp_ch3.adb}.
23529
23530 @item
23531 The files prefixed with @file{^bind^BIND^} implement the binder, which
23532 verifies the consistency of the compilation, determines an order of
23533 elaboration, and generates the bind file.
23534
23535 @item
23536 The files @file{atree.ads} and @file{atree.adb} detail the low-level
23537 data structures used by the front-end.
23538
23539 @item
23540 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
23541 the abstract syntax tree as produced by the parser.
23542
23543 @item
23544 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
23545 all entities, computed during semantic analysis.
23546
23547 @item
23548 Library management issues are dealt with in files with prefix
23549 @file{^lib^LIB^}.
23550
23551 @item
23552 @findex Ada
23553 @cindex Annex A
23554 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
23555 defined in Annex A.
23556
23557 @item
23558 @findex Interfaces
23559 @cindex Annex B
23560 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
23561 defined in Annex B.
23562
23563 @item
23564 @findex System
23565 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
23566 both language-defined children and GNAT run-time routines.
23567
23568 @item
23569 @findex GNAT
23570 Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
23571 general-purpose packages, fully documented in their specs. All
23572 the other @file{.c} files are modifications of common @command{gcc} files.
23573 @end itemize
23574
23575 @node Getting Internal Debugging Information
23576 @section Getting Internal Debugging Information
23577
23578 @noindent
23579 Most compilers have internal debugging switches and modes. GNAT
23580 does also, except GNAT internal debugging switches and modes are not
23581 secret. A summary and full description of all the compiler and binder
23582 debug flags are in the file @file{debug.adb}. You must obtain the
23583 sources of the compiler to see the full detailed effects of these flags.
23584
23585 The switches that print the source of the program (reconstructed from
23586 the internal tree) are of general interest for user programs, as are the
23587 options to print
23588 the full internal tree, and the entity table (the symbol table
23589 information). The reconstructed source provides a readable version of the
23590 program after the front-end has completed analysis and  expansion,
23591 and is useful when studying the performance of specific constructs.
23592 For example, constraint checks are indicated, complex aggregates
23593 are replaced with loops and assignments, and tasking primitives
23594 are replaced with run-time calls.
23595
23596 @node Stack Traceback
23597 @section Stack Traceback
23598 @cindex traceback
23599 @cindex stack traceback
23600 @cindex stack unwinding
23601
23602 @noindent
23603 Traceback is a mechanism to display the sequence of subprogram calls that
23604 leads to a specified execution point in a program. Often (but not always)
23605 the execution point is an instruction at which an exception has been raised.
23606 This mechanism is also known as @i{stack unwinding} because it obtains
23607 its information by scanning the run-time stack and recovering the activation
23608 records of all active subprograms. Stack unwinding is one of the most
23609 important tools for program debugging.
23610
23611 The first entry stored in traceback corresponds to the deepest calling level,
23612 that is to say the subprogram currently executing the instruction
23613 from which we want to obtain the traceback.
23614
23615 Note that there is no runtime performance penalty when stack traceback
23616 is enabled, and no exception is raised during program execution.
23617
23618 @menu
23619 * Non-Symbolic Traceback::
23620 * Symbolic Traceback::
23621 @end menu
23622
23623 @node Non-Symbolic Traceback
23624 @subsection Non-Symbolic Traceback
23625 @cindex traceback, non-symbolic
23626
23627 @noindent
23628 Note: this feature is not supported on all platforms. See
23629 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
23630 platforms.
23631
23632 @menu
23633 * Tracebacks From an Unhandled Exception::
23634 * Tracebacks From Exception Occurrences (non-symbolic)::
23635 * Tracebacks From Anywhere in a Program (non-symbolic)::
23636 @end menu
23637
23638 @node Tracebacks From an Unhandled Exception
23639 @subsubsection Tracebacks From an Unhandled Exception
23640
23641 @noindent
23642 A runtime non-symbolic traceback is a list of addresses of call instructions.
23643 To enable this feature you must use the @option{-E}
23644 @code{gnatbind}'s option. With this option a stack traceback is stored as part
23645 of exception information. You can retrieve this information using the
23646 @code{addr2line} tool.
23647
23648 Here is a simple example:
23649
23650 @smallexample @c ada
23651 @cartouche
23652 procedure STB is
23653
23654    procedure P1 is
23655    begin
23656       raise Constraint_Error;
23657    end P1;
23658
23659    procedure P2 is
23660    begin
23661       P1;
23662    end P2;
23663
23664 begin
23665    P2;
23666 end STB;
23667 @end cartouche
23668 @end smallexample
23669
23670 @smallexample
23671 $ gnatmake stb -bargs -E
23672 $ stb
23673
23674 Execution terminated by unhandled exception
23675 Exception name: CONSTRAINT_ERROR
23676 Message: stb.adb:5
23677 Call stack traceback locations:
23678 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
23679 @end smallexample
23680
23681 @noindent
23682 As we see the traceback lists a sequence of addresses for the unhandled
23683 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
23684 guess that this exception come from procedure P1. To translate these
23685 addresses into the source lines where the calls appear, the
23686 @code{addr2line} tool, described below, is invaluable. The use of this tool
23687 requires the program to be compiled with debug information.
23688
23689 @smallexample
23690 $ gnatmake -g stb -bargs -E
23691 $ stb
23692
23693 Execution terminated by unhandled exception
23694 Exception name: CONSTRAINT_ERROR
23695 Message: stb.adb:5
23696 Call stack traceback locations:
23697 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
23698
23699 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
23700    0x4011f1 0x77e892a4
23701
23702 00401373 at d:/stb/stb.adb:5
23703 0040138B at d:/stb/stb.adb:10
23704 0040139C at d:/stb/stb.adb:14
23705 00401335 at d:/stb/b~stb.adb:104
23706 004011C4 at /build/@dots{}/crt1.c:200
23707 004011F1 at /build/@dots{}/crt1.c:222
23708 77E892A4 in ?? at ??:0
23709 @end smallexample
23710
23711 @noindent
23712 The @code{addr2line} tool has several other useful options:
23713
23714 @table @code
23715 @item --functions
23716 to get the function name corresponding to any location
23717
23718 @item --demangle=gnat
23719 to use the gnat decoding mode for the function names. Note that
23720 for binutils version 2.9.x the option is simply @option{--demangle}.
23721 @end table
23722
23723 @smallexample
23724 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
23725    0x40139c 0x401335 0x4011c4 0x4011f1
23726
23727 00401373 in stb.p1 at d:/stb/stb.adb:5
23728 0040138B in stb.p2 at d:/stb/stb.adb:10
23729 0040139C in stb at d:/stb/stb.adb:14
23730 00401335 in main at d:/stb/b~stb.adb:104
23731 004011C4 in <__mingw_CRTStartup> at /build/@dots{}/crt1.c:200
23732 004011F1 in <mainCRTStartup> at /build/@dots{}/crt1.c:222
23733 @end smallexample
23734
23735 @noindent
23736 From this traceback we can see that the exception was raised in
23737 @file{stb.adb} at line 5, which was reached from a procedure call in
23738 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
23739 which contains the call to the main program.
23740 @xref{Running gnatbind}. The remaining entries are assorted runtime routines,
23741 and the output will vary from platform to platform.
23742
23743 It is also possible to use @code{GDB} with these traceback addresses to debug
23744 the program. For example, we can break at a given code location, as reported
23745 in the stack traceback:
23746
23747 @smallexample
23748 $ gdb -nw stb
23749 @ifclear vms
23750 @noindent
23751 Furthermore, this feature is not implemented inside Windows DLL. Only
23752 the non-symbolic traceback is reported in this case.
23753 @end ifclear
23754
23755 (gdb) break *0x401373
23756 Breakpoint 1 at 0x401373: file stb.adb, line 5.
23757 @end smallexample
23758
23759 @noindent
23760 It is important to note that the stack traceback addresses
23761 do not change when debug information is included. This is particularly useful
23762 because it makes it possible to release software without debug information (to
23763 minimize object size), get a field report that includes a stack traceback
23764 whenever an internal bug occurs, and then be able to retrieve the sequence
23765 of calls with the same program compiled with debug information.
23766
23767 @node Tracebacks From Exception Occurrences (non-symbolic)
23768 @subsubsection Tracebacks From Exception Occurrences
23769
23770 @noindent
23771 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
23772 The stack traceback is attached to the exception information string, and can
23773 be retrieved in an exception handler within the Ada program, by means of the
23774 Ada facilities defined in @code{Ada.Exceptions}. Here is a simple example:
23775
23776 @smallexample @c ada
23777 with Ada.Text_IO;
23778 with Ada.Exceptions;
23779
23780 procedure STB is
23781
23782    use Ada;
23783    use Ada.Exceptions;
23784
23785    procedure P1 is
23786       K : Positive := 1;
23787    begin
23788       K := K - 1;
23789    exception
23790       when E : others =>
23791          Text_IO.Put_Line (Exception_Information (E));
23792    end P1;
23793
23794    procedure P2 is
23795    begin
23796       P1;
23797    end P2;
23798
23799 begin
23800    P2;
23801 end STB;
23802 @end smallexample
23803
23804 @noindent
23805 This program will output:
23806
23807 @smallexample
23808 $ stb
23809
23810 Exception name: CONSTRAINT_ERROR
23811 Message: stb.adb:12
23812 Call stack traceback locations:
23813 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
23814 @end smallexample
23815
23816 @node Tracebacks From Anywhere in a Program (non-symbolic)
23817 @subsubsection Tracebacks From Anywhere in a Program
23818
23819 @noindent
23820 It is also possible to retrieve a stack traceback from anywhere in a
23821 program. For this you need to
23822 use the @code{GNAT.Traceback} API. This package includes a procedure called
23823 @code{Call_Chain} that computes a complete stack traceback, as well as useful
23824 display procedures described below. It is not necessary to use the
23825 @option{-E gnatbind} option in this case, because the stack traceback mechanism
23826 is invoked explicitly.
23827
23828 @noindent
23829 In the following example we compute a traceback at a specific location in
23830 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
23831 convert addresses to strings:
23832
23833 @smallexample @c ada
23834 with Ada.Text_IO;
23835 with GNAT.Traceback;
23836 with GNAT.Debug_Utilities;
23837
23838 procedure STB is
23839
23840    use Ada;
23841    use GNAT;
23842    use GNAT.Traceback;
23843
23844    procedure P1 is
23845       TB  : Tracebacks_Array (1 .. 10);
23846       --  We are asking for a maximum of 10 stack frames.
23847       Len : Natural;
23848       --  Len will receive the actual number of stack frames returned.
23849    begin
23850       Call_Chain (TB, Len);
23851
23852       Text_IO.Put ("In STB.P1 : ");
23853
23854       for K in 1 .. Len loop
23855          Text_IO.Put (Debug_Utilities.Image (TB (K)));
23856          Text_IO.Put (' ');
23857       end loop;
23858
23859       Text_IO.New_Line;
23860    end P1;
23861
23862    procedure P2 is
23863    begin
23864       P1;
23865    end P2;
23866
23867 begin
23868    P2;
23869 end STB;
23870 @end smallexample
23871
23872 @smallexample
23873 $ gnatmake -g stb
23874 $ stb
23875
23876 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
23877 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
23878 @end smallexample
23879
23880 @noindent
23881 You can then get further information by invoking the @code{addr2line}
23882 tool as described earlier (note that the hexadecimal addresses
23883 need to be specified in C format, with a leading ``0x'').
23884
23885 @node Symbolic Traceback
23886 @subsection Symbolic Traceback
23887 @cindex traceback, symbolic
23888
23889 @noindent
23890 A symbolic traceback is a stack traceback in which procedure names are
23891 associated with each code location.
23892
23893 @noindent
23894 Note that this feature is not supported on all platforms. See
23895 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
23896 list of currently supported platforms.
23897
23898 @noindent
23899 Note that the symbolic traceback requires that the program be compiled
23900 with debug information. If it is not compiled with debug information
23901 only the non-symbolic information will be valid.
23902
23903 @menu
23904 * Tracebacks From Exception Occurrences (symbolic)::
23905 * Tracebacks From Anywhere in a Program (symbolic)::
23906 @end menu
23907
23908 @node Tracebacks From Exception Occurrences (symbolic)
23909 @subsubsection Tracebacks From Exception Occurrences
23910
23911 @smallexample @c ada
23912 with Ada.Text_IO;
23913 with GNAT.Traceback.Symbolic;
23914
23915 procedure STB is
23916
23917    procedure P1 is
23918    begin
23919       raise Constraint_Error;
23920    end P1;
23921
23922    procedure P2 is
23923    begin
23924       P1;
23925    end P2;
23926
23927    procedure P3 is
23928    begin
23929       P2;
23930    end P3;
23931
23932 begin
23933    P3;
23934 exception
23935    when E : others =>
23936       Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
23937 end STB;
23938 @end smallexample
23939
23940 @smallexample
23941 $ gnatmake -g .\stb -bargs -E -largs -lgnat -laddr2line -lintl
23942 $ stb
23943
23944 0040149F in stb.p1 at stb.adb:8
23945 004014B7 in stb.p2 at stb.adb:13
23946 004014CF in stb.p3 at stb.adb:18
23947 004015DD in ada.stb at stb.adb:22
23948 00401461 in main at b~stb.adb:168
23949 004011C4 in __mingw_CRTStartup at crt1.c:200
23950 004011F1 in mainCRTStartup at crt1.c:222
23951 77E892A4 in ?? at ??:0
23952 @end smallexample
23953
23954 @noindent
23955 In the above example the ``.\'' syntax in the @command{gnatmake} command
23956 is currently required by @command{addr2line} for files that are in
23957 the current working directory.
23958 Moreover, the exact sequence of linker options may vary from platform
23959 to platform.
23960 The above @option{-largs} section is for Windows platforms. By contrast,
23961 under Unix there is no need for the @option{-largs} section.
23962 Differences across platforms are due to details of linker implementation.
23963
23964 @node Tracebacks From Anywhere in a Program (symbolic)
23965 @subsubsection Tracebacks From Anywhere in a Program
23966
23967 @noindent
23968 It is possible to get a symbolic stack traceback
23969 from anywhere in a program, just as for non-symbolic tracebacks.
23970 The first step is to obtain a non-symbolic
23971 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
23972 information. Here is an example:
23973
23974 @smallexample @c ada
23975 with Ada.Text_IO;
23976 with GNAT.Traceback;
23977 with GNAT.Traceback.Symbolic;
23978
23979 procedure STB is
23980
23981    use Ada;
23982    use GNAT.Traceback;
23983    use GNAT.Traceback.Symbolic;
23984
23985    procedure P1 is
23986       TB  : Tracebacks_Array (1 .. 10);
23987       --  We are asking for a maximum of 10 stack frames.
23988       Len : Natural;
23989       --  Len will receive the actual number of stack frames returned.
23990    begin
23991       Call_Chain (TB, Len);
23992       Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
23993    end P1;
23994
23995    procedure P2 is
23996    begin
23997       P1;
23998    end P2;
23999
24000 begin
24001    P2;
24002 end STB;
24003 @end smallexample
24004
24005 @c ******************************
24006 @ifset vms
24007 @node Compatibility with HP Ada
24008 @chapter Compatibility with HP Ada
24009 @cindex Compatibility
24010
24011 @noindent
24012 @cindex DEC Ada
24013 @cindex HP Ada
24014 @cindex Compatibility between GNAT and HP Ada
24015 This chapter compares HP Ada (formerly known as ``DEC Ada'')
24016 for OpenVMS Alpha and GNAT for OpenVMS for Alpha and for I64.
24017 GNAT is highly compatible
24018 with HP Ada, and it should generally be straightforward to port code
24019 from the HP Ada environment to GNAT. However, there are a few language
24020 and implementation differences of which the user must be aware. These
24021 differences are discussed in this chapter. In
24022 addition, the operating environment and command structure for the
24023 compiler are different, and these differences are also discussed.
24024
24025 For further details on these and other compatibility issues,
24026 see Appendix E of the HP publication
24027 @cite{HP Ada, Technical Overview and Comparison on HP Platforms}.
24028
24029 Except where otherwise indicated, the description of GNAT for OpenVMS
24030 applies to both the Alpha and I64 platforms.
24031
24032 For information on porting Ada code from GNAT on Alpha OpenVMS to GNAT on
24033 I64 OpenVMS, see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
24034
24035 The discussion in this chapter addresses specifically the implementation
24036 of Ada 83 for HP OpenVMS Alpha Systems. In cases where the implementation
24037 of HP Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems,
24038 GNAT always follows the Alpha implementation.
24039
24040 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
24041 attributes are recognized, although only a subset of them can sensibly
24042 be implemented.  The description of pragmas in
24043 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual}
24044 indicates whether or not they are applicable to non-VMS systems.
24045
24046 @menu
24047 * Ada Language Compatibility::
24048 * Differences in the Definition of Package System::
24049 * Language-Related Features::
24050 * The Package STANDARD::
24051 * The Package SYSTEM::
24052 * Tasking and Task-Related Features::
24053 * Pragmas and Pragma-Related Features::
24054 * Library of Predefined Units::
24055 * Bindings::
24056 * Main Program Definition::
24057 * Implementation-Defined Attributes::
24058 * Compiler and Run-Time Interfacing::
24059 * Program Compilation and Library Management::
24060 * Input-Output::
24061 * Implementation Limits::
24062 * Tools and Utilities::
24063 @end menu
24064
24065 @node Ada Language Compatibility
24066 @section Ada Language Compatibility
24067
24068 @noindent
24069 GNAT handles Ada 95 and Ada 2005 as well as Ada 83, whereas HP Ada is only
24070 for Ada 83. Ada 95 and Ada 2005 are almost completely upwards compatible
24071 with Ada 83, and therefore Ada 83 programs will compile
24072 and run under GNAT with
24073 no changes or only minor changes. The @cite{Annotated Ada Reference Manual}
24074 provides details on specific incompatibilities.
24075
24076 GNAT provides the switch @option{/83} on the @command{GNAT COMPILE} command,
24077 as well as the pragma @code{ADA_83}, to force the compiler to
24078 operate in Ada 83 mode. This mode does not guarantee complete
24079 conformance to Ada 83, but in practice is sufficient to
24080 eliminate most sources of incompatibilities.
24081 In particular, it eliminates the recognition of the
24082 additional Ada 95 and Ada 2005 keywords, so that their use as identifiers
24083 in Ada 83 programs is legal, and handles the cases of packages
24084 with optional bodies, and generics that instantiate unconstrained
24085 types without the use of @code{(<>)}.
24086
24087 @node Differences in the Definition of Package System
24088 @section Differences in the Definition of Package @code{System}
24089
24090 @noindent
24091 An Ada compiler is allowed to add
24092 implementation-dependent declarations to package @code{System}.
24093 In normal mode,
24094 GNAT does not take advantage of this permission, and the version of
24095 @code{System} provided by GNAT exactly matches that defined in the Ada
24096 Reference Manual.
24097
24098 However, HP Ada adds an extensive set of declarations to package
24099 @code{System},
24100 as fully documented in the HP Ada manuals. To minimize changes required
24101 for programs that make use of these extensions, GNAT provides the pragma
24102 @code{Extend_System} for extending the definition of package System. By using:
24103 @cindex pragma @code{Extend_System}
24104 @cindex @code{Extend_System} pragma
24105
24106 @smallexample @c ada
24107 @group
24108 @cartouche
24109 pragma Extend_System (Aux_DEC);
24110 @end cartouche
24111 @end group
24112 @end smallexample
24113
24114 @noindent
24115 the set of definitions in @code{System} is extended to include those in
24116 package @code{System.Aux_DEC}.
24117 @cindex @code{System.Aux_DEC} package
24118 @cindex @code{Aux_DEC} package (child of @code{System})
24119 These definitions are incorporated directly into package @code{System},
24120 as though they had been declared there. For a
24121 list of the declarations added, see the spec of this package,
24122 which can be found in the file @file{s-auxdec.ads} in the GNAT library.
24123 @cindex @file{s-auxdec.ads} file
24124 The pragma @code{Extend_System} is a configuration pragma, which means that
24125 it can be placed in the file @file{gnat.adc}, so that it will automatically
24126 apply to all subsequent compilations. See @ref{Configuration Pragmas},
24127 for further details.
24128
24129 An alternative approach that avoids the use of the non-standard
24130 @code{Extend_System} pragma is to add a context clause to the unit that
24131 references these facilities:
24132
24133 @smallexample @c ada
24134 @cartouche
24135 with System.Aux_DEC;
24136 use  System.Aux_DEC;
24137 @end cartouche
24138 @end smallexample
24139
24140 @noindent
24141 The effect is not quite semantically identical to incorporating
24142 the declarations directly into package @code{System},
24143 but most programs will not notice a difference
24144 unless they use prefix notation (e.g.@: @code{System.Integer_8})
24145 to reference the entities directly in package @code{System}.
24146 For units containing such references,
24147 the prefixes must either be removed, or the pragma @code{Extend_System}
24148 must be used.
24149
24150 @node Language-Related Features
24151 @section Language-Related Features
24152
24153 @noindent
24154 The following sections highlight differences in types,
24155 representations of types, operations, alignment, and
24156 related topics.
24157
24158 @menu
24159 * Integer Types and Representations::
24160 * Floating-Point Types and Representations::
24161 * Pragmas Float_Representation and Long_Float::
24162 * Fixed-Point Types and Representations::
24163 * Record and Array Component Alignment::
24164 * Address Clauses::
24165 * Other Representation Clauses::
24166 @end menu
24167
24168 @node Integer Types and Representations
24169 @subsection Integer Types and Representations
24170
24171 @noindent
24172 The set of predefined integer types is identical in HP Ada and GNAT.
24173 Furthermore the representation of these integer types is also identical,
24174 including the capability of size clauses forcing biased representation.
24175
24176 In addition,
24177 HP Ada for OpenVMS Alpha systems has defined the
24178 following additional integer types in package @code{System}:
24179
24180 @itemize @bullet
24181
24182 @item
24183 @code{INTEGER_8}
24184
24185 @item
24186 @code{INTEGER_16}
24187
24188 @item
24189 @code{INTEGER_32}
24190
24191 @item
24192 @code{INTEGER_64}
24193
24194 @item
24195 @code{LARGEST_INTEGER}
24196 @end itemize
24197
24198 @noindent
24199 In GNAT, the first four of these types may be obtained from the
24200 standard Ada package @code{Interfaces}.
24201 Alternatively, by use of the pragma @code{Extend_System}, identical
24202 declarations can be referenced directly in package @code{System}.
24203 On both GNAT and HP Ada, the maximum integer size is 64 bits.
24204
24205 @node Floating-Point Types and Representations
24206 @subsection Floating-Point Types and Representations
24207 @cindex Floating-Point types
24208
24209 @noindent
24210 The set of predefined floating-point types is identical in HP Ada and GNAT.
24211 Furthermore the representation of these floating-point
24212 types is also identical. One important difference is that the default
24213 representation for HP Ada is @code{VAX_Float}, but the default representation
24214 for GNAT is IEEE.
24215
24216 Specific types may be declared to be @code{VAX_Float} or IEEE, using the
24217 pragma @code{Float_Representation} as described in the HP Ada
24218 documentation.
24219 For example, the declarations:
24220
24221 @smallexample @c ada
24222 @cartouche
24223 type F_Float is digits 6;
24224 pragma Float_Representation (VAX_Float, F_Float);
24225 @end cartouche
24226 @end smallexample
24227
24228 @noindent
24229 declares a type @code{F_Float} that will be represented in @code{VAX_Float}
24230 format.
24231 This set of declarations actually appears in @code{System.Aux_DEC},
24232 which contains
24233 the full set of additional floating-point declarations provided in
24234 the HP Ada version of package @code{System}.
24235 This and similar declarations may be accessed in a user program
24236 by using pragma @code{Extend_System}. The use of this
24237 pragma, and the related pragma @code{Long_Float} is described in further
24238 detail in the following section.
24239
24240 @node Pragmas Float_Representation and Long_Float
24241 @subsection Pragmas @code{Float_Representation} and @code{Long_Float}
24242
24243 @noindent
24244 HP Ada provides the pragma @code{Float_Representation}, which
24245 acts as a program library switch to allow control over
24246 the internal representation chosen for the predefined
24247 floating-point types declared in the package @code{Standard}.
24248 The format of this pragma is as follows:
24249
24250 @smallexample @c ada
24251 @cartouche
24252 pragma Float_Representation(VAX_Float | IEEE_Float);
24253 @end cartouche
24254 @end smallexample
24255
24256 @noindent
24257 This pragma controls the representation of floating-point
24258 types as follows:
24259
24260 @itemize @bullet
24261 @item
24262 @code{VAX_Float} specifies that floating-point
24263 types are represented by default with the VAX system hardware types
24264 @code{F-floating}, @code{D-floating}, @code{G-floating}.
24265 Note that the @code{H-floating}
24266 type was available only on VAX systems, and is not available
24267 in either HP Ada or GNAT.
24268
24269 @item
24270 @code{IEEE_Float} specifies that floating-point
24271 types are represented by default with the IEEE single and
24272 double floating-point types.
24273 @end itemize
24274
24275 @noindent
24276 GNAT provides an identical implementation of the pragma
24277 @code{Float_Representation}, except that it functions as a
24278 configuration pragma. Note that the
24279 notion of configuration pragma corresponds closely to the
24280 HP Ada notion of a program library switch.
24281
24282 When no pragma is used in GNAT, the default is @code{IEEE_Float},
24283 which is different
24284 from HP Ada 83, where the default is @code{VAX_Float}. In addition, the
24285 predefined libraries in GNAT are built using @code{IEEE_Float}, so it is not
24286 advisable to change the format of numbers passed to standard library
24287 routines, and if necessary explicit type conversions may be needed.
24288
24289 The use of @code{IEEE_Float} is recommended in GNAT since it is more
24290 efficient, and (given that it conforms to an international standard)
24291 potentially more portable.
24292 The situation in which @code{VAX_Float} may be useful is in interfacing
24293 to existing code and data that expect the use of @code{VAX_Float}.
24294 In such a situation use the predefined @code{VAX_Float}
24295 types in package @code{System}, as extended by
24296 @code{Extend_System}. For example, use @code{System.F_Float}
24297 to specify the 32-bit @code{F-Float} format.
24298
24299 @noindent
24300 On OpenVMS systems, HP Ada provides the pragma @code{Long_Float}
24301 to allow control over the internal representation chosen
24302 for the predefined type @code{Long_Float} and for floating-point
24303 type declarations with digits specified in the range 7 .. 15.
24304 The format of this pragma is as follows:
24305
24306 @smallexample @c ada
24307 @cartouche
24308 pragma Long_Float (D_FLOAT | G_FLOAT);
24309 @end cartouche
24310 @end smallexample
24311
24312 @node Fixed-Point Types and Representations
24313 @subsection Fixed-Point Types and Representations
24314
24315 @noindent
24316 On HP Ada for OpenVMS Alpha systems, rounding is
24317 away from zero for both positive and negative numbers.
24318 Therefore, @code{+0.5} rounds to @code{1},
24319 and @code{-0.5} rounds to @code{-1}.
24320
24321 On GNAT the results of operations
24322 on fixed-point types are in accordance with the Ada
24323 rules. In particular, results of operations on decimal
24324 fixed-point types are truncated.
24325
24326 @node Record and Array Component Alignment
24327 @subsection Record and Array Component Alignment
24328
24329 @noindent
24330 On HP Ada for OpenVMS Alpha, all non-composite components
24331 are aligned on natural boundaries. For example, 1-byte
24332 components are aligned on byte boundaries, 2-byte
24333 components on 2-byte boundaries, 4-byte components on 4-byte
24334 byte boundaries, and so on. The OpenVMS Alpha hardware
24335 runs more efficiently with naturally aligned data.
24336
24337 On GNAT, alignment rules are compatible
24338 with HP Ada for OpenVMS Alpha.
24339
24340 @node Address Clauses
24341 @subsection Address Clauses
24342
24343 @noindent
24344 In HP Ada and GNAT, address clauses are supported for
24345 objects and imported subprograms.
24346 The predefined type @code{System.Address} is a private type
24347 in both compilers on Alpha OpenVMS, with the same representation
24348 (it is simply a machine pointer). Addition, subtraction, and comparison
24349 operations are available in the standard Ada package
24350 @code{System.Storage_Elements}, or in package @code{System}
24351 if it is extended to include @code{System.Aux_DEC} using a
24352 pragma @code{Extend_System} as previously described.
24353
24354 Note that code that @code{with}'s both this extended package @code{System}
24355 and the package @code{System.Storage_Elements} should not @code{use}
24356 both packages, or ambiguities will result. In general it is better
24357 not to mix these two sets of facilities. The Ada package was
24358 designed specifically to provide the kind of features that HP Ada
24359 adds directly to package @code{System}.
24360
24361 The type @code{System.Address} is a 64-bit integer type in GNAT for
24362 I64 OpenVMS.  For more information,
24363 see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
24364
24365 GNAT is compatible with HP Ada in its handling of address
24366 clauses, except for some limitations in
24367 the form of address clauses for composite objects with
24368 initialization. Such address clauses are easily replaced
24369 by the use of an explicitly-defined constant as described
24370 in the Ada Reference Manual (13.1(22)). For example, the sequence
24371 of declarations:
24372
24373 @smallexample @c ada
24374 @cartouche
24375 X, Y : Integer := Init_Func;
24376 Q : String (X .. Y) := "abc";
24377 @dots{}
24378 for Q'Address use Compute_Address;
24379 @end cartouche
24380 @end smallexample
24381
24382 @noindent
24383 will be rejected by GNAT, since the address cannot be computed at the time
24384 that @code{Q} is declared. To achieve the intended effect, write instead:
24385
24386 @smallexample @c ada
24387 @group
24388 @cartouche
24389 X, Y : Integer := Init_Func;
24390 Q_Address : constant Address := Compute_Address;
24391 Q : String (X .. Y) := "abc";
24392 @dots{}
24393 for Q'Address use Q_Address;
24394 @end cartouche
24395 @end group
24396 @end smallexample
24397
24398 @noindent
24399 which will be accepted by GNAT (and other Ada compilers), and is also
24400 compatible with Ada 83. A fuller description of the restrictions
24401 on address specifications is found in @ref{Top, GNAT Reference Manual,
24402 About This Guide, gnat_rm, GNAT Reference Manual}.
24403
24404 @node Other Representation Clauses
24405 @subsection Other Representation Clauses
24406
24407 @noindent
24408 GNAT implements in a compatible manner all the representation
24409 clauses supported by HP Ada. In addition, GNAT
24410 implements the representation clause forms that were introduced in Ada 95,
24411 including @code{COMPONENT_SIZE} and @code{SIZE} clauses for objects.
24412
24413 @node The Package STANDARD
24414 @section The Package @code{STANDARD}
24415
24416 @noindent
24417 The package @code{STANDARD}, as implemented by HP Ada, is fully
24418 described in the @cite{Ada Reference Manual} and in the
24419 @cite{HP Ada Language Reference Manual}. As implemented by GNAT, the
24420 package @code{STANDARD} is described in the @cite{Ada Reference Manual}.
24421
24422 In addition, HP Ada supports the Latin-1 character set in
24423 the type @code{CHARACTER}. GNAT supports the Latin-1 character set
24424 in the type @code{CHARACTER} and also Unicode (ISO 10646 BMP) in
24425 the type @code{WIDE_CHARACTER}.
24426
24427 The floating-point types supported by GNAT are those
24428 supported by HP Ada, but the defaults are different, and are controlled by
24429 pragmas. See @ref{Floating-Point Types and Representations}, for details.
24430
24431 @node The Package SYSTEM
24432 @section The Package @code{SYSTEM}
24433
24434 @noindent
24435 HP Ada provides a specific version of the package
24436 @code{SYSTEM} for each platform on which the language is implemented.
24437 For the complete spec of the package @code{SYSTEM}, see
24438 Appendix F of the @cite{HP Ada Language Reference Manual}.
24439
24440 On HP Ada, the package @code{SYSTEM} includes the following conversion
24441 functions:
24442 @itemize @bullet
24443 @item @code{TO_ADDRESS(INTEGER)}
24444
24445 @item @code{TO_ADDRESS(UNSIGNED_LONGWORD)}
24446
24447 @item @code{TO_ADDRESS(}@i{universal_integer}@code{)}
24448
24449 @item @code{TO_INTEGER(ADDRESS)}
24450
24451 @item @code{TO_UNSIGNED_LONGWORD(ADDRESS)}
24452
24453 @item Function @code{IMPORT_VALUE return UNSIGNED_LONGWORD} and the
24454 functions @code{IMPORT_ADDRESS} and @code{IMPORT_LARGEST_VALUE}
24455 @end itemize
24456
24457 @noindent
24458 By default, GNAT supplies a version of @code{SYSTEM} that matches
24459 the definition given in the @cite{Ada Reference Manual}.
24460 This
24461 is a subset of the HP system definitions, which is as
24462 close as possible to the original definitions. The only difference
24463 is that the definition of @code{SYSTEM_NAME} is different:
24464
24465 @smallexample @c ada
24466 @cartouche
24467 type Name is (SYSTEM_NAME_GNAT);
24468 System_Name : constant Name := SYSTEM_NAME_GNAT;
24469 @end cartouche
24470 @end smallexample
24471
24472 @noindent
24473 Also, GNAT adds the Ada declarations for
24474 @code{BIT_ORDER} and @code{DEFAULT_BIT_ORDER}.
24475
24476 However, the use of the following pragma causes GNAT
24477 to extend the definition of package @code{SYSTEM} so that it
24478 encompasses the full set of HP-specific extensions,
24479 including the functions listed above:
24480
24481 @smallexample @c ada
24482 @cartouche
24483 pragma Extend_System (Aux_DEC);
24484 @end cartouche
24485 @end smallexample
24486
24487 @noindent
24488 The pragma @code{Extend_System} is a configuration pragma that
24489 is most conveniently placed in the @file{gnat.adc} file. @xref{Pragma
24490 Extend_System,,, gnat_rm, GNAT Reference Manual} for further details.
24491
24492 HP Ada does not allow the recompilation of the package
24493 @code{SYSTEM}. Instead HP Ada provides several pragmas
24494 (@code{SYSTEM_NAME}, @code{STORAGE_UNIT}, and @code{MEMORY_SIZE})
24495 to modify values in the package @code{SYSTEM}.
24496 On OpenVMS Alpha systems, the pragma
24497 @code{SYSTEM_NAME} takes the enumeration literal @code{OPENVMS_AXP} as
24498 its single argument.
24499
24500 GNAT does permit the recompilation of package @code{SYSTEM} using
24501 the special switch @option{-gnatg}, and this switch can be used if
24502 it is necessary to modify the definitions in @code{SYSTEM}. GNAT does
24503 not permit the specification of @code{SYSTEM_NAME}, @code{STORAGE_UNIT}
24504 or @code{MEMORY_SIZE} by any other means.
24505
24506 On GNAT systems, the pragma @code{SYSTEM_NAME} takes the
24507 enumeration literal @code{SYSTEM_NAME_GNAT}.
24508
24509 The definitions provided by the use of
24510
24511 @smallexample @c ada
24512 pragma Extend_System (AUX_Dec);
24513 @end smallexample
24514
24515 @noindent
24516 are virtually identical to those provided by the HP Ada 83 package
24517 @code{SYSTEM}. One important difference is that the name of the
24518 @code{TO_ADDRESS}
24519 function for type @code{UNSIGNED_LONGWORD} is changed to
24520 @code{TO_ADDRESS_LONG}.
24521 @xref{Address Clauses,,, gnat_rm, GNAT Reference Manual} for a
24522 discussion of why this change was necessary.
24523
24524 @noindent
24525 The version of @code{TO_ADDRESS} taking a @i{universal_integer} argument
24526 is in fact
24527 an extension to Ada 83 not strictly compatible with the reference manual.
24528 GNAT, in order to be exactly compatible with the standard,
24529 does not provide this capability. In HP Ada 83, the
24530 point of this definition is to deal with a call like:
24531
24532 @smallexample @c ada
24533 TO_ADDRESS (16#12777#);
24534 @end smallexample
24535
24536 @noindent
24537 Normally, according to Ada 83 semantics, one would expect this to be
24538 ambiguous, since it matches both the @code{INTEGER} and
24539 @code{UNSIGNED_LONGWORD} forms of @code{TO_ADDRESS}.
24540 However, in HP Ada 83, there is no ambiguity, since the
24541 definition using @i{universal_integer} takes precedence.
24542
24543 In GNAT, since the version with @i{universal_integer} cannot be supplied,
24544 it is
24545 not possible to be 100% compatible. Since there are many programs using
24546 numeric constants for the argument to @code{TO_ADDRESS}, the decision in
24547 GNAT was
24548 to change the name of the function in the @code{UNSIGNED_LONGWORD} case,
24549 so the declarations provided in the GNAT version of @code{AUX_Dec} are:
24550
24551 @smallexample @c ada
24552 function To_Address (X : Integer) return Address;
24553 pragma Pure_Function (To_Address);
24554
24555 function To_Address_Long (X : Unsigned_Longword) return Address;
24556 pragma Pure_Function (To_Address_Long);
24557 @end smallexample
24558
24559 @noindent
24560 This means that programs using @code{TO_ADDRESS} for
24561 @code{UNSIGNED_LONGWORD} must change the name to @code{TO_ADDRESS_LONG}.
24562
24563 @node Tasking and Task-Related Features
24564 @section Tasking and Task-Related Features
24565
24566 @noindent
24567 This section compares the treatment of tasking in GNAT
24568 and in HP Ada for OpenVMS Alpha.
24569 The GNAT description applies to both Alpha and I64 OpenVMS.
24570 For detailed information on tasking in
24571 HP Ada, see the @cite{HP Ada Language Reference Manual} and the
24572 relevant run-time reference manual.
24573
24574 @menu
24575 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
24576 * Assigning Task IDs::
24577 * Task IDs and Delays::
24578 * Task-Related Pragmas::
24579 * Scheduling and Task Priority::
24580 * The Task Stack::
24581 * External Interrupts::
24582 @end menu
24583
24584 @node Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
24585 @subsection Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
24586
24587 @noindent
24588 On OpenVMS Alpha systems, each Ada task (except a passive
24589 task) is implemented as a single stream of execution
24590 that is created and managed by the kernel. On these
24591 systems, HP Ada tasking support is based on DECthreads,
24592 an implementation of the POSIX standard for threads.
24593
24594 Also, on OpenVMS Alpha systems, HP Ada tasks and foreign
24595 code that calls DECthreads routines can be used together.
24596 The interaction between Ada tasks and DECthreads routines
24597 can have some benefits. For example when on OpenVMS Alpha,
24598 HP Ada can call C code that is already threaded.
24599
24600 GNAT uses the facilities of DECthreads,
24601 and Ada tasks are mapped to threads.
24602
24603 @node Assigning Task IDs
24604 @subsection Assigning Task IDs
24605
24606 @noindent
24607 The HP Ada Run-Time Library always assigns @code{%TASK 1} to
24608 the environment task that executes the main program. On
24609 OpenVMS Alpha systems, @code{%TASK 0} is often used for tasks
24610 that have been created but are not yet activated.
24611
24612 On OpenVMS Alpha systems, task IDs are assigned at
24613 activation. On GNAT systems, task IDs are also assigned at
24614 task creation but do not have the same form or values as
24615 task ID values in HP Ada. There is no null task, and the
24616 environment task does not have a specific task ID value.
24617
24618 @node Task IDs and Delays
24619 @subsection Task IDs and Delays
24620
24621 @noindent
24622 On OpenVMS Alpha systems, tasking delays are implemented
24623 using Timer System Services. The Task ID is used for the
24624 identification of the timer request (the @code{REQIDT} parameter).
24625 If Timers are used in the application take care not to use
24626 @code{0} for the identification, because cancelling such a timer
24627 will cancel all timers and may lead to unpredictable results.
24628
24629 @node Task-Related Pragmas
24630 @subsection Task-Related Pragmas
24631
24632 @noindent
24633 Ada supplies the pragma @code{TASK_STORAGE}, which allows
24634 specification of the size of the guard area for a task
24635 stack. (The guard area forms an area of memory that has no
24636 read or write access and thus helps in the detection of
24637 stack overflow.) On OpenVMS Alpha systems, if the pragma
24638 @code{TASK_STORAGE} specifies a value of zero, a minimal guard
24639 area is created. In the absence of a pragma @code{TASK_STORAGE},
24640 a default guard area is created.
24641
24642 GNAT supplies the following task-related pragmas:
24643
24644 @itemize @bullet
24645 @item  @code{TASK_INFO}
24646
24647 This pragma appears within a task definition and
24648 applies to the task in which it appears. The argument
24649 must be of type @code{SYSTEM.TASK_INFO.TASK_INFO_TYPE}.
24650
24651 @item  @code{TASK_STORAGE}
24652
24653 GNAT implements pragma @code{TASK_STORAGE} in the same way as HP Ada.
24654 Both HP Ada and GNAT supply the pragmas @code{PASSIVE},
24655 @code{SUPPRESS}, and @code{VOLATILE}.
24656 @end itemize
24657 @node Scheduling and Task Priority
24658 @subsection Scheduling and Task Priority
24659
24660 @noindent
24661 HP Ada implements the Ada language requirement that
24662 when two tasks are eligible for execution and they have
24663 different priorities, the lower priority task does not
24664 execute while the higher priority task is waiting. The HP
24665 Ada Run-Time Library keeps a task running until either the
24666 task is suspended or a higher priority task becomes ready.
24667
24668 On OpenVMS Alpha systems, the default strategy is round-
24669 robin with preemption. Tasks of equal priority take turns
24670 at the processor. A task is run for a certain period of
24671 time and then placed at the tail of the ready queue for
24672 its priority level.
24673
24674 HP Ada provides the implementation-defined pragma @code{TIME_SLICE},
24675 which can be used to enable or disable round-robin
24676 scheduling of tasks with the same priority.
24677 See the relevant HP Ada run-time reference manual for
24678 information on using the pragmas to control HP Ada task
24679 scheduling.
24680
24681 GNAT follows the scheduling rules of Annex D (Real-Time
24682 Annex) of the @cite{Ada Reference Manual}. In general, this
24683 scheduling strategy is fully compatible with HP Ada
24684 although it provides some additional constraints (as
24685 fully documented in Annex D).
24686 GNAT implements time slicing control in a manner compatible with
24687 HP Ada 83, by means of the pragma @code{Time_Slice}, whose semantics
24688 are identical to the HP Ada 83 pragma of the same name.
24689 Note that it is not possible to mix GNAT tasking and
24690 HP Ada 83 tasking in the same program, since the two run-time
24691 libraries are not compatible.
24692
24693 @node The Task Stack
24694 @subsection The Task Stack
24695
24696 @noindent
24697 In HP Ada, a task stack is allocated each time a
24698 non-passive task is activated. As soon as the task is
24699 terminated, the storage for the task stack is deallocated.
24700 If you specify a size of zero (bytes) with @code{T'STORAGE_SIZE},
24701 a default stack size is used. Also, regardless of the size
24702 specified, some additional space is allocated for task
24703 management purposes. On OpenVMS Alpha systems, at least
24704 one page is allocated.
24705
24706 GNAT handles task stacks in a similar manner. In accordance with
24707 the Ada rules, it provides the pragma @code{STORAGE_SIZE} as
24708 an alternative method for controlling the task stack size.
24709 The specification of the attribute @code{T'STORAGE_SIZE} is also
24710 supported in a manner compatible with HP Ada.
24711
24712 @node External Interrupts
24713 @subsection External Interrupts
24714
24715 @noindent
24716 On HP Ada, external interrupts can be associated with task entries.
24717 GNAT is compatible with HP Ada in its handling of external interrupts.
24718
24719 @node Pragmas and Pragma-Related Features
24720 @section Pragmas and Pragma-Related Features
24721
24722 @noindent
24723 Both HP Ada and GNAT supply all language-defined pragmas
24724 as specified by the Ada 83 standard. GNAT also supplies all
24725 language-defined pragmas introduced by Ada 95 and Ada 2005.
24726 In addition, GNAT implements the implementation-defined pragmas
24727 from HP Ada 83.
24728
24729 @itemize @bullet
24730 @item  @code{AST_ENTRY}
24731
24732 @item  @code{COMMON_OBJECT}
24733
24734 @item  @code{COMPONENT_ALIGNMENT}
24735
24736 @item  @code{EXPORT_EXCEPTION}
24737
24738 @item  @code{EXPORT_FUNCTION}
24739
24740 @item  @code{EXPORT_OBJECT}
24741
24742 @item  @code{EXPORT_PROCEDURE}
24743
24744 @item  @code{EXPORT_VALUED_PROCEDURE}
24745
24746 @item  @code{FLOAT_REPRESENTATION}
24747
24748 @item  @code{IDENT}
24749
24750 @item  @code{IMPORT_EXCEPTION}
24751
24752 @item  @code{IMPORT_FUNCTION}
24753
24754 @item  @code{IMPORT_OBJECT}
24755
24756 @item  @code{IMPORT_PROCEDURE}
24757
24758 @item  @code{IMPORT_VALUED_PROCEDURE}
24759
24760 @item  @code{INLINE_GENERIC}
24761
24762 @item  @code{INTERFACE_NAME}
24763
24764 @item  @code{LONG_FLOAT}
24765
24766 @item  @code{MAIN_STORAGE}
24767
24768 @item  @code{PASSIVE}
24769
24770 @item  @code{PSECT_OBJECT}
24771
24772 @item  @code{SHARE_GENERIC}
24773
24774 @item  @code{SUPPRESS_ALL}
24775
24776 @item  @code{TASK_STORAGE}
24777
24778 @item  @code{TIME_SLICE}
24779
24780 @item  @code{TITLE}
24781 @end itemize
24782
24783 @noindent
24784 These pragmas are all fully implemented, with the exception of @code{TITLE},
24785 @code{PASSIVE}, and @code{SHARE_GENERIC}, which are
24786 recognized, but which have no
24787 effect in GNAT. The effect of @code{PASSIVE} may be obtained by the
24788 use of Ada protected objects. In GNAT, all generics are inlined.
24789
24790 Unlike HP Ada, the GNAT ``@code{EXPORT_}@i{subprogram}'' pragmas require
24791 a separate subprogram specification which must appear before the
24792 subprogram body.
24793
24794 GNAT also supplies a number of implementation-defined pragmas as follows:
24795 @itemize @bullet
24796 @item  @code{ABORT_DEFER}
24797
24798 @item  @code{ADA_83}
24799
24800 @item  @code{ADA_95}
24801
24802 @item  @code{ADA_05}
24803
24804 @item  @code{ANNOTATE}
24805
24806 @item  @code{ASSERT}
24807
24808 @item  @code{C_PASS_BY_COPY}
24809
24810 @item  @code{CPP_CLASS}
24811
24812 @item  @code{CPP_CONSTRUCTOR}
24813
24814 @item  @code{CPP_DESTRUCTOR}
24815
24816 @item  @code{DEBUG}
24817
24818 @item  @code{EXTEND_SYSTEM}
24819
24820 @item  @code{LINKER_ALIAS}
24821
24822 @item  @code{LINKER_SECTION}
24823
24824 @item  @code{MACHINE_ATTRIBUTE}
24825
24826 @item  @code{NO_RETURN}
24827
24828 @item  @code{PURE_FUNCTION}
24829
24830 @item  @code{SOURCE_FILE_NAME}
24831
24832 @item  @code{SOURCE_REFERENCE}
24833
24834 @item  @code{TASK_INFO}
24835
24836 @item  @code{UNCHECKED_UNION}
24837
24838 @item  @code{UNIMPLEMENTED_UNIT}
24839
24840 @item  @code{UNIVERSAL_DATA}
24841
24842 @item  @code{UNSUPPRESS}
24843
24844 @item  @code{WARNINGS}
24845
24846 @item  @code{WEAK_EXTERNAL}
24847 @end itemize
24848
24849 @noindent
24850 For full details on these GNAT implementation-defined pragmas,
24851 see @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference
24852 Manual}.
24853
24854 @menu
24855 * Restrictions on the Pragma INLINE::
24856 * Restrictions on the Pragma INTERFACE::
24857 * Restrictions on the Pragma SYSTEM_NAME::
24858 @end menu
24859
24860 @node Restrictions on the Pragma INLINE
24861 @subsection Restrictions on Pragma @code{INLINE}
24862
24863 @noindent
24864 HP Ada enforces the following restrictions on the pragma @code{INLINE}:
24865 @itemize @bullet
24866 @item  Parameters cannot have a task type.
24867
24868 @item  Function results cannot be task types, unconstrained
24869 array types, or unconstrained types with discriminants.
24870
24871 @item  Bodies cannot declare the following:
24872 @itemize @bullet
24873 @item  Subprogram body or stub (imported subprogram is allowed)
24874
24875 @item  Tasks
24876
24877 @item  Generic declarations
24878
24879 @item  Instantiations
24880
24881 @item  Exceptions
24882
24883 @item  Access types (types derived from access types allowed)
24884
24885 @item  Array or record types
24886
24887 @item  Dependent tasks
24888
24889 @item  Direct recursive calls of subprogram or containing
24890 subprogram, directly or via a renaming
24891
24892 @end itemize
24893 @end itemize
24894
24895 @noindent
24896 In GNAT, the only restriction on pragma @code{INLINE} is that the
24897 body must occur before the call if both are in the same
24898 unit, and the size must be appropriately small. There are
24899 no other specific restrictions which cause subprograms to
24900 be incapable of being inlined.
24901
24902 @node  Restrictions on the Pragma INTERFACE
24903 @subsection  Restrictions on Pragma @code{INTERFACE}
24904
24905 @noindent
24906 The following restrictions on pragma @code{INTERFACE}
24907 are enforced by both HP Ada and GNAT:
24908 @itemize @bullet
24909 @item  Languages accepted: Ada, Bliss, C, Fortran, Default.
24910 Default is the default on OpenVMS Alpha systems.
24911
24912 @item  Parameter passing: Language specifies default
24913 mechanisms but can be overridden with an @code{EXPORT} pragma.
24914
24915 @itemize @bullet
24916 @item  Ada: Use internal Ada rules.
24917
24918 @item  Bliss, C: Parameters must be mode @code{in}; cannot be
24919 record or task type. Result cannot be a string, an
24920 array, or a record.
24921
24922 @item  Fortran: Parameters cannot have a task type. Result cannot
24923 be a string, an array, or a record.
24924 @end itemize
24925 @end itemize
24926
24927 @noindent
24928 GNAT is entirely upwards compatible with HP Ada, and in addition allows
24929 record parameters for all languages.
24930
24931 @node  Restrictions on the Pragma SYSTEM_NAME
24932 @subsection  Restrictions on Pragma @code{SYSTEM_NAME}
24933
24934 @noindent
24935 For HP Ada for OpenVMS Alpha, the enumeration literal
24936 for the type @code{NAME} is @code{OPENVMS_AXP}.
24937 In GNAT, the enumeration
24938 literal for the type @code{NAME} is @code{SYSTEM_NAME_GNAT}.
24939
24940 @node  Library of Predefined Units
24941 @section  Library of Predefined Units
24942
24943 @noindent
24944 A library of predefined units is provided as part of the
24945 HP Ada and GNAT implementations. HP Ada does not provide
24946 the package @code{MACHINE_CODE} but instead recommends importing
24947 assembler code.
24948
24949 The GNAT versions of the HP Ada Run-Time Library (@code{ADA$PREDEFINED:})
24950 units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
24951 version.
24952 The HP Ada Predefined Library units are modified to remove post-Ada 83
24953 incompatibilities and to make them interoperable with GNAT
24954 (@pxref{Changes to DECLIB}, for details).
24955 The units are located in the @file{DECLIB} directory.
24956
24957 The GNAT RTL is contained in
24958 the @file{ADALIB} directory, and
24959 the default search path is set up to find @code{DECLIB} units in preference
24960 to @code{ADALIB} units with the same name (@code{TEXT_IO},
24961 @code{SEQUENTIAL_IO}, and @code{DIRECT_IO}, for example).
24962
24963 @menu
24964 * Changes to DECLIB::
24965 @end menu
24966
24967 @node Changes to DECLIB
24968 @subsection Changes to @code{DECLIB}
24969
24970 @noindent
24971 The changes made to the HP Ada predefined library for GNAT and post-Ada 83
24972 compatibility are minor and include the following:
24973
24974 @itemize @bullet
24975 @item  Adjusting the location of pragmas and record representation
24976 clauses to obey Ada 95 (and thus Ada 2005) rules
24977
24978 @item  Adding the proper notation to generic formal parameters
24979 that take unconstrained types in instantiation
24980
24981 @item  Adding pragma @code{ELABORATE_BODY} to package specs
24982 that have package bodies not otherwise allowed
24983
24984 @item  Replacing occurrences of the identifier ``@code{PROTECTED}'' by
24985 ``@code{PROTECTD}''.
24986 Currently these are found only in the @code{STARLET} package spec.
24987
24988 @item Changing @code{SYSTEM.ADDRESS} to @code{SYSTEM.SHORT_ADDRESS}
24989 where the address size is constrained to 32 bits.
24990 @end itemize
24991
24992 @noindent
24993 None of the above changes is visible to users.
24994
24995 @node Bindings
24996 @section Bindings
24997
24998 @noindent
24999 On OpenVMS Alpha, HP Ada provides the following strongly-typed bindings:
25000 @itemize @bullet
25001
25002 @item  Command Language Interpreter (CLI interface)
25003
25004 @item  DECtalk Run-Time Library (DTK interface)
25005
25006 @item  Librarian utility routines (LBR interface)
25007
25008 @item  General Purpose Run-Time Library (LIB interface)
25009
25010 @item  Math Run-Time Library (MTH interface)
25011
25012 @item  National Character Set Run-Time Library (NCS interface)
25013
25014 @item  Compiled Code Support Run-Time Library (OTS interface)
25015
25016 @item  Parallel Processing Run-Time Library (PPL interface)
25017
25018 @item  Screen Management Run-Time Library (SMG interface)
25019
25020 @item  Sort Run-Time Library (SOR interface)
25021
25022 @item  String Run-Time Library (STR interface)
25023
25024 @item STARLET System Library
25025 @findex Starlet
25026
25027 @item  X Window System Version 11R4 and 11R5 (X, XLIB interface)
25028
25029 @item  X Windows Toolkit (XT interface)
25030
25031 @item  X/Motif Version 1.1.3 and 1.2 (XM interface)
25032 @end itemize
25033
25034 @noindent
25035 GNAT provides implementations of these HP bindings in the @code{DECLIB}
25036 directory, on both the Alpha and I64 OpenVMS platforms.
25037
25038 The X/Motif bindings used to build @code{DECLIB} are whatever versions are
25039 in the
25040 HP Ada @file{ADA$PREDEFINED} directory with extension @file{.ADC}.
25041 A pragma @code{Linker_Options} has been added to packages @code{Xm},
25042 @code{Xt}, and @code{X_Lib}
25043 causing the default X/Motif sharable image libraries to be linked in. This
25044 is done via options files named @file{xm.opt}, @file{xt.opt}, and
25045 @file{x_lib.opt} (also located in the @file{DECLIB} directory).
25046
25047 It may be necessary to edit these options files to update or correct the
25048 library names if, for example, the newer X/Motif bindings from
25049 @file{ADA$EXAMPLES}
25050 had been (previous to installing GNAT) copied and renamed to supersede the
25051 default @file{ADA$PREDEFINED} versions.
25052
25053 @menu
25054 * Shared Libraries and Options Files::
25055 * Interfaces to C::
25056 @end menu
25057
25058 @node Shared Libraries and Options Files
25059 @subsection Shared Libraries and Options Files
25060
25061 @noindent
25062 When using the HP Ada
25063 predefined X and Motif bindings, the linking with their sharable images is
25064 done automatically by @command{GNAT LINK}.
25065 When using other X and Motif bindings, you need
25066 to add the corresponding sharable images to the command line for
25067 @code{GNAT LINK}. When linking with shared libraries, or with
25068 @file{.OPT} files, you must
25069 also add them to the command line for @command{GNAT LINK}.
25070
25071 A shared library to be used with GNAT is built in the same way as other
25072 libraries under VMS. The VMS Link command can be used in standard fashion.
25073
25074 @node Interfaces to C
25075 @subsection Interfaces to C
25076
25077 @noindent
25078 HP Ada
25079 provides the following Ada types and operations:
25080
25081 @itemize @bullet
25082 @item C types package (@code{C_TYPES})
25083
25084 @item C strings (@code{C_TYPES.NULL_TERMINATED})
25085
25086 @item Other_types (@code{SHORT_INT})
25087 @end itemize
25088
25089 @noindent
25090 Interfacing to C with GNAT, you can use the above approach
25091 described for HP Ada or the facilities of Annex B of
25092 the @cite{Ada Reference Manual} (packages @code{INTERFACES.C},
25093 @code{INTERFACES.C.STRINGS} and @code{INTERFACES.C.POINTERS}). For more
25094 information, see @ref{Interfacing to C,,, gnat_rm, GNAT Reference Manual}.
25095
25096 The @option{-gnatF} qualifier forces default and explicit
25097 @code{External_Name} parameters in pragmas @code{Import} and @code{Export}
25098 to be uppercased for compatibility with the default behavior
25099 of HP C. The qualifier has no effect on @code{Link_Name} parameters.
25100
25101 @node Main Program Definition
25102 @section Main Program Definition
25103
25104 @noindent
25105 The following section discusses differences in the
25106 definition of main programs on HP Ada and GNAT.
25107 On HP Ada, main programs are defined to meet the
25108 following conditions:
25109 @itemize @bullet
25110 @item  Procedure with no formal parameters (returns @code{0} upon
25111 normal completion)
25112
25113 @item  Procedure with no formal parameters (returns @code{42} when
25114 an unhandled exception is raised)
25115
25116 @item  Function with no formal parameters whose returned value
25117 is of a discrete type
25118
25119 @item  Procedure with one @code{out} formal of a discrete type for
25120 which a specification of pragma @code{EXPORT_VALUED_PROCEDURE} is given.
25121
25122 @end itemize
25123
25124 @noindent
25125 When declared with the pragma @code{EXPORT_VALUED_PROCEDURE},
25126 a main function or main procedure returns a discrete
25127 value whose size is less than 64 bits (32 on VAX systems),
25128 the value is zero- or sign-extended as appropriate.
25129 On GNAT, main programs are defined as follows:
25130 @itemize @bullet
25131 @item  Must be a non-generic, parameterless subprogram that
25132 is either a procedure or function returning an Ada
25133 @code{STANDARD.INTEGER} (the predefined type)
25134
25135 @item  Cannot be a generic subprogram or an instantiation of a
25136 generic subprogram
25137 @end itemize
25138
25139 @node Implementation-Defined Attributes
25140 @section Implementation-Defined Attributes
25141
25142 @noindent
25143 GNAT provides all HP Ada implementation-defined
25144 attributes.
25145
25146 @node Compiler and Run-Time Interfacing
25147 @section Compiler and Run-Time Interfacing
25148
25149 @noindent
25150 HP Ada provides the following qualifiers to pass options to the linker
25151 (ACS LINK):
25152 @itemize @bullet
25153 @item  @option{/WAIT} and @option{/SUBMIT}
25154
25155 @item  @option{/COMMAND}
25156
25157 @item  @option{/@r{[}NO@r{]}MAP}
25158
25159 @item  @option{/OUTPUT=@var{file-spec}}
25160
25161 @item  @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
25162 @end itemize
25163
25164 @noindent
25165 To pass options to the linker, GNAT provides the following
25166 switches:
25167
25168 @itemize @bullet
25169 @item   @option{/EXECUTABLE=@var{exec-name}}
25170
25171 @item   @option{/VERBOSE}
25172
25173 @item   @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
25174 @end itemize
25175
25176 @noindent
25177 For more information on these switches, see
25178 @ref{Switches for gnatlink}.
25179 In HP Ada, the command-line switch @option{/OPTIMIZE} is available
25180 to control optimization. HP Ada also supplies the
25181 following pragmas:
25182 @itemize @bullet
25183 @item  @code{OPTIMIZE}
25184
25185 @item  @code{INLINE}
25186
25187 @item  @code{INLINE_GENERIC}
25188
25189 @item  @code{SUPPRESS_ALL}
25190
25191 @item  @code{PASSIVE}
25192 @end itemize
25193
25194 @noindent
25195 In GNAT, optimization is controlled strictly by command
25196 line parameters, as described in the corresponding section of this guide.
25197 The HP pragmas for control of optimization are
25198 recognized but ignored.
25199
25200 Note that in GNAT, the default is optimization off, whereas in HP Ada
25201 the default is that optimization is turned on.
25202
25203 @node Program Compilation and Library Management
25204 @section Program Compilation and Library Management
25205
25206 @noindent
25207 HP Ada and GNAT provide a comparable set of commands to
25208 build programs. HP Ada also provides a program library,
25209 which is a concept that does not exist on GNAT. Instead,
25210 GNAT provides directories of sources that are compiled as
25211 needed.
25212
25213 The following table summarizes
25214 the HP Ada commands and provides
25215 equivalent GNAT commands. In this table, some GNAT
25216 equivalents reflect the fact that GNAT does not use the
25217 concept of a program library. Instead, it uses a model
25218 in which collections of source and object files are used
25219 in a manner consistent with other languages like C and
25220 Fortran. Therefore, standard system file commands are used
25221 to manipulate these elements. Those GNAT commands are marked with
25222 an asterisk.
25223 Note that, unlike HP Ada, none of the GNAT commands accepts wild cards.
25224
25225 @need 1500
25226 @multitable @columnfractions .35 .65
25227
25228 @item @emph{HP Ada Command}
25229 @tab @emph{GNAT Equivalent / Description}
25230
25231 @item @command{ADA}
25232 @tab @command{GNAT COMPILE}@*
25233 Invokes the compiler to compile one or more Ada source files.
25234
25235 @item @command{ACS ATTACH}@*
25236 @tab [No equivalent]@*
25237 Switches control of terminal from current process running the program
25238 library manager.
25239
25240 @item @command{ACS CHECK}
25241 @tab @command{GNAT MAKE /DEPENDENCY_LIST}@*
25242 Forms the execution closure of one
25243 or more compiled units and checks completeness and currency.
25244
25245 @item @command{ACS COMPILE}
25246 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
25247 Forms the execution closure of one or
25248 more specified units, checks completeness and currency,
25249 identifies units that have revised source files, compiles same,
25250 and recompiles units that are or will become obsolete.
25251 Also completes incomplete generic instantiations.
25252
25253 @item @command{ACS COPY FOREIGN}
25254 @tab Copy (*)@*
25255 Copies a foreign object file into the program library as a
25256 library unit body.
25257
25258 @item @command{ACS COPY UNIT}
25259 @tab Copy (*)@*
25260 Copies a compiled unit from one program library to another.
25261
25262 @item @command{ACS CREATE LIBRARY}
25263 @tab Create /directory (*)@*
25264 Creates a program library.
25265
25266 @item @command{ACS CREATE SUBLIBRARY}
25267 @tab Create /directory (*)@*
25268 Creates a program sublibrary.
25269
25270 @item @command{ACS DELETE LIBRARY}
25271 @tab @*
25272 Deletes a program library and its contents.
25273
25274 @item @command{ACS DELETE SUBLIBRARY}
25275 @tab @*
25276 Deletes a program sublibrary and its contents.
25277
25278 @item @command{ACS DELETE UNIT}
25279 @tab Delete file (*)@*
25280 On OpenVMS systems, deletes one or more compiled units from
25281 the current program library.
25282
25283 @item @command{ACS DIRECTORY}
25284 @tab Directory (*)@*
25285 On OpenVMS systems, lists units contained in the current
25286 program library.
25287
25288 @item @command{ACS ENTER FOREIGN}
25289 @tab Copy (*)@*
25290 Allows the import of a foreign body as an Ada library
25291 spec and enters a reference to a pointer.
25292
25293 @item @command{ACS ENTER UNIT}
25294 @tab Copy (*)@*
25295 Enters a reference (pointer) from the current program library to
25296 a unit compiled into another program library.
25297
25298 @item @command{ACS EXIT}
25299 @tab [No equivalent]@*
25300 Exits from the program library manager.
25301
25302 @item @command{ACS EXPORT}
25303 @tab Copy (*)@*
25304 Creates an object file that contains system-specific object code
25305 for one or more units. With GNAT, object files can simply be copied
25306 into the desired directory.
25307
25308 @item @command{ACS EXTRACT SOURCE}
25309 @tab Copy (*)@*
25310 Allows access to the copied source file for each Ada compilation unit
25311
25312 @item @command{ACS HELP}
25313 @tab @command{HELP GNAT}@*
25314 Provides online help.
25315
25316 @item @command{ACS LINK}
25317 @tab @command{GNAT LINK}@*
25318 Links an object file containing Ada units into an executable file.
25319
25320 @item @command{ACS LOAD}
25321 @tab Copy (*)@*
25322 Loads (partially compiles) Ada units into the program library.
25323 Allows loading a program from a collection of files into a library
25324 without knowing the relationship among units.
25325
25326 @item @command{ACS MERGE}
25327 @tab Copy (*)@*
25328 Merges into the current program library, one or more units from
25329 another library where they were modified.
25330
25331 @item @command{ACS RECOMPILE}
25332 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
25333 Recompiles from   external or copied source files any obsolete
25334 unit in the closure. Also, completes any incomplete generic
25335 instantiations.
25336
25337 @item @command{ACS REENTER}
25338 @tab @command{GNAT MAKE}@*
25339 Reenters current references to units compiled after last entered
25340 with the @command{ACS ENTER UNIT} command.
25341
25342 @item @command{ACS SET LIBRARY}
25343 @tab Set default (*)@*
25344 Defines a program library to be the compilation context as well
25345 as the target library for compiler output and commands in general.
25346
25347 @item @command{ACS SET PRAGMA}
25348 @tab Edit @file{gnat.adc} (*)@*
25349 Redefines specified  values of the library characteristics
25350 @code{LONG_ FLOAT}, @code{MEMORY_SIZE}, @code{SYSTEM_NAME},
25351 and @code{Float_Representation}.
25352
25353 @item @command{ACS SET SOURCE}
25354 @tab Define @code{ADA_INCLUDE_PATH} path (*)@*
25355 Defines the source file search list for the @command{ACS COMPILE} command.
25356
25357 @item @command{ACS SHOW LIBRARY}
25358 @tab Directory (*)@*
25359 Lists information about one or more program libraries.
25360
25361 @item @command{ACS SHOW PROGRAM}
25362 @tab [No equivalent]@*
25363 Lists information about the execution closure of one or
25364 more units in the program library.
25365
25366 @item @command{ACS SHOW SOURCE}
25367 @tab Show logical @code{ADA_INCLUDE_PATH}@*
25368 Shows the source file search used when compiling units.
25369
25370 @item @command{ACS SHOW VERSION}
25371 @tab Compile with @option{VERBOSE} option
25372 Displays the version number of the compiler and program library
25373 manager used.
25374
25375 @item @command{ACS SPAWN}
25376 @tab [No equivalent]@*
25377 Creates a subprocess of the current process (same as @command{DCL SPAWN}
25378 command).
25379
25380 @item @command{ACS VERIFY}
25381 @tab [No equivalent]@*
25382 Performs a series of consistency checks on a program library to
25383 determine whether the library structure and library files are in
25384 valid form.
25385 @end multitable
25386
25387 @noindent
25388
25389 @node Input-Output
25390 @section Input-Output
25391
25392 @noindent
25393 On OpenVMS Alpha systems, HP Ada uses OpenVMS Record
25394 Management Services (RMS) to perform operations on
25395 external files.
25396
25397 @noindent
25398 HP Ada and GNAT predefine an identical set of input-
25399 output packages. To make the use of the
25400 generic @code{TEXT_IO} operations more convenient, HP Ada
25401 provides predefined library packages that instantiate the
25402 integer and floating-point operations for the predefined
25403 integer and floating-point types as shown in the following table.
25404
25405 @multitable @columnfractions .45 .55
25406 @item @emph{Package Name} @tab Instantiation
25407
25408 @item @code{INTEGER_TEXT_IO}
25409 @tab @code{INTEGER_IO(INTEGER)}
25410
25411 @item @code{SHORT_INTEGER_TEXT_IO}
25412 @tab @code{INTEGER_IO(SHORT_INTEGER)}
25413
25414 @item @code{SHORT_SHORT_INTEGER_TEXT_IO}
25415 @tab @code{INTEGER_IO(SHORT_SHORT_INTEGER)}
25416
25417 @item @code{FLOAT_TEXT_IO}
25418 @tab @code{FLOAT_IO(FLOAT)}
25419
25420 @item @code{LONG_FLOAT_TEXT_IO}
25421 @tab @code{FLOAT_IO(LONG_FLOAT)}
25422 @end multitable
25423
25424 @noindent
25425 The HP Ada predefined packages and their operations
25426 are implemented using OpenVMS Alpha files and input-output
25427 facilities. HP Ada supports asynchronous input-output on OpenVMS Alpha.
25428 Familiarity with the following is recommended:
25429 @itemize @bullet
25430 @item  RMS file organizations and access methods
25431
25432 @item  OpenVMS file specifications and directories
25433
25434 @item  OpenVMS File Definition Language (FDL)
25435 @end itemize
25436
25437 @noindent
25438 GNAT provides I/O facilities that are completely
25439 compatible with HP Ada. The distribution includes the
25440 standard HP Ada versions of all I/O packages, operating
25441 in a manner compatible with HP Ada. In particular, the
25442 following packages are by default the HP Ada (Ada 83)
25443 versions of these packages rather than the renamings
25444 suggested in Annex J of the Ada Reference Manual:
25445 @itemize @bullet
25446 @item  @code{TEXT_IO}
25447
25448 @item  @code{SEQUENTIAL_IO}
25449
25450 @item  @code{DIRECT_IO}
25451 @end itemize
25452
25453 @noindent
25454 The use of the standard child package syntax (for
25455 example, @code{ADA.TEXT_IO}) retrieves the post-Ada 83 versions of these
25456 packages.
25457 GNAT provides HP-compatible predefined instantiations
25458 of the @code{TEXT_IO} packages, and also
25459 provides the standard predefined instantiations required
25460 by the @cite{Ada Reference Manual}.
25461
25462 For further information on how GNAT interfaces to the file
25463 system or how I/O is implemented in programs written in
25464 mixed languages, see @ref{Implementation of the Standard I/O,,,
25465 gnat_rm, GNAT Reference Manual}.
25466 This chapter covers the following:
25467 @itemize @bullet
25468 @item  Standard I/O packages
25469
25470 @item  @code{FORM} strings
25471
25472 @item  @code{ADA.DIRECT_IO}
25473
25474 @item  @code{ADA.SEQUENTIAL_IO}
25475
25476 @item  @code{ADA.TEXT_IO}
25477
25478 @item  Stream pointer positioning
25479
25480 @item  Reading and writing non-regular files
25481
25482 @item  @code{GET_IMMEDIATE}
25483
25484 @item  Treating @code{TEXT_IO} files as streams
25485
25486 @item  Shared files
25487
25488 @item  Open modes
25489 @end itemize
25490
25491 @node Implementation Limits
25492 @section Implementation Limits
25493
25494 @noindent
25495 The following table lists implementation limits for HP Ada
25496 and GNAT systems.
25497 @multitable @columnfractions .60 .20 .20
25498 @sp 1
25499 @item  @emph{Compilation Parameter}
25500 @tab   @emph{HP Ada}
25501 @tab   @emph{GNAT}
25502 @sp 1
25503
25504 @item  In a subprogram or entry  declaration, maximum number of
25505 formal parameters that are of an unconstrained record type
25506 @tab   32
25507 @tab   No set limit
25508 @sp 1
25509
25510 @item  Maximum identifier length (number of characters)
25511 @tab   255
25512 @tab   32766
25513 @sp 1
25514
25515 @item  Maximum number of characters in a source line
25516 @tab   255
25517 @tab   32766
25518 @sp 1
25519
25520 @item  Maximum collection size   (number of bytes)
25521 @tab   2**31-1
25522 @tab   2**31-1
25523 @sp 1
25524
25525 @item  Maximum number of discriminants for a record type
25526 @tab   245
25527 @tab   No set limit
25528 @sp 1
25529
25530 @item  Maximum number of formal parameters in an entry or
25531 subprogram declaration
25532 @tab   246
25533 @tab    No set limit
25534 @sp 1
25535
25536 @item  Maximum number of dimensions in an array type
25537 @tab   255
25538 @tab   No set limit
25539 @sp 1
25540
25541 @item  Maximum number of library  units and subunits in a compilation.
25542 @tab   4095
25543 @tab   No set limit
25544 @sp 1
25545
25546 @item  Maximum number of library units and subunits in an execution.
25547 @tab   16383
25548 @tab   No set limit
25549 @sp 1
25550
25551 @item  Maximum number of objects declared with the pragma @code{COMMON_OBJECT}
25552 or @code{PSECT_OBJECT}
25553 @tab   32757
25554 @tab   No set limit
25555 @sp 1
25556
25557 @item  Maximum number of enumeration literals in an enumeration type
25558 definition
25559 @tab   65535
25560 @tab   No set limit
25561 @sp 1
25562
25563 @item  Maximum number of lines in a source file
25564 @tab   65534
25565 @tab   No set limit
25566 @sp 1
25567
25568 @item  Maximum number of bits in any object
25569 @tab   2**31-1
25570 @tab   2**31-1
25571 @sp 1
25572
25573 @item  Maximum size of the static portion of a stack frame (approximate)
25574 @tab   2**31-1
25575 @tab   2**31-1
25576 @end multitable
25577
25578 @node Tools and Utilities
25579 @section Tools and Utilities
25580
25581 @noindent
25582 The following table lists some of the OpenVMS development tools
25583 available for HP Ada, and the corresponding tools for
25584 use with @value{EDITION} on Alpha and I64 platforms.
25585 Aside from the debugger, all the OpenVMS tools identified are part
25586 of the DECset package.
25587
25588 @iftex
25589 @c Specify table in TeX since Texinfo does a poor job
25590 @tex
25591 \smallskip
25592 \smallskip
25593 \settabs\+Language-Sensitive Editor\quad
25594    &Product with HP Ada\quad
25595    &\cr
25596 \+\it Tool
25597    &\it Product with HP Ada
25598    & \it Product with GNAT Pro\cr
25599 \smallskip
25600 \+Code Management System
25601    &HP CMS
25602    & HP CMS\cr
25603 \smallskip
25604 \+Language-Sensitive Editor
25605    &HP LSE
25606    & emacs or HP LSE (Alpha)\cr
25607 \+
25608    &
25609    & HP LSE (I64)\cr
25610 \smallskip
25611 \+Debugger
25612    &OpenVMS Debug
25613    & gdb (Alpha),\cr
25614 \+
25615    &
25616    & OpenVMS Debug (I64)\cr
25617 \smallskip
25618 \+Source Code Analyzer /
25619    &HP SCA
25620    & GNAT XREF\cr
25621 \+Cross Referencer
25622    &
25623    &\cr
25624 \smallskip
25625 \+Test Manager
25626    &HP Digital Test
25627    & HP DTM\cr
25628 \+
25629    &Manager (DTM)
25630    &\cr
25631 \smallskip
25632 \+Performance and
25633    & HP PCA
25634    & HP PCA\cr
25635 \+Coverage Analyzer
25636    &
25637    &\cr
25638 \smallskip
25639 \+Module Management
25640    & HP MMS
25641    & Not applicable\cr
25642 \+ System
25643    &
25644    &\cr
25645 \smallskip
25646 \smallskip
25647 @end tex
25648 @end iftex
25649
25650 @ifnottex
25651 @c This is the Texinfo version of the table.  It renders poorly in pdf, hence
25652 @c the TeX version above for the printed version
25653 @flushleft
25654 @c @multitable @columnfractions .3 .4 .4
25655 @multitable {Source Code Analyzer /}{Tool with HP Ada}{Tool with GNAT Pro}
25656 @item @i{Tool}
25657 @tab @i{Tool with HP Ada}
25658 @tab @i{Tool with @value{EDITION}}
25659 @item Code Management@*System
25660 @tab HP CMS
25661 @tab HP CMS
25662 @item Language-Sensitive@*Editor
25663 @tab HP LSE
25664 @tab emacs or HP LSE (Alpha)
25665 @item
25666 @tab
25667 @tab HP LSE (I64)
25668 @item Debugger
25669 @tab OpenVMS Debug
25670 @tab gdb (Alpha),
25671 @item
25672 @tab
25673 @tab OpenVMS Debug (I64)
25674 @item Source Code Analyzer /@*Cross Referencer
25675 @tab HP SCA
25676 @tab GNAT XREF
25677 @item Test Manager
25678 @tab HP Digital Test@*Manager (DTM)
25679 @tab HP DTM
25680 @item Performance and@*Coverage Analyzer
25681 @tab HP PCA
25682 @tab HP PCA
25683 @item Module Management@*System
25684 @tab HP MMS
25685 @tab Not applicable
25686 @end multitable
25687 @end flushleft
25688 @end ifnottex
25689
25690 @end ifset
25691
25692 @c **************************************
25693 @node Platform-Specific Information for the Run-Time Libraries
25694 @appendix Platform-Specific Information for the Run-Time Libraries
25695 @cindex Tasking and threads libraries
25696 @cindex Threads libraries and tasking
25697 @cindex Run-time libraries (platform-specific information)
25698
25699 @noindent
25700 The GNAT run-time implementation may vary with respect to both the
25701 underlying threads library and the exception handling scheme.
25702 For threads support, one or more of the following are supplied:
25703 @itemize @bullet
25704 @item @b{native threads library}, a binding to the thread package from
25705 the underlying operating system
25706
25707 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
25708 POSIX thread package
25709 @end itemize
25710
25711 @noindent
25712 For exception handling, either or both of two models are supplied:
25713 @itemize @bullet
25714 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
25715 Most programs should experience a substantial speed improvement by
25716 being compiled with a ZCX run-time.
25717 This is especially true for
25718 tasking applications or applications with many exception handlers.}
25719 @cindex Zero-Cost Exceptions
25720 @cindex ZCX (Zero-Cost Exceptions)
25721 which uses binder-generated tables that
25722 are interrogated at run time to locate a handler
25723
25724 @item @b{setjmp / longjmp} (``SJLJ''),
25725 @cindex setjmp/longjmp Exception Model
25726 @cindex SJLJ (setjmp/longjmp Exception Model)
25727 which uses dynamically-set data to establish
25728 the set of handlers
25729 @end itemize
25730
25731 @noindent
25732 This appendix summarizes which combinations of threads and exception support
25733 are supplied on various GNAT platforms.
25734 It then shows how to select a particular library either
25735 permanently or temporarily,
25736 explains the properties of (and tradeoffs among) the various threads
25737 libraries, and provides some additional
25738 information about several specific platforms.
25739
25740 @menu
25741 * Summary of Run-Time Configurations::
25742 * Specifying a Run-Time Library::
25743 * Choosing the Scheduling Policy::
25744 * Solaris-Specific Considerations::
25745 * Linux-Specific Considerations::
25746 * AIX-Specific Considerations::
25747 * Irix-Specific Considerations::
25748 * RTX-Specific Considerations::
25749 @end menu
25750
25751 @node Summary of Run-Time Configurations
25752 @section Summary of Run-Time Configurations
25753
25754 @multitable @columnfractions .30 .70
25755 @item @b{alpha-openvms}
25756 @item @code{@ @ }@i{rts-native (default)}
25757 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
25758 @item @code{@ @ @ @ }Exceptions @tab ZCX
25759 @*
25760 @item @b{alpha-tru64}
25761 @item @code{@ @ }@i{rts-native (default)}
25762 @item @code{@ @ @ @ }Tasking    @tab native TRU64 threads
25763 @item @code{@ @ @ @ }Exceptions @tab ZCX
25764 @*
25765 @item @code{@ @ }@i{rts-sjlj}
25766 @item @code{@ @ @ @ }Tasking    @tab native TRU64 threads
25767 @item @code{@ @ @ @ }Exceptions @tab SJLJ
25768 @*
25769 @item @b{ia64-hp_linux}
25770 @item @code{@ @ }@i{rts-native (default)}
25771 @item @code{@ @ @ @ }Tasking    @tab pthread library
25772 @item @code{@ @ @ @ }Exceptions @tab ZCX
25773 @*
25774 @item @b{ia64-hpux}
25775 @item @code{@ @ }@i{rts-native (default)}
25776 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
25777 @item @code{@ @ @ @ }Exceptions @tab SJLJ
25778 @*
25779 @item @b{ia64-openvms}
25780 @item @code{@ @ }@i{rts-native (default)}
25781 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
25782 @item @code{@ @ @ @ }Exceptions @tab ZCX
25783 @*
25784 @item @b{ia64-sgi_linux}
25785 @item @code{@ @ }@i{rts-native (default)}
25786 @item @code{@ @ @ @ }Tasking    @tab pthread library
25787 @item @code{@ @ @ @ }Exceptions @tab ZCX
25788 @*
25789 @item @b{mips-irix}
25790 @item @code{@ @ }@i{rts-native (default)}
25791 @item @code{@ @ @ @ }Tasking    @tab native IRIX threads
25792 @item @code{@ @ @ @ }Exceptions @tab ZCX
25793 @*
25794 @item @b{pa-hpux}
25795 @item @code{@ @ }@i{rts-native (default)}
25796 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
25797 @item @code{@ @ @ @ }Exceptions @tab ZCX
25798 @*
25799 @item @code{@ @ }@i{rts-sjlj}
25800 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
25801 @item @code{@ @ @ @ }Exceptions @tab SJLJ
25802 @*
25803 @item @b{ppc-aix}
25804 @item @code{@ @ }@i{rts-native (default)}
25805 @item @code{@ @ @ @ }Tasking    @tab native AIX threads
25806 @item @code{@ @ @ @ }Exceptions @tab SJLJ
25807 @*
25808 @item @b{ppc-darwin}
25809 @item @code{@ @ }@i{rts-native (default)}
25810 @item @code{@ @ @ @ }Tasking    @tab native MacOS threads
25811 @item @code{@ @ @ @ }Exceptions @tab ZCX
25812 @*
25813 @item @b{sparc-solaris}  @tab
25814 @item @code{@ @ }@i{rts-native (default)}
25815 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
25816 @item @code{@ @ @ @ }Exceptions @tab ZCX
25817 @*
25818 @item @code{@ @ }@i{rts-pthread}
25819 @item @code{@ @ @ @ }Tasking    @tab pthread library
25820 @item @code{@ @ @ @ }Exceptions @tab ZCX
25821 @*
25822 @item @code{@ @ }@i{rts-sjlj}
25823 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
25824 @item @code{@ @ @ @ }Exceptions @tab SJLJ
25825 @*
25826 @item @b{sparc64-solaris}  @tab
25827 @item @code{@ @ }@i{rts-native (default)}
25828 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
25829 @item @code{@ @ @ @ }Exceptions @tab ZCX
25830 @*
25831 @item @b{x86-linux}
25832 @item @code{@ @ }@i{rts-native (default)}
25833 @item @code{@ @ @ @ }Tasking    @tab pthread library
25834 @item @code{@ @ @ @ }Exceptions @tab ZCX
25835 @*
25836 @item @code{@ @ }@i{rts-sjlj}
25837 @item @code{@ @ @ @ }Tasking    @tab pthread library
25838 @item @code{@ @ @ @ }Exceptions @tab SJLJ
25839 @*
25840 @item @b{x86-lynx}
25841 @item @code{@ @ }@i{rts-native (default)}
25842 @item @code{@ @ @ @ }Tasking    @tab native LynxOS threads
25843 @item @code{@ @ @ @ }Exceptions @tab SJLJ
25844 @*
25845 @item @b{x86-solaris}
25846 @item @code{@ @ }@i{rts-native (default)}
25847 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads
25848 @item @code{@ @ @ @ }Exceptions @tab SJLJ
25849 @*
25850 @item @b{x86-windows}
25851 @item @code{@ @ }@i{rts-native (default)}
25852 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
25853 @item @code{@ @ @ @ }Exceptions @tab ZCX
25854 @*
25855 @item @code{@ @ }@i{rts-sjlj (default)}
25856 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
25857 @item @code{@ @ @ @ }Exceptions @tab SJLJ
25858 @*
25859 @item @b{x86-windows-rtx}
25860 @item @code{@ @ }@i{rts-rtx-rtss (default)}
25861 @item @code{@ @ @ @ }Tasking    @tab RTX real-time subsystem RTSS threads (kernel mode)
25862 @item @code{@ @ @ @ }Exceptions @tab SJLJ
25863 @*
25864 @item @code{@ @ }@i{rts-rtx-w32}
25865 @item @code{@ @ @ @ }Tasking    @tab RTX Win32 threads (user mode)
25866 @item @code{@ @ @ @ }Exceptions @tab ZCX
25867 @*
25868 @item @b{x86_64-linux}
25869 @item @code{@ @ }@i{rts-native (default)}
25870 @item @code{@ @ @ @ }Tasking    @tab pthread library
25871 @item @code{@ @ @ @ }Exceptions @tab ZCX
25872 @*
25873 @item @code{@ @ }@i{rts-sjlj}
25874 @item @code{@ @ @ @ }Tasking    @tab pthread library
25875 @item @code{@ @ @ @ }Exceptions @tab SJLJ
25876 @*
25877 @end multitable
25878
25879 @node Specifying a Run-Time Library
25880 @section Specifying a Run-Time Library
25881
25882 @noindent
25883 The @file{adainclude} subdirectory containing the sources of the GNAT
25884 run-time library, and the @file{adalib} subdirectory containing the
25885 @file{ALI} files and the static and/or shared GNAT library, are located
25886 in the gcc target-dependent area:
25887
25888 @smallexample
25889 target=$prefix/lib/gcc/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
25890 @end smallexample
25891
25892 @noindent
25893 As indicated above, on some platforms several run-time libraries are supplied.
25894 These libraries are installed in the target dependent area and
25895 contain a complete source and binary subdirectory. The detailed description
25896 below explains the differences between the different libraries in terms of
25897 their thread support.
25898
25899 The default run-time library (when GNAT is installed) is @emph{rts-native}.
25900 This default run time is selected by the means of soft links.
25901 For example on x86-linux:
25902
25903 @smallexample
25904 @group
25905  $(target-dir)
25906      |
25907      +--- adainclude----------+
25908      |                        |
25909      +--- adalib-----------+  |
25910      |                     |  |
25911      +--- rts-native       |  |
25912      |    |                |  |
25913      |    +--- adainclude <---+
25914      |    |                |
25915      |    +--- adalib <----+
25916      |
25917      +--- rts-sjlj
25918           |
25919           +--- adainclude
25920           |
25921           +--- adalib
25922 @end group
25923 @end smallexample
25924
25925 @noindent
25926 If the @i{rts-sjlj} library is to be selected on a permanent basis,
25927 these soft links can be modified with the following commands:
25928
25929 @smallexample
25930 $ cd $target
25931 $ rm -f adainclude adalib
25932 $ ln -s rts-sjlj/adainclude adainclude
25933 $ ln -s rts-sjlj/adalib adalib
25934 @end smallexample
25935
25936 @noindent
25937 Alternatively, you can specify @file{rts-sjlj/adainclude} in the file
25938 @file{$target/ada_source_path} and @file{rts-sjlj/adalib} in
25939 @file{$target/ada_object_path}.
25940
25941 Selecting another run-time library temporarily can be
25942 achieved by using the @option{--RTS} switch, e.g., @option{--RTS=sjlj}
25943 @cindex @option{--RTS} option
25944
25945 @node Choosing the Scheduling Policy
25946 @section Choosing the Scheduling Policy
25947
25948 @noindent
25949 When using a POSIX threads implementation, you have a choice of several
25950 scheduling policies: @code{SCHED_FIFO},
25951 @cindex @code{SCHED_FIFO} scheduling policy
25952 @code{SCHED_RR}
25953 @cindex @code{SCHED_RR} scheduling policy
25954 and @code{SCHED_OTHER}.
25955 @cindex @code{SCHED_OTHER} scheduling policy
25956 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
25957 or @code{SCHED_RR} requires special (e.g., root) privileges.
25958
25959 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
25960 @code{SCHED_FIFO},
25961 @cindex @code{SCHED_FIFO} scheduling policy
25962 you can use one of the following:
25963
25964 @itemize @bullet
25965 @item
25966 @code{pragma Time_Slice (0.0)}
25967 @cindex pragma Time_Slice
25968 @item
25969 the corresponding binder option @option{-T0}
25970 @cindex @option{-T0} option
25971 @item
25972 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
25973 @cindex pragma Task_Dispatching_Policy
25974 @end itemize
25975
25976 @noindent
25977 To specify @code{SCHED_RR},
25978 @cindex @code{SCHED_RR} scheduling policy
25979 you should use @code{pragma Time_Slice} with a
25980 value greater than @code{0.0}, or else use the corresponding @option{-T}
25981 binder option.
25982
25983 @node Solaris-Specific Considerations
25984 @section Solaris-Specific Considerations
25985 @cindex Solaris Sparc threads libraries
25986
25987 @noindent
25988 This section addresses some topics related to the various threads libraries
25989 on Sparc Solaris.
25990
25991 @menu
25992 * Solaris Threads Issues::
25993 @end menu
25994
25995 @node Solaris Threads Issues
25996 @subsection Solaris Threads Issues
25997
25998 @noindent
25999 GNAT under Solaris/Sparc 32 bits comes with an alternate tasking run-time
26000 library based on POSIX threads --- @emph{rts-pthread}.
26001 @cindex rts-pthread threads library
26002 This run-time library has the advantage of being mostly shared across all
26003 POSIX-compliant thread implementations, and it also provides under
26004 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
26005 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
26006 and @code{PTHREAD_PRIO_PROTECT}
26007 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
26008 semantics that can be selected using the predefined pragma
26009 @code{Locking_Policy}
26010 @cindex pragma Locking_Policy (under rts-pthread)
26011 with respectively
26012 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
26013 @cindex @code{Inheritance_Locking} (under rts-pthread)
26014 @cindex @code{Ceiling_Locking} (under rts-pthread)
26015
26016 As explained above, the native run-time library is based on the Solaris thread
26017 library (@code{libthread}) and is the default library.
26018
26019 When the Solaris threads library is used (this is the default), programs
26020 compiled with GNAT can automatically take advantage of
26021 and can thus execute on multiple processors.
26022 The user can alternatively specify a processor on which the program should run
26023 to emulate a single-processor system. The multiprocessor / uniprocessor choice
26024 is made by
26025 setting the environment variable @env{GNAT_PROCESSOR}
26026 @cindex @env{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
26027 to one of the following:
26028
26029 @table @code
26030 @item -2
26031 Use the default configuration (run the program on all
26032 available processors) - this is the same as having @code{GNAT_PROCESSOR}
26033 unset
26034
26035 @item -1
26036 Let the run-time implementation choose one processor and run the program on
26037 that processor
26038
26039 @item 0 .. Last_Proc
26040 Run the program on the specified processor.
26041 @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
26042 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
26043 @end table
26044
26045 @node Linux-Specific Considerations
26046 @section Linux-Specific Considerations
26047 @cindex Linux threads libraries
26048
26049 @noindent
26050 On GNU/Linux without NPTL support (usually system with GNU C Library
26051 older than 2.3), the signal model is not POSIX compliant, which means
26052 that to send a signal to the process, you need to send the signal to all
26053 threads, e.g.@: by using @code{killpg()}.
26054
26055 @node AIX-Specific Considerations
26056 @section AIX-Specific Considerations
26057 @cindex AIX resolver library
26058
26059 @noindent
26060 On AIX, the resolver library initializes some internal structure on
26061 the first call to @code{get*by*} functions, which are used to implement
26062 @code{GNAT.Sockets.Get_Host_By_Name} and
26063 @code{GNAT.Sockets.Get_Host_By_Address}.
26064 If such initialization occurs within an Ada task, and the stack size for
26065 the task is the default size, a stack overflow may occur.
26066
26067 To avoid this overflow, the user should either ensure that the first call
26068 to @code{GNAT.Sockets.Get_Host_By_Name} or
26069 @code{GNAT.Sockets.Get_Host_By_Addrss}
26070 occurs in the environment task, or use @code{pragma Storage_Size} to
26071 specify a sufficiently large size for the stack of the task that contains
26072 this call.
26073
26074 @node Irix-Specific Considerations
26075 @section Irix-Specific Considerations
26076 @cindex Irix libraries
26077
26078 @noindent
26079 The GCC support libraries coming with the Irix compiler have moved to
26080 their canonical place with respect to the general Irix ABI related
26081 conventions. Running applications built with the default shared GNAT
26082 run-time now requires the LD_LIBRARY_PATH environment variable to
26083 include this location. A possible way to achieve this is to issue the
26084 following command line on a bash prompt:
26085
26086 @smallexample
26087 @group
26088 $  LD_LIBRARY_PATH=$LD_LIBRARY_PATH:`dirname \`gcc --print-file-name=libgcc_s.so\``
26089 @end group
26090 @end smallexample
26091
26092 @node RTX-Specific Considerations
26093 @section RTX-Specific Considerations
26094 @cindex RTX libraries
26095
26096 @noindent
26097 The Real-time Extension (RTX) to Windows is based on the Windows Win32
26098 API. Applications can be built to work in two different modes:
26099
26100 @itemize @bullet
26101 @item
26102 Windows executables that run in Ring 3 to utilize memory protection
26103 (@emph{rts-rtx-w32}).
26104
26105 @item
26106 Real-time subsystem (RTSS) executables that run in Ring 0, where
26107 performance can be optimized with RTSS applications taking precedent
26108 over all Windows applications (@emph{rts-rtx-rtss}).
26109
26110 @end itemize
26111
26112 @c *******************************
26113 @node Example of Binder Output File
26114 @appendix Example of Binder Output File
26115
26116 @noindent
26117 This Appendix displays the source code for @command{gnatbind}'s output
26118 file generated for a simple ``Hello World'' program.
26119 Comments have been added for clarification purposes.
26120
26121 @smallexample @c adanocomment
26122 @iftex
26123 @leftskip=0cm
26124 @end iftex
26125 --  The package is called Ada_Main unless this name is actually used
26126 --  as a unit name in the partition, in which case some other unique
26127 --  name is used.
26128
26129 with System;
26130 package ada_main is
26131
26132    Elab_Final_Code : Integer;
26133    pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
26134
26135    --  The main program saves the parameters (argument count,
26136    --  argument values, environment pointer) in global variables
26137    --  for later access by other units including
26138    --  Ada.Command_Line.
26139
26140    gnat_argc : Integer;
26141    gnat_argv : System.Address;
26142    gnat_envp : System.Address;
26143
26144    --  The actual variables are stored in a library routine. This
26145    --  is useful for some shared library situations, where there
26146    --  are problems if variables are not in the library.
26147
26148    pragma Import (C, gnat_argc);
26149    pragma Import (C, gnat_argv);
26150    pragma Import (C, gnat_envp);
26151
26152    --  The exit status is similarly an external location
26153
26154    gnat_exit_status : Integer;
26155    pragma Import (C, gnat_exit_status);
26156
26157    GNAT_Version : constant String :=
26158                     "GNAT Version: 6.0.0w (20061115)";
26159    pragma Export (C, GNAT_Version, "__gnat_version");
26160
26161    --  This is the generated adafinal routine that performs
26162    --  finalization at the end of execution. In the case where
26163    --  Ada is the main program, this main program makes a call
26164    --  to adafinal at program termination.
26165
26166    procedure adafinal;
26167    pragma Export (C, adafinal, "adafinal");
26168
26169    --  This is the generated adainit routine that performs
26170    --  initialization at the start of execution. In the case
26171    --  where Ada is the main program, this main program makes
26172    --  a call to adainit at program startup.
26173
26174    procedure adainit;
26175    pragma Export (C, adainit, "adainit");
26176
26177    --  This routine is called at the start of execution. It is
26178    --  a dummy routine that is used by the debugger to breakpoint
26179    --  at the start of execution.
26180
26181    procedure Break_Start;
26182    pragma Import (C, Break_Start, "__gnat_break_start");
26183
26184    --  This is the actual generated main program (it would be
26185    --  suppressed if the no main program switch were used). As
26186    --  required by standard system conventions, this program has
26187    --  the external name main.
26188
26189    function main
26190      (argc : Integer;
26191       argv : System.Address;
26192       envp : System.Address)
26193       return Integer;
26194    pragma Export (C, main, "main");
26195
26196    --  The following set of constants give the version
26197    --  identification values for every unit in the bound
26198    --  partition. This identification is computed from all
26199    --  dependent semantic units, and corresponds to the
26200    --  string that would be returned by use of the
26201    --  Body_Version or Version attributes.
26202
26203    type Version_32 is mod 2 ** 32;
26204    u00001 : constant Version_32 := 16#7880BEB3#;
26205    u00002 : constant Version_32 := 16#0D24CBD0#;
26206    u00003 : constant Version_32 := 16#3283DBEB#;
26207    u00004 : constant Version_32 := 16#2359F9ED#;
26208    u00005 : constant Version_32 := 16#664FB847#;
26209    u00006 : constant Version_32 := 16#68E803DF#;
26210    u00007 : constant Version_32 := 16#5572E604#;
26211    u00008 : constant Version_32 := 16#46B173D8#;
26212    u00009 : constant Version_32 := 16#156A40CF#;
26213    u00010 : constant Version_32 := 16#033DABE0#;
26214    u00011 : constant Version_32 := 16#6AB38FEA#;
26215    u00012 : constant Version_32 := 16#22B6217D#;
26216    u00013 : constant Version_32 := 16#68A22947#;
26217    u00014 : constant Version_32 := 16#18CC4A56#;
26218    u00015 : constant Version_32 := 16#08258E1B#;
26219    u00016 : constant Version_32 := 16#367D5222#;
26220    u00017 : constant Version_32 := 16#20C9ECA4#;
26221    u00018 : constant Version_32 := 16#50D32CB6#;
26222    u00019 : constant Version_32 := 16#39A8BB77#;
26223    u00020 : constant Version_32 := 16#5CF8FA2B#;
26224    u00021 : constant Version_32 := 16#2F1EB794#;
26225    u00022 : constant Version_32 := 16#31AB6444#;
26226    u00023 : constant Version_32 := 16#1574B6E9#;
26227    u00024 : constant Version_32 := 16#5109C189#;
26228    u00025 : constant Version_32 := 16#56D770CD#;
26229    u00026 : constant Version_32 := 16#02F9DE3D#;
26230    u00027 : constant Version_32 := 16#08AB6B2C#;
26231    u00028 : constant Version_32 := 16#3FA37670#;
26232    u00029 : constant Version_32 := 16#476457A0#;
26233    u00030 : constant Version_32 := 16#731E1B6E#;
26234    u00031 : constant Version_32 := 16#23C2E789#;
26235    u00032 : constant Version_32 := 16#0F1BD6A1#;
26236    u00033 : constant Version_32 := 16#7C25DE96#;
26237    u00034 : constant Version_32 := 16#39ADFFA2#;
26238    u00035 : constant Version_32 := 16#571DE3E7#;
26239    u00036 : constant Version_32 := 16#5EB646AB#;
26240    u00037 : constant Version_32 := 16#4249379B#;
26241    u00038 : constant Version_32 := 16#0357E00A#;
26242    u00039 : constant Version_32 := 16#3784FB72#;
26243    u00040 : constant Version_32 := 16#2E723019#;
26244    u00041 : constant Version_32 := 16#623358EA#;
26245    u00042 : constant Version_32 := 16#107F9465#;
26246    u00043 : constant Version_32 := 16#6843F68A#;
26247    u00044 : constant Version_32 := 16#63305874#;
26248    u00045 : constant Version_32 := 16#31E56CE1#;
26249    u00046 : constant Version_32 := 16#02917970#;
26250    u00047 : constant Version_32 := 16#6CCBA70E#;
26251    u00048 : constant Version_32 := 16#41CD4204#;
26252    u00049 : constant Version_32 := 16#572E3F58#;
26253    u00050 : constant Version_32 := 16#20729FF5#;
26254    u00051 : constant Version_32 := 16#1D4F93E8#;
26255    u00052 : constant Version_32 := 16#30B2EC3D#;
26256    u00053 : constant Version_32 := 16#34054F96#;
26257    u00054 : constant Version_32 := 16#5A199860#;
26258    u00055 : constant Version_32 := 16#0E7F912B#;
26259    u00056 : constant Version_32 := 16#5760634A#;
26260    u00057 : constant Version_32 := 16#5D851835#;
26261
26262    --  The following Export pragmas export the version numbers
26263    --  with symbolic names ending in B (for body) or S
26264    --  (for spec) so that they can be located in a link. The
26265    --  information provided here is sufficient to track down
26266    --  the exact versions of units used in a given build.
26267
26268    pragma Export (C, u00001, "helloB");
26269    pragma Export (C, u00002, "system__standard_libraryB");
26270    pragma Export (C, u00003, "system__standard_libraryS");
26271    pragma Export (C, u00004, "adaS");
26272    pragma Export (C, u00005, "ada__text_ioB");
26273    pragma Export (C, u00006, "ada__text_ioS");
26274    pragma Export (C, u00007, "ada__exceptionsB");
26275    pragma Export (C, u00008, "ada__exceptionsS");
26276    pragma Export (C, u00009, "gnatS");
26277    pragma Export (C, u00010, "gnat__heap_sort_aB");
26278    pragma Export (C, u00011, "gnat__heap_sort_aS");
26279    pragma Export (C, u00012, "systemS");
26280    pragma Export (C, u00013, "system__exception_tableB");
26281    pragma Export (C, u00014, "system__exception_tableS");
26282    pragma Export (C, u00015, "gnat__htableB");
26283    pragma Export (C, u00016, "gnat__htableS");
26284    pragma Export (C, u00017, "system__exceptionsS");
26285    pragma Export (C, u00018, "system__machine_state_operationsB");
26286    pragma Export (C, u00019, "system__machine_state_operationsS");
26287    pragma Export (C, u00020, "system__machine_codeS");
26288    pragma Export (C, u00021, "system__storage_elementsB");
26289    pragma Export (C, u00022, "system__storage_elementsS");
26290    pragma Export (C, u00023, "system__secondary_stackB");
26291    pragma Export (C, u00024, "system__secondary_stackS");
26292    pragma Export (C, u00025, "system__parametersB");
26293    pragma Export (C, u00026, "system__parametersS");
26294    pragma Export (C, u00027, "system__soft_linksB");
26295    pragma Export (C, u00028, "system__soft_linksS");
26296    pragma Export (C, u00029, "system__stack_checkingB");
26297    pragma Export (C, u00030, "system__stack_checkingS");
26298    pragma Export (C, u00031, "system__tracebackB");
26299    pragma Export (C, u00032, "system__tracebackS");
26300    pragma Export (C, u00033, "ada__streamsS");
26301    pragma Export (C, u00034, "ada__tagsB");
26302    pragma Export (C, u00035, "ada__tagsS");
26303    pragma Export (C, u00036, "system__string_opsB");
26304    pragma Export (C, u00037, "system__string_opsS");
26305    pragma Export (C, u00038, "interfacesS");
26306    pragma Export (C, u00039, "interfaces__c_streamsB");
26307    pragma Export (C, u00040, "interfaces__c_streamsS");
26308    pragma Export (C, u00041, "system__file_ioB");
26309    pragma Export (C, u00042, "system__file_ioS");
26310    pragma Export (C, u00043, "ada__finalizationB");
26311    pragma Export (C, u00044, "ada__finalizationS");
26312    pragma Export (C, u00045, "system__finalization_rootB");
26313    pragma Export (C, u00046, "system__finalization_rootS");
26314    pragma Export (C, u00047, "system__finalization_implementationB");
26315    pragma Export (C, u00048, "system__finalization_implementationS");
26316    pragma Export (C, u00049, "system__string_ops_concat_3B");
26317    pragma Export (C, u00050, "system__string_ops_concat_3S");
26318    pragma Export (C, u00051, "system__stream_attributesB");
26319    pragma Export (C, u00052, "system__stream_attributesS");
26320    pragma Export (C, u00053, "ada__io_exceptionsS");
26321    pragma Export (C, u00054, "system__unsigned_typesS");
26322    pragma Export (C, u00055, "system__file_control_blockS");
26323    pragma Export (C, u00056, "ada__finalization__list_controllerB");
26324    pragma Export (C, u00057, "ada__finalization__list_controllerS");
26325
26326    -- BEGIN ELABORATION ORDER
26327    -- ada (spec)
26328    -- gnat (spec)
26329    -- gnat.heap_sort_a (spec)
26330    -- gnat.heap_sort_a (body)
26331    -- gnat.htable (spec)
26332    -- gnat.htable (body)
26333    -- interfaces (spec)
26334    -- system (spec)
26335    -- system.machine_code (spec)
26336    -- system.parameters (spec)
26337    -- system.parameters (body)
26338    -- interfaces.c_streams (spec)
26339    -- interfaces.c_streams (body)
26340    -- system.standard_library (spec)
26341    -- ada.exceptions (spec)
26342    -- system.exception_table (spec)
26343    -- system.exception_table (body)
26344    -- ada.io_exceptions (spec)
26345    -- system.exceptions (spec)
26346    -- system.storage_elements (spec)
26347    -- system.storage_elements (body)
26348    -- system.machine_state_operations (spec)
26349    -- system.machine_state_operations (body)
26350    -- system.secondary_stack (spec)
26351    -- system.stack_checking (spec)
26352    -- system.soft_links (spec)
26353    -- system.soft_links (body)
26354    -- system.stack_checking (body)
26355    -- system.secondary_stack (body)
26356    -- system.standard_library (body)
26357    -- system.string_ops (spec)
26358    -- system.string_ops (body)
26359    -- ada.tags (spec)
26360    -- ada.tags (body)
26361    -- ada.streams (spec)
26362    -- system.finalization_root (spec)
26363    -- system.finalization_root (body)
26364    -- system.string_ops_concat_3 (spec)
26365    -- system.string_ops_concat_3 (body)
26366    -- system.traceback (spec)
26367    -- system.traceback (body)
26368    -- ada.exceptions (body)
26369    -- system.unsigned_types (spec)
26370    -- system.stream_attributes (spec)
26371    -- system.stream_attributes (body)
26372    -- system.finalization_implementation (spec)
26373    -- system.finalization_implementation (body)
26374    -- ada.finalization (spec)
26375    -- ada.finalization (body)
26376    -- ada.finalization.list_controller (spec)
26377    -- ada.finalization.list_controller (body)
26378    -- system.file_control_block (spec)
26379    -- system.file_io (spec)
26380    -- system.file_io (body)
26381    -- ada.text_io (spec)
26382    -- ada.text_io (body)
26383    -- hello (body)
26384    -- END ELABORATION ORDER
26385
26386 end ada_main;
26387
26388 --  The following source file name pragmas allow the generated file
26389 --  names to be unique for different main programs. They are needed
26390 --  since the package name will always be Ada_Main.
26391
26392 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
26393 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
26394
26395 --  Generated package body for Ada_Main starts here
26396
26397 package body ada_main is
26398
26399    --  The actual finalization is performed by calling the
26400    --  library routine in System.Standard_Library.Adafinal
26401
26402    procedure Do_Finalize;
26403    pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
26404
26405    -------------
26406    -- adainit --
26407    -------------
26408
26409 @findex adainit
26410    procedure adainit is
26411
26412       --  These booleans are set to True once the associated unit has
26413       --  been elaborated. It is also used to avoid elaborating the
26414       --  same unit twice.
26415
26416       E040 : Boolean;
26417       pragma Import (Ada, E040, "interfaces__c_streams_E");
26418
26419       E008 : Boolean;
26420       pragma Import (Ada, E008, "ada__exceptions_E");
26421
26422       E014 : Boolean;
26423       pragma Import (Ada, E014, "system__exception_table_E");
26424
26425       E053 : Boolean;
26426       pragma Import (Ada, E053, "ada__io_exceptions_E");
26427
26428       E017 : Boolean;
26429       pragma Import (Ada, E017, "system__exceptions_E");
26430
26431       E024 : Boolean;
26432       pragma Import (Ada, E024, "system__secondary_stack_E");
26433
26434       E030 : Boolean;
26435       pragma Import (Ada, E030, "system__stack_checking_E");
26436
26437       E028 : Boolean;
26438       pragma Import (Ada, E028, "system__soft_links_E");
26439
26440       E035 : Boolean;
26441       pragma Import (Ada, E035, "ada__tags_E");
26442
26443       E033 : Boolean;
26444       pragma Import (Ada, E033, "ada__streams_E");
26445
26446       E046 : Boolean;
26447       pragma Import (Ada, E046, "system__finalization_root_E");
26448
26449       E048 : Boolean;
26450       pragma Import (Ada, E048, "system__finalization_implementation_E");
26451
26452       E044 : Boolean;
26453       pragma Import (Ada, E044, "ada__finalization_E");
26454
26455       E057 : Boolean;
26456       pragma Import (Ada, E057, "ada__finalization__list_controller_E");
26457
26458       E055 : Boolean;
26459       pragma Import (Ada, E055, "system__file_control_block_E");
26460
26461       E042 : Boolean;
26462       pragma Import (Ada, E042, "system__file_io_E");
26463
26464       E006 : Boolean;
26465       pragma Import (Ada, E006, "ada__text_io_E");
26466
26467       --  Set_Globals is a library routine that stores away the
26468       --  value of the indicated set of global values in global
26469       --  variables within the library.
26470
26471       procedure Set_Globals
26472         (Main_Priority            : Integer;
26473          Time_Slice_Value         : Integer;
26474          WC_Encoding              : Character;
26475          Locking_Policy           : Character;
26476          Queuing_Policy           : Character;
26477          Task_Dispatching_Policy  : Character;
26478          Adafinal                 : System.Address;
26479          Unreserve_All_Interrupts : Integer;
26480          Exception_Tracebacks     : Integer);
26481 @findex __gnat_set_globals
26482       pragma Import (C, Set_Globals, "__gnat_set_globals");
26483
26484       --  SDP_Table_Build is a library routine used to build the
26485       --  exception tables. See unit Ada.Exceptions in files
26486       --  a-except.ads/adb for full details of how zero cost
26487       --  exception handling works. This procedure, the call to
26488       --  it, and the two following tables are all omitted if the
26489       --  build is in longjmp/setjmp exception mode.
26490
26491 @findex SDP_Table_Build
26492 @findex Zero Cost Exceptions
26493       procedure SDP_Table_Build
26494         (SDP_Addresses   : System.Address;
26495          SDP_Count       : Natural;
26496          Elab_Addresses  : System.Address;
26497          Elab_Addr_Count : Natural);
26498       pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
26499
26500       --  Table of Unit_Exception_Table addresses. Used for zero
26501       --  cost exception handling to build the top level table.
26502
26503       ST : aliased constant array (1 .. 23) of System.Address := (
26504         Hello'UET_Address,
26505         Ada.Text_Io'UET_Address,
26506         Ada.Exceptions'UET_Address,
26507         Gnat.Heap_Sort_A'UET_Address,
26508         System.Exception_Table'UET_Address,
26509         System.Machine_State_Operations'UET_Address,
26510         System.Secondary_Stack'UET_Address,
26511         System.Parameters'UET_Address,
26512         System.Soft_Links'UET_Address,
26513         System.Stack_Checking'UET_Address,
26514         System.Traceback'UET_Address,
26515         Ada.Streams'UET_Address,
26516         Ada.Tags'UET_Address,
26517         System.String_Ops'UET_Address,
26518         Interfaces.C_Streams'UET_Address,
26519         System.File_Io'UET_Address,
26520         Ada.Finalization'UET_Address,
26521         System.Finalization_Root'UET_Address,
26522         System.Finalization_Implementation'UET_Address,
26523         System.String_Ops_Concat_3'UET_Address,
26524         System.Stream_Attributes'UET_Address,
26525         System.File_Control_Block'UET_Address,
26526         Ada.Finalization.List_Controller'UET_Address);
26527
26528       --  Table of addresses of elaboration routines. Used for
26529       --  zero cost exception handling to make sure these
26530       --  addresses are included in the top level procedure
26531       --  address table.
26532
26533       EA : aliased constant array (1 .. 23) of System.Address := (
26534         adainit'Code_Address,
26535         Do_Finalize'Code_Address,
26536         Ada.Exceptions'Elab_Spec'Address,
26537         System.Exceptions'Elab_Spec'Address,
26538         Interfaces.C_Streams'Elab_Spec'Address,
26539         System.Exception_Table'Elab_Body'Address,
26540         Ada.Io_Exceptions'Elab_Spec'Address,
26541         System.Stack_Checking'Elab_Spec'Address,
26542         System.Soft_Links'Elab_Body'Address,
26543         System.Secondary_Stack'Elab_Body'Address,
26544         Ada.Tags'Elab_Spec'Address,
26545         Ada.Tags'Elab_Body'Address,
26546         Ada.Streams'Elab_Spec'Address,
26547         System.Finalization_Root'Elab_Spec'Address,
26548         Ada.Exceptions'Elab_Body'Address,
26549         System.Finalization_Implementation'Elab_Spec'Address,
26550         System.Finalization_Implementation'Elab_Body'Address,
26551         Ada.Finalization'Elab_Spec'Address,
26552         Ada.Finalization.List_Controller'Elab_Spec'Address,
26553         System.File_Control_Block'Elab_Spec'Address,
26554         System.File_Io'Elab_Body'Address,
26555         Ada.Text_Io'Elab_Spec'Address,
26556         Ada.Text_Io'Elab_Body'Address);
26557
26558    --  Start of processing for adainit
26559
26560    begin
26561
26562       --  Call SDP_Table_Build to build the top level procedure
26563       --  table for zero cost exception handling (omitted in
26564       --  longjmp/setjmp mode).
26565
26566       SDP_Table_Build (ST'Address, 23, EA'Address, 23);
26567
26568       --  Call Set_Globals to record various information for
26569       --  this partition.  The values are derived by the binder
26570       --  from information stored in the ali files by the compiler.
26571
26572 @findex __gnat_set_globals
26573       Set_Globals
26574         (Main_Priority            => -1,
26575          --  Priority of main program, -1 if no pragma Priority used
26576
26577          Time_Slice_Value         => -1,
26578          --  Time slice from Time_Slice pragma, -1 if none used
26579
26580          WC_Encoding              => 'b',
26581          --  Wide_Character encoding used, default is brackets
26582
26583          Locking_Policy           => ' ',
26584          --  Locking_Policy used, default of space means not
26585          --  specified, otherwise it is the first character of
26586          --  the policy name.
26587
26588          Queuing_Policy           => ' ',
26589          --  Queuing_Policy used, default of space means not
26590          --  specified, otherwise it is the first character of
26591          --  the policy name.
26592
26593          Task_Dispatching_Policy  => ' ',
26594          --  Task_Dispatching_Policy used, default of space means
26595          --  not specified, otherwise first character of the
26596          --  policy name.
26597
26598          Adafinal                 => System.Null_Address,
26599          --  Address of Adafinal routine, not used anymore
26600
26601          Unreserve_All_Interrupts => 0,
26602          --  Set true if pragma Unreserve_All_Interrupts was used
26603
26604          Exception_Tracebacks     => 0);
26605          --  Indicates if exception tracebacks are enabled
26606
26607       Elab_Final_Code := 1;
26608
26609       --  Now we have the elaboration calls for all units in the partition.
26610       --  The Elab_Spec and Elab_Body attributes generate references to the
26611       --  implicit elaboration procedures generated by the compiler for
26612       --  each unit that requires elaboration.
26613
26614       if not E040 then
26615          Interfaces.C_Streams'Elab_Spec;
26616       end if;
26617       E040 := True;
26618       if not E008 then
26619          Ada.Exceptions'Elab_Spec;
26620       end if;
26621       if not E014 then
26622          System.Exception_Table'Elab_Body;
26623          E014 := True;
26624       end if;
26625       if not E053 then
26626          Ada.Io_Exceptions'Elab_Spec;
26627          E053 := True;
26628       end if;
26629       if not E017 then
26630          System.Exceptions'Elab_Spec;
26631          E017 := True;
26632       end if;
26633       if not E030 then
26634          System.Stack_Checking'Elab_Spec;
26635       end if;
26636       if not E028 then
26637          System.Soft_Links'Elab_Body;
26638          E028 := True;
26639       end if;
26640       E030 := True;
26641       if not E024 then
26642          System.Secondary_Stack'Elab_Body;
26643          E024 := True;
26644       end if;
26645       if not E035 then
26646          Ada.Tags'Elab_Spec;
26647       end if;
26648       if not E035 then
26649          Ada.Tags'Elab_Body;
26650          E035 := True;
26651       end if;
26652       if not E033 then
26653          Ada.Streams'Elab_Spec;
26654          E033 := True;
26655       end if;
26656       if not E046 then
26657          System.Finalization_Root'Elab_Spec;
26658       end if;
26659       E046 := True;
26660       if not E008 then
26661          Ada.Exceptions'Elab_Body;
26662          E008 := True;
26663       end if;
26664       if not E048 then
26665          System.Finalization_Implementation'Elab_Spec;
26666       end if;
26667       if not E048 then
26668          System.Finalization_Implementation'Elab_Body;
26669          E048 := True;
26670       end if;
26671       if not E044 then
26672          Ada.Finalization'Elab_Spec;
26673       end if;
26674       E044 := True;
26675       if not E057 then
26676          Ada.Finalization.List_Controller'Elab_Spec;
26677       end if;
26678       E057 := True;
26679       if not E055 then
26680          System.File_Control_Block'Elab_Spec;
26681          E055 := True;
26682       end if;
26683       if not E042 then
26684          System.File_Io'Elab_Body;
26685          E042 := True;
26686       end if;
26687       if not E006 then
26688          Ada.Text_Io'Elab_Spec;
26689       end if;
26690       if not E006 then
26691          Ada.Text_Io'Elab_Body;
26692          E006 := True;
26693       end if;
26694
26695       Elab_Final_Code := 0;
26696    end adainit;
26697
26698    --------------
26699    -- adafinal --
26700    --------------
26701
26702 @findex adafinal
26703    procedure adafinal is
26704    begin
26705       Do_Finalize;
26706    end adafinal;
26707
26708    ----------
26709    -- main --
26710    ----------
26711
26712    --  main is actually a function, as in the ANSI C standard,
26713    --  defined to return the exit status. The three parameters
26714    --  are the argument count, argument values and environment
26715    --  pointer.
26716
26717 @findex Main Program
26718    function main
26719      (argc : Integer;
26720       argv : System.Address;
26721       envp : System.Address)
26722       return Integer
26723    is
26724       --  The initialize routine performs low level system
26725       --  initialization using a standard library routine which
26726       --  sets up signal handling and performs any other
26727       --  required setup. The routine can be found in file
26728       --  a-init.c.
26729
26730 @findex __gnat_initialize
26731       procedure initialize;
26732       pragma Import (C, initialize, "__gnat_initialize");
26733
26734       --  The finalize routine performs low level system
26735       --  finalization using a standard library routine. The
26736       --  routine is found in file a-final.c and in the standard
26737       --  distribution is a dummy routine that does nothing, so
26738       --  really this is a hook for special user finalization.
26739
26740 @findex __gnat_finalize
26741       procedure finalize;
26742       pragma Import (C, finalize, "__gnat_finalize");
26743
26744       --  We get to the main program of the partition by using
26745       --  pragma Import because if we try to with the unit and
26746       --  call it Ada style, then not only do we waste time
26747       --  recompiling it, but also, we don't really know the right
26748       --  switches (e.g.@: identifier character set) to be used
26749       --  to compile it.
26750
26751       procedure Ada_Main_Program;
26752       pragma Import (Ada, Ada_Main_Program, "_ada_hello");
26753
26754    --  Start of processing for main
26755
26756    begin
26757       --  Save global variables
26758
26759       gnat_argc := argc;
26760       gnat_argv := argv;
26761       gnat_envp := envp;
26762
26763       --  Call low level system initialization
26764
26765       Initialize;
26766
26767       --  Call our generated Ada initialization routine
26768
26769       adainit;
26770
26771       --  This is the point at which we want the debugger to get
26772       --  control
26773
26774       Break_Start;
26775
26776       --  Now we call the main program of the partition
26777
26778       Ada_Main_Program;
26779
26780       --  Perform Ada finalization
26781
26782       adafinal;
26783
26784       --  Perform low level system finalization
26785
26786       Finalize;
26787
26788       --  Return the proper exit status
26789       return (gnat_exit_status);
26790    end;
26791
26792 --  This section is entirely comments, so it has no effect on the
26793 --  compilation of the Ada_Main package. It provides the list of
26794 --  object files and linker options, as well as some standard
26795 --  libraries needed for the link. The gnatlink utility parses
26796 --  this b~hello.adb file to read these comment lines to generate
26797 --  the appropriate command line arguments for the call to the
26798 --  system linker. The BEGIN/END lines are used for sentinels for
26799 --  this parsing operation.
26800
26801 --  The exact file names will of course depend on the environment,
26802 --  host/target and location of files on the host system.
26803
26804 @findex Object file list
26805 -- BEGIN Object file/option list
26806    --   ./hello.o
26807    --   -L./
26808    --   -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
26809    --   /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
26810 -- END Object file/option list
26811
26812 end ada_main;
26813 @end smallexample
26814
26815 @noindent
26816 The Ada code in the above example is exactly what is generated by the
26817 binder. We have added comments to more clearly indicate the function
26818 of each part of the generated @code{Ada_Main} package.
26819
26820 The code is standard Ada in all respects, and can be processed by any
26821 tools that handle Ada. In particular, it is possible to use the debugger
26822 in Ada mode to debug the generated @code{Ada_Main} package. For example,
26823 suppose that for reasons that you do not understand, your program is crashing
26824 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
26825 you can place a breakpoint on the call:
26826
26827 @smallexample @c ada
26828 Ada.Text_Io'Elab_Body;
26829 @end smallexample
26830
26831 @noindent
26832 and trace the elaboration routine for this package to find out where
26833 the problem might be (more usually of course you would be debugging
26834 elaboration code in your own application).
26835
26836 @node Elaboration Order Handling in GNAT
26837 @appendix Elaboration Order Handling in GNAT
26838 @cindex Order of elaboration
26839 @cindex Elaboration control
26840
26841 @menu
26842 * Elaboration Code::
26843 * Checking the Elaboration Order::
26844 * Controlling the Elaboration Order::
26845 * Controlling Elaboration in GNAT - Internal Calls::
26846 * Controlling Elaboration in GNAT - External Calls::
26847 * Default Behavior in GNAT - Ensuring Safety::
26848 * Treatment of Pragma Elaborate::
26849 * Elaboration Issues for Library Tasks::
26850 * Mixing Elaboration Models::
26851 * What to Do If the Default Elaboration Behavior Fails::
26852 * Elaboration for Access-to-Subprogram Values::
26853 * Summary of Procedures for Elaboration Control::
26854 * Other Elaboration Order Considerations::
26855 @end menu
26856
26857 @noindent
26858 This chapter describes the handling of elaboration code in Ada and
26859 in GNAT, and discusses how the order of elaboration of program units can
26860 be controlled in GNAT, either automatically or with explicit programming
26861 features.
26862
26863 @node Elaboration Code
26864 @section Elaboration Code
26865
26866 @noindent
26867 Ada provides rather general mechanisms for executing code at elaboration
26868 time, that is to say before the main program starts executing. Such code arises
26869 in three contexts:
26870
26871 @table @asis
26872 @item Initializers for variables.
26873 Variables declared at the library level, in package specs or bodies, can
26874 require initialization that is performed at elaboration time, as in:
26875 @smallexample @c ada
26876 @cartouche
26877 Sqrt_Half : Float := Sqrt (0.5);
26878 @end cartouche
26879 @end smallexample
26880
26881 @item Package initialization code
26882 Code in a @code{BEGIN-END} section at the outer level of a package body is
26883 executed as part of the package body elaboration code.
26884
26885 @item Library level task allocators
26886 Tasks that are declared using task allocators at the library level
26887 start executing immediately and hence can execute at elaboration time.
26888 @end table
26889
26890 @noindent
26891 Subprogram calls are possible in any of these contexts, which means that
26892 any arbitrary part of the program may be executed as part of the elaboration
26893 code. It is even possible to write a program which does all its work at
26894 elaboration time, with a null main program, although stylistically this
26895 would usually be considered an inappropriate way to structure
26896 a program.
26897
26898 An important concern arises in the context of elaboration code:
26899 we have to be sure that it is executed in an appropriate order. What we
26900 have is a series of elaboration code sections, potentially one section
26901 for each unit in the program. It is important that these execute
26902 in the correct order. Correctness here means that, taking the above
26903 example of the declaration of @code{Sqrt_Half},
26904 if some other piece of
26905 elaboration code references @code{Sqrt_Half},
26906 then it must run after the
26907 section of elaboration code that contains the declaration of
26908 @code{Sqrt_Half}.
26909
26910 There would never be any order of elaboration problem if we made a rule
26911 that whenever you @code{with} a unit, you must elaborate both the spec and body
26912 of that unit before elaborating the unit doing the @code{with}'ing:
26913
26914 @smallexample @c ada
26915 @group
26916 @cartouche
26917 with Unit_1;
26918 package Unit_2 is @dots{}
26919 @end cartouche
26920 @end group
26921 @end smallexample
26922
26923 @noindent
26924 would require that both the body and spec of @code{Unit_1} be elaborated
26925 before the spec of @code{Unit_2}. However, a rule like that would be far too
26926 restrictive. In particular, it would make it impossible to have routines
26927 in separate packages that were mutually recursive.
26928
26929 You might think that a clever enough compiler could look at the actual
26930 elaboration code and determine an appropriate correct order of elaboration,
26931 but in the general case, this is not possible. Consider the following
26932 example.
26933
26934 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
26935 that references
26936 the variable @code{Sqrt_1}, which is declared in the elaboration code
26937 of the body of @code{Unit_1}:
26938
26939 @smallexample @c ada
26940 @cartouche
26941 Sqrt_1 : Float := Sqrt (0.1);
26942 @end cartouche
26943 @end smallexample
26944
26945 @noindent
26946 The elaboration code of the body of @code{Unit_1} also contains:
26947
26948 @smallexample @c ada
26949 @group
26950 @cartouche
26951 if expression_1 = 1 then
26952    Q := Unit_2.Func_2;
26953 end if;
26954 @end cartouche
26955 @end group
26956 @end smallexample
26957
26958 @noindent
26959 @code{Unit_2} is exactly parallel,
26960 it has a procedure @code{Func_2} that references
26961 the variable @code{Sqrt_2}, which is declared in the elaboration code of
26962 the body @code{Unit_2}:
26963
26964 @smallexample @c ada
26965 @cartouche
26966 Sqrt_2 : Float := Sqrt (0.1);
26967 @end cartouche
26968 @end smallexample
26969
26970 @noindent
26971 The elaboration code of the body of @code{Unit_2} also contains:
26972
26973 @smallexample @c ada
26974 @group
26975 @cartouche
26976 if expression_2 = 2 then
26977    Q := Unit_1.Func_1;
26978 end if;
26979 @end cartouche
26980 @end group
26981 @end smallexample
26982
26983 @noindent
26984 Now the question is, which of the following orders of elaboration is
26985 acceptable:
26986
26987 @smallexample
26988 @group
26989 Spec of Unit_1
26990 Spec of Unit_2
26991 Body of Unit_1
26992 Body of Unit_2
26993 @end group
26994 @end smallexample
26995
26996 @noindent
26997 or
26998
26999 @smallexample
27000 @group
27001 Spec of Unit_2
27002 Spec of Unit_1
27003 Body of Unit_2
27004 Body of Unit_1
27005 @end group
27006 @end smallexample
27007
27008 @noindent
27009 If you carefully analyze the flow here, you will see that you cannot tell
27010 at compile time the answer to this question.
27011 If @code{expression_1} is not equal to 1,
27012 and @code{expression_2} is not equal to 2,
27013 then either order is acceptable, because neither of the function calls is
27014 executed. If both tests evaluate to true, then neither order is acceptable
27015 and in fact there is no correct order.
27016
27017 If one of the two expressions is true, and the other is false, then one
27018 of the above orders is correct, and the other is incorrect. For example,
27019 if @code{expression_1} /= 1 and @code{expression_2} = 2,
27020 then the call to @code{Func_1}
27021 will occur, but not the call to @code{Func_2.}
27022 This means that it is essential
27023 to elaborate the body of @code{Unit_1} before
27024 the body of @code{Unit_2}, so the first
27025 order of elaboration is correct and the second is wrong.
27026
27027 By making @code{expression_1} and @code{expression_2}
27028 depend on input data, or perhaps
27029 the time of day, we can make it impossible for the compiler or binder
27030 to figure out which of these expressions will be true, and hence it
27031 is impossible to guarantee a safe order of elaboration at run time.
27032
27033 @node Checking the Elaboration Order
27034 @section Checking the Elaboration Order
27035
27036 @noindent
27037 In some languages that involve the same kind of elaboration problems,
27038 e.g.@: Java and C++, the programmer is expected to worry about these
27039 ordering problems himself, and it is common to
27040 write a program in which an incorrect elaboration order  gives
27041 surprising results, because it references variables before they
27042 are initialized.
27043 Ada is designed to be a safe language, and a programmer-beware approach is
27044 clearly not sufficient. Consequently, the language provides three lines
27045 of defense:
27046
27047 @table @asis
27048 @item Standard rules
27049 Some standard rules restrict the possible choice of elaboration
27050 order. In particular, if you @code{with} a unit, then its spec is always
27051 elaborated before the unit doing the @code{with}. Similarly, a parent
27052 spec is always elaborated before the child spec, and finally
27053 a spec is always elaborated before its corresponding body.
27054
27055 @item Dynamic elaboration checks
27056 @cindex Elaboration checks
27057 @cindex Checks, elaboration
27058 Dynamic checks are made at run time, so that if some entity is accessed
27059 before it is elaborated (typically  by means of a subprogram call)
27060 then the exception (@code{Program_Error}) is raised.
27061
27062 @item Elaboration control
27063 Facilities are provided for the programmer to specify the desired order
27064 of elaboration.
27065 @end table
27066
27067 Let's look at these facilities in more detail. First, the rules for
27068 dynamic checking. One possible rule would be simply to say that the
27069 exception is raised if you access a variable which has not yet been
27070 elaborated. The trouble with this approach is that it could require
27071 expensive checks on every variable reference. Instead Ada has two
27072 rules which are a little more restrictive, but easier to check, and
27073 easier to state:
27074
27075 @table @asis
27076 @item Restrictions on calls
27077 A subprogram can only be called at elaboration time if its body
27078 has been elaborated. The rules for elaboration given above guarantee
27079 that the spec of the subprogram has been elaborated before the
27080 call, but not the body. If this rule is violated, then the
27081 exception @code{Program_Error} is raised.
27082
27083 @item Restrictions on instantiations
27084 A generic unit can only be instantiated if the body of the generic
27085 unit has been elaborated. Again, the rules for elaboration given above
27086 guarantee that the spec of the generic unit has been elaborated
27087 before the instantiation, but not the body. If this rule is
27088 violated, then the exception @code{Program_Error} is raised.
27089 @end table
27090
27091 @noindent
27092 The idea is that if the body has been elaborated, then any variables
27093 it references must have been elaborated; by checking for the body being
27094 elaborated we guarantee that none of its references causes any
27095 trouble. As we noted above, this is a little too restrictive, because a
27096 subprogram that has no non-local references in its body may in fact be safe
27097 to call. However, it really would be unsafe to rely on this, because
27098 it would mean that the caller was aware of details of the implementation
27099 in the body. This goes against the basic tenets of Ada.
27100
27101 A plausible implementation can be described as follows.
27102 A Boolean variable is associated with each subprogram
27103 and each generic unit. This variable is initialized to False, and is set to
27104 True at the point body is elaborated. Every call or instantiation checks the
27105 variable, and raises @code{Program_Error} if the variable is False.
27106
27107 Note that one might think that it would be good enough to have one Boolean
27108 variable for each package, but that would not deal with cases of trying
27109 to call a body in the same package as the call
27110 that has not been elaborated yet.
27111 Of course a compiler may be able to do enough analysis to optimize away
27112 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
27113 does such optimizations, but still the easiest conceptual model is to
27114 think of there being one variable per subprogram.
27115
27116 @node Controlling the Elaboration Order
27117 @section Controlling the Elaboration Order
27118
27119 @noindent
27120 In the previous section we discussed the rules in Ada which ensure
27121 that @code{Program_Error} is raised if an incorrect elaboration order is
27122 chosen. This prevents erroneous executions, but we need mechanisms to
27123 specify a correct execution and avoid the exception altogether.
27124 To achieve this, Ada provides a number of features for controlling
27125 the order of elaboration. We discuss these features in this section.
27126
27127 First, there are several ways of indicating to the compiler that a given
27128 unit has no elaboration problems:
27129
27130 @table @asis
27131 @item packages that do not require a body
27132 A library package that does not require a body does not permit
27133 a body (this rule was introduced in Ada 95).
27134 Thus if we have a such a package, as in:
27135
27136 @smallexample @c ada
27137 @group
27138 @cartouche
27139 package Definitions is
27140    generic
27141       type m is new integer;
27142    package Subp is
27143       type a is array (1 .. 10) of m;
27144       type b is array (1 .. 20) of m;
27145    end Subp;
27146 end Definitions;
27147 @end cartouche
27148 @end group
27149 @end smallexample
27150
27151 @noindent
27152 A package that @code{with}'s @code{Definitions} may safely instantiate
27153 @code{Definitions.Subp} because the compiler can determine that there
27154 definitely is no package body to worry about in this case
27155
27156 @item pragma Pure
27157 @cindex pragma Pure
27158 @findex Pure
27159 Places sufficient restrictions on a unit to guarantee that
27160 no call to any subprogram in the unit can result in an
27161 elaboration problem. This means that the compiler does not need
27162 to worry about the point of elaboration of such units, and in
27163 particular, does not need to check any calls to any subprograms
27164 in this unit.
27165
27166 @item pragma Preelaborate
27167 @findex Preelaborate
27168 @cindex pragma Preelaborate
27169 This pragma places slightly less stringent restrictions on a unit than
27170 does pragma Pure,
27171 but these restrictions are still sufficient to ensure that there
27172 are no elaboration problems with any calls to the unit.
27173
27174 @item pragma Elaborate_Body
27175 @findex Elaborate_Body
27176 @cindex pragma Elaborate_Body
27177 This pragma requires that the body of a unit be elaborated immediately
27178 after its spec. Suppose a unit @code{A} has such a pragma,
27179 and unit @code{B} does
27180 a @code{with} of unit @code{A}. Recall that the standard rules require
27181 the spec of unit @code{A}
27182 to be elaborated before the @code{with}'ing unit; given the pragma in
27183 @code{A}, we also know that the body of @code{A}
27184 will be elaborated before @code{B}, so
27185 that calls to @code{A} are safe and do not need a check.
27186 @end table
27187
27188 @noindent
27189 Note that,
27190 unlike pragma @code{Pure} and pragma @code{Preelaborate},
27191 the use of
27192 @code{Elaborate_Body} does not guarantee that the program is
27193 free of elaboration problems, because it may not be possible
27194 to satisfy the requested elaboration order.
27195 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
27196 If a programmer
27197 marks @code{Unit_1} as @code{Elaborate_Body},
27198 and not @code{Unit_2,} then the order of
27199 elaboration will be:
27200
27201 @smallexample
27202 @group
27203 Spec of Unit_2
27204 Spec of Unit_1
27205 Body of Unit_1
27206 Body of Unit_2
27207 @end group
27208 @end smallexample
27209
27210 @noindent
27211 Now that means that the call to @code{Func_1} in @code{Unit_2}
27212 need not be checked,
27213 it must be safe. But the call to @code{Func_2} in
27214 @code{Unit_1} may still fail if
27215 @code{Expression_1} is equal to 1,
27216 and the programmer must still take
27217 responsibility for this not being the case.
27218
27219 If all units carry a pragma @code{Elaborate_Body}, then all problems are
27220 eliminated, except for calls entirely within a body, which are
27221 in any case fully under programmer control. However, using the pragma
27222 everywhere is not always possible.
27223 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
27224 we marked both of them as having pragma @code{Elaborate_Body}, then
27225 clearly there would be no possible elaboration order.
27226
27227 The above pragmas allow a server to guarantee safe use by clients, and
27228 clearly this is the preferable approach. Consequently a good rule
27229 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
27230 and if this is not possible,
27231 mark them as @code{Elaborate_Body} if possible.
27232 As we have seen, there are situations where neither of these
27233 three pragmas can be used.
27234 So we also provide methods for clients to control the
27235 order of elaboration of the servers on which they depend:
27236
27237 @table @asis
27238 @item pragma Elaborate (unit)
27239 @findex Elaborate
27240 @cindex pragma Elaborate
27241 This pragma is placed in the context clause, after a @code{with} clause,
27242 and it requires that the body of the named unit be elaborated before
27243 the unit in which the pragma occurs. The idea is to use this pragma
27244 if the current unit calls at elaboration time, directly or indirectly,
27245 some subprogram in the named unit.
27246
27247 @item pragma Elaborate_All (unit)
27248 @findex Elaborate_All
27249 @cindex pragma Elaborate_All
27250 This is a stronger version of the Elaborate pragma. Consider the
27251 following example:
27252
27253 @smallexample
27254 Unit A @code{with}'s unit B and calls B.Func in elab code
27255 Unit B @code{with}'s unit C, and B.Func calls C.Func
27256 @end smallexample
27257
27258 @noindent
27259 Now if we put a pragma @code{Elaborate (B)}
27260 in unit @code{A}, this ensures that the
27261 body of @code{B} is elaborated before the call, but not the
27262 body of @code{C}, so
27263 the call to @code{C.Func} could still cause @code{Program_Error} to
27264 be raised.
27265
27266 The effect of a pragma @code{Elaborate_All} is stronger, it requires
27267 not only that the body of the named unit be elaborated before the
27268 unit doing the @code{with}, but also the bodies of all units that the
27269 named unit uses, following @code{with} links transitively. For example,
27270 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
27271 then it requires
27272 not only that the body of @code{B} be elaborated before @code{A},
27273 but also the
27274 body of @code{C}, because @code{B} @code{with}'s @code{C}.
27275 @end table
27276
27277 @noindent
27278 We are now in a position to give a usage rule in Ada for avoiding
27279 elaboration problems, at least if dynamic dispatching and access to
27280 subprogram values are not used. We will handle these cases separately
27281 later.
27282
27283 The rule is simple. If a unit has elaboration code that can directly or
27284 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
27285 a generic package in a @code{with}'ed unit,
27286 then if the @code{with}'ed unit does not have
27287 pragma @code{Pure} or @code{Preelaborate}, then the client should have
27288 a pragma @code{Elaborate_All}
27289 for the @code{with}'ed unit. By following this rule a client is
27290 assured that calls can be made without risk of an exception.
27291
27292 For generic subprogram instantiations, the rule can be relaxed to
27293 require only a pragma @code{Elaborate} since elaborating the body
27294 of a subprogram cannot cause any transitive elaboration (we are
27295 not calling the subprogram in this case, just elaborating its
27296 declaration).
27297
27298 If this rule is not followed, then a program may be in one of four
27299 states:
27300
27301 @table @asis
27302 @item No order exists
27303 No order of elaboration exists which follows the rules, taking into
27304 account any @code{Elaborate}, @code{Elaborate_All},
27305 or @code{Elaborate_Body} pragmas. In
27306 this case, an Ada compiler must diagnose the situation at bind
27307 time, and refuse to build an executable program.
27308
27309 @item One or more orders exist, all incorrect
27310 One or more acceptable elaboration orders exist, and all of them
27311 generate an elaboration order problem. In this case, the binder
27312 can build an executable program, but @code{Program_Error} will be raised
27313 when the program is run.
27314
27315 @item Several orders exist, some right, some incorrect
27316 One or more acceptable elaboration orders exists, and some of them
27317 work, and some do not. The programmer has not controlled
27318 the order of elaboration, so the binder may or may not pick one of
27319 the correct orders, and the program may or may not raise an
27320 exception when it is run. This is the worst case, because it means
27321 that the program may fail when moved to another compiler, or even
27322 another version of the same compiler.
27323
27324 @item One or more orders exists, all correct
27325 One ore more acceptable elaboration orders exist, and all of them
27326 work. In this case the program runs successfully. This state of
27327 affairs can be guaranteed by following the rule we gave above, but
27328 may be true even if the rule is not followed.
27329 @end table
27330
27331 @noindent
27332 Note that one additional advantage of following our rules on the use
27333 of @code{Elaborate} and @code{Elaborate_All}
27334 is that the program continues to stay in the ideal (all orders OK) state
27335 even if maintenance
27336 changes some bodies of some units. Conversely, if a program that does
27337 not follow this rule happens to be safe at some point, this state of affairs
27338 may deteriorate silently as a result of maintenance changes.
27339
27340 You may have noticed that the above discussion did not mention
27341 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
27342 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
27343 code in the body makes calls to some other unit, so it is still necessary
27344 to use @code{Elaborate_All} on such units.
27345
27346 @node Controlling Elaboration in GNAT - Internal Calls
27347 @section Controlling Elaboration in GNAT - Internal Calls
27348
27349 @noindent
27350 In the case of internal calls, i.e., calls within a single package, the
27351 programmer has full control over the order of elaboration, and it is up
27352 to the programmer to elaborate declarations in an appropriate order. For
27353 example writing:
27354
27355 @smallexample @c ada
27356 @group
27357 @cartouche
27358 function One return Float;
27359
27360 Q : Float := One;
27361
27362 function One return Float is
27363 begin
27364      return 1.0;
27365 end One;
27366 @end cartouche
27367 @end group
27368 @end smallexample
27369
27370 @noindent
27371 will obviously raise @code{Program_Error} at run time, because function
27372 One will be called before its body is elaborated. In this case GNAT will
27373 generate a warning that the call will raise @code{Program_Error}:
27374
27375 @smallexample
27376 @group
27377 @cartouche
27378  1. procedure y is
27379  2.    function One return Float;
27380  3.
27381  4.    Q : Float := One;
27382                     |
27383     >>> warning: cannot call "One" before body is elaborated
27384     >>> warning: Program_Error will be raised at run time
27385
27386  5.
27387  6.    function One return Float is
27388  7.    begin
27389  8.         return 1.0;
27390  9.    end One;
27391 10.
27392 11. begin
27393 12.    null;
27394 13. end;
27395 @end cartouche
27396 @end group
27397 @end smallexample
27398
27399 @noindent
27400 Note that in this particular case, it is likely that the call is safe, because
27401 the function @code{One} does not access any global variables.
27402 Nevertheless in Ada, we do not want the validity of the check to depend on
27403 the contents of the body (think about the separate compilation case), so this
27404 is still wrong, as we discussed in the previous sections.
27405
27406 The error is easily corrected by rearranging the declarations so that the
27407 body of @code{One} appears before the declaration containing the call
27408 (note that in Ada 95 and Ada 2005,
27409 declarations can appear in any order, so there is no restriction that
27410 would prevent this reordering, and if we write:
27411
27412 @smallexample @c ada
27413 @group
27414 @cartouche
27415 function One return Float;
27416
27417 function One return Float is
27418 begin
27419      return 1.0;
27420 end One;
27421
27422 Q : Float := One;
27423 @end cartouche
27424 @end group
27425 @end smallexample
27426
27427 @noindent
27428 then all is well, no warning is generated, and no
27429 @code{Program_Error} exception
27430 will be raised.
27431 Things are more complicated when a chain of subprograms is executed:
27432
27433 @smallexample @c ada
27434 @group
27435 @cartouche
27436 function A return Integer;
27437 function B return Integer;
27438 function C return Integer;
27439
27440 function B return Integer is begin return A; end;
27441 function C return Integer is begin return B; end;
27442
27443 X : Integer := C;
27444
27445 function A return Integer is begin return 1; end;
27446 @end cartouche
27447 @end group
27448 @end smallexample
27449
27450 @noindent
27451 Now the call to @code{C}
27452 at elaboration time in the declaration of @code{X} is correct, because
27453 the body of @code{C} is already elaborated,
27454 and the call to @code{B} within the body of
27455 @code{C} is correct, but the call
27456 to @code{A} within the body of @code{B} is incorrect, because the body
27457 of @code{A} has not been elaborated, so @code{Program_Error}
27458 will be raised on the call to @code{A}.
27459 In this case GNAT will generate a
27460 warning that @code{Program_Error} may be
27461 raised at the point of the call. Let's look at the warning:
27462
27463 @smallexample
27464 @group
27465 @cartouche
27466  1. procedure x is
27467  2.    function A return Integer;
27468  3.    function B return Integer;
27469  4.    function C return Integer;
27470  5.
27471  6.    function B return Integer is begin return A; end;
27472                                                     |
27473     >>> warning: call to "A" before body is elaborated may
27474                  raise Program_Error
27475     >>> warning: "B" called at line 7
27476     >>> warning: "C" called at line 9
27477
27478  7.    function C return Integer is begin return B; end;
27479  8.
27480  9.    X : Integer := C;
27481 10.
27482 11.    function A return Integer is begin return 1; end;
27483 12.
27484 13. begin
27485 14.    null;
27486 15. end;
27487 @end cartouche
27488 @end group
27489 @end smallexample
27490
27491 @noindent
27492 Note that the message here says ``may raise'', instead of the direct case,
27493 where the message says ``will be raised''. That's because whether
27494 @code{A} is
27495 actually called depends in general on run-time flow of control.
27496 For example, if the body of @code{B} said
27497
27498 @smallexample @c ada
27499 @group
27500 @cartouche
27501 function B return Integer is
27502 begin
27503    if some-condition-depending-on-input-data then
27504       return A;
27505    else
27506       return 1;
27507    end if;
27508 end B;
27509 @end cartouche
27510 @end group
27511 @end smallexample
27512
27513 @noindent
27514 then we could not know until run time whether the incorrect call to A would
27515 actually occur, so @code{Program_Error} might
27516 or might not be raised. It is possible for a compiler to
27517 do a better job of analyzing bodies, to
27518 determine whether or not @code{Program_Error}
27519 might be raised, but it certainly
27520 couldn't do a perfect job (that would require solving the halting problem
27521 and is provably impossible), and because this is a warning anyway, it does
27522 not seem worth the effort to do the analysis. Cases in which it
27523 would be relevant are rare.
27524
27525 In practice, warnings of either of the forms given
27526 above will usually correspond to
27527 real errors, and should be examined carefully and eliminated.
27528 In the rare case where a warning is bogus, it can be suppressed by any of
27529 the following methods:
27530
27531 @itemize @bullet
27532 @item
27533 Compile with the @option{-gnatws} switch set
27534
27535 @item
27536 Suppress @code{Elaboration_Check} for the called subprogram
27537
27538 @item
27539 Use pragma @code{Warnings_Off} to turn warnings off for the call
27540 @end itemize
27541
27542 @noindent
27543 For the internal elaboration check case,
27544 GNAT by default generates the
27545 necessary run-time checks to ensure
27546 that @code{Program_Error} is raised if any
27547 call fails an elaboration check. Of course this can only happen if a
27548 warning has been issued as described above. The use of pragma
27549 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
27550 some of these checks, meaning that it may be possible (but is not
27551 guaranteed) for a program to be able to call a subprogram whose body
27552 is not yet elaborated, without raising a @code{Program_Error} exception.
27553
27554 @node Controlling Elaboration in GNAT - External Calls
27555 @section Controlling Elaboration in GNAT - External Calls
27556
27557 @noindent
27558 The previous section discussed the case in which the execution of a
27559 particular thread of elaboration code occurred entirely within a
27560 single unit. This is the easy case to handle, because a programmer
27561 has direct and total control over the order of elaboration, and
27562 furthermore, checks need only be generated in cases which are rare
27563 and which the compiler can easily detect.
27564 The situation is more complex when separate compilation is taken into account.
27565 Consider the following:
27566
27567 @smallexample @c ada
27568 @cartouche
27569 @group
27570 package Math is
27571    function Sqrt (Arg : Float) return Float;
27572 end Math;
27573
27574 package body Math is
27575    function Sqrt (Arg : Float) return Float is
27576    begin
27577          @dots{}
27578    end Sqrt;
27579 end Math;
27580 @end group
27581 @group
27582 with Math;
27583 package Stuff is
27584    X : Float := Math.Sqrt (0.5);
27585 end Stuff;
27586
27587 with Stuff;
27588 procedure Main is
27589 begin
27590    @dots{}
27591 end Main;
27592 @end group
27593 @end cartouche
27594 @end smallexample
27595
27596 @noindent
27597 where @code{Main} is the main program. When this program is executed, the
27598 elaboration code must first be executed, and one of the jobs of the
27599 binder is to determine the order in which the units of a program are
27600 to be elaborated. In this case we have four units: the spec and body
27601 of @code{Math},
27602 the spec of @code{Stuff} and the body of @code{Main}).
27603 In what order should the four separate sections of elaboration code
27604 be executed?
27605
27606 There are some restrictions in the order of elaboration that the binder
27607 can choose. In particular, if unit U has a @code{with}
27608 for a package @code{X}, then you
27609 are assured that the spec of @code{X}
27610 is elaborated before U , but you are
27611 not assured that the body of @code{X}
27612 is elaborated before U.
27613 This means that in the above case, the binder is allowed to choose the
27614 order:
27615
27616 @smallexample
27617 spec of Math
27618 spec of Stuff
27619 body of Math
27620 body of Main
27621 @end smallexample
27622
27623 @noindent
27624 but that's not good, because now the call to @code{Math.Sqrt}
27625 that happens during
27626 the elaboration of the @code{Stuff}
27627 spec happens before the body of @code{Math.Sqrt} is
27628 elaborated, and hence causes @code{Program_Error} exception to be raised.
27629 At first glance, one might say that the binder is misbehaving, because
27630 obviously you want to elaborate the body of something you @code{with}
27631 first, but
27632 that is not a general rule that can be followed in all cases. Consider
27633
27634 @smallexample @c ada
27635 @group
27636 @cartouche
27637 package X is @dots{}
27638
27639 package Y is @dots{}
27640
27641 with X;
27642 package body Y is @dots{}
27643
27644 with Y;
27645 package body X is @dots{}
27646 @end cartouche
27647 @end group
27648 @end smallexample
27649
27650 @noindent
27651 This is a common arrangement, and, apart from the order of elaboration
27652 problems that might arise in connection with elaboration code, this works fine.
27653 A rule that says that you must first elaborate the body of anything you
27654 @code{with} cannot work in this case:
27655 the body of @code{X} @code{with}'s @code{Y},
27656 which means you would have to
27657 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
27658 which means
27659 you have to elaborate the body of @code{X} first, but @dots{} and we have a
27660 loop that cannot be broken.
27661
27662 It is true that the binder can in many cases guess an order of elaboration
27663 that is unlikely to cause a @code{Program_Error}
27664 exception to be raised, and it tries to do so (in the
27665 above example of @code{Math/Stuff/Spec}, the GNAT binder will
27666 by default
27667 elaborate the body of @code{Math} right after its spec, so all will be well).
27668
27669 However, a program that blindly relies on the binder to be helpful can
27670 get into trouble, as we discussed in the previous sections, so
27671 GNAT
27672 provides a number of facilities for assisting the programmer in
27673 developing programs that are robust with respect to elaboration order.
27674
27675 @node Default Behavior in GNAT - Ensuring Safety
27676 @section Default Behavior in GNAT - Ensuring Safety
27677
27678 @noindent
27679 The default behavior in GNAT ensures elaboration safety. In its
27680 default mode GNAT implements the
27681 rule we previously described as the right approach. Let's restate it:
27682
27683 @itemize
27684 @item
27685 @emph{If a unit has elaboration code that can directly or indirectly make a
27686 call to a subprogram in a @code{with}'ed unit, or instantiate a generic
27687 package in a @code{with}'ed unit, then if the @code{with}'ed unit
27688 does not have pragma @code{Pure} or
27689 @code{Preelaborate}, then the client should have an
27690 @code{Elaborate_All} pragma for the @code{with}'ed unit.}
27691
27692 @emph{In the case of instantiating a generic subprogram, it is always
27693 sufficient to have only an @code{Elaborate} pragma for the
27694 @code{with}'ed unit.}
27695 @end itemize
27696
27697 @noindent
27698 By following this rule a client is assured that calls and instantiations
27699 can be made without risk of an exception.
27700
27701 In this mode GNAT traces all calls that are potentially made from
27702 elaboration code, and puts in any missing implicit @code{Elaborate}
27703 and @code{Elaborate_All} pragmas.
27704 The advantage of this approach is that no elaboration problems
27705 are possible if the binder can find an elaboration order that is
27706 consistent with these implicit @code{Elaborate} and
27707 @code{Elaborate_All} pragmas. The
27708 disadvantage of this approach is that no such order may exist.
27709
27710 If the binder does not generate any diagnostics, then it means that it has
27711 found an elaboration order that is guaranteed to be safe. However, the binder
27712 may still be relying on implicitly generated @code{Elaborate} and
27713 @code{Elaborate_All} pragmas so portability to other compilers than GNAT is not
27714 guaranteed.
27715
27716 If it is important to guarantee portability, then the compilations should
27717 use the
27718 @option{-gnatwl}
27719 (warn on elaboration problems) switch. This will cause warning messages
27720 to be generated indicating the missing @code{Elaborate} and
27721 @code{Elaborate_All} pragmas.
27722 Consider the following source program:
27723
27724 @smallexample @c ada
27725 @group
27726 @cartouche
27727 with k;
27728 package j is
27729   m : integer := k.r;
27730 end;
27731 @end cartouche
27732 @end group
27733 @end smallexample
27734
27735 @noindent
27736 where it is clear that there
27737 should be a pragma @code{Elaborate_All}
27738 for unit @code{k}. An implicit pragma will be generated, and it is
27739 likely that the binder will be able to honor it. However, if you want
27740 to port this program to some other Ada compiler than GNAT.
27741 it is safer to include the pragma explicitly in the source. If this
27742 unit is compiled with the
27743 @option{-gnatwl}
27744 switch, then the compiler outputs a warning:
27745
27746 @smallexample
27747 @group
27748 @cartouche
27749 1. with k;
27750 2. package j is
27751 3.   m : integer := k.r;
27752                      |
27753    >>> warning: call to "r" may raise Program_Error
27754    >>> warning: missing pragma Elaborate_All for "k"
27755
27756 4. end;
27757 @end cartouche
27758 @end group
27759 @end smallexample
27760
27761 @noindent
27762 and these warnings can be used as a guide for supplying manually
27763 the missing pragmas. It is usually a bad idea to use this warning
27764 option during development. That's because it will warn you when
27765 you need to put in a pragma, but cannot warn you when it is time
27766 to take it out. So the use of pragma @code{Elaborate_All} may lead to
27767 unnecessary dependencies and even false circularities.
27768
27769 This default mode is more restrictive than the Ada Reference
27770 Manual, and it is possible to construct programs which will compile
27771 using the dynamic model described there, but will run into a
27772 circularity using the safer static model we have described.
27773
27774 Of course any Ada compiler must be able to operate in a mode
27775 consistent with the requirements of the Ada Reference Manual,
27776 and in particular must have the capability of implementing the
27777 standard dynamic model of elaboration with run-time checks.
27778
27779 In GNAT, this standard mode can be achieved either by the use of
27780 the @option{-gnatE} switch on the compiler (@command{gcc} or
27781 @command{gnatmake}) command, or by the use of the configuration pragma:
27782
27783 @smallexample @c ada
27784 pragma Elaboration_Checks (RM);
27785 @end smallexample
27786
27787 @noindent
27788 Either approach will cause the unit affected to be compiled using the
27789 standard dynamic run-time elaboration checks described in the Ada
27790 Reference Manual. The static model is generally preferable, since it
27791 is clearly safer to rely on compile and link time checks rather than
27792 run-time checks. However, in the case of legacy code, it may be
27793 difficult to meet the requirements of the static model. This
27794 issue is further discussed in
27795 @ref{What to Do If the Default Elaboration Behavior Fails}.
27796
27797 Note that the static model provides a strict subset of the allowed
27798 behavior and programs of the Ada Reference Manual, so if you do
27799 adhere to the static model and no circularities exist,
27800 then you are assured that your program will
27801 work using the dynamic model, providing that you remove any
27802 pragma Elaborate statements from the source.
27803
27804 @node Treatment of Pragma Elaborate
27805 @section Treatment of Pragma Elaborate
27806 @cindex Pragma Elaborate
27807
27808 @noindent
27809 The use of @code{pragma Elaborate}
27810 should generally be avoided in Ada 95 and Ada 2005 programs,
27811 since there is no guarantee that transitive calls
27812 will be properly handled. Indeed at one point, this pragma was placed
27813 in Annex J (Obsolescent Features), on the grounds that it is never useful.
27814
27815 Now that's a bit restrictive. In practice, the case in which
27816 @code{pragma Elaborate} is useful is when the caller knows that there
27817 are no transitive calls, or that the called unit contains all necessary
27818 transitive @code{pragma Elaborate} statements, and legacy code often
27819 contains such uses.
27820
27821 Strictly speaking the static mode in GNAT should ignore such pragmas,
27822 since there is no assurance at compile time that the necessary safety
27823 conditions are met. In practice, this would cause GNAT to be incompatible
27824 with correctly written Ada 83 code that had all necessary
27825 @code{pragma Elaborate} statements in place. Consequently, we made the
27826 decision that GNAT in its default mode will believe that if it encounters
27827 a @code{pragma Elaborate} then the programmer knows what they are doing,
27828 and it will trust that no elaboration errors can occur.
27829
27830 The result of this decision is two-fold. First to be safe using the
27831 static mode, you should remove all @code{pragma Elaborate} statements.
27832 Second, when fixing circularities in existing code, you can selectively
27833 use @code{pragma Elaborate} statements to convince the static mode of
27834 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
27835 statement.
27836
27837 When using the static mode with @option{-gnatwl}, any use of
27838 @code{pragma Elaborate} will generate a warning about possible
27839 problems.
27840
27841 @node Elaboration Issues for Library Tasks
27842 @section Elaboration Issues for Library Tasks
27843 @cindex Library tasks, elaboration issues
27844 @cindex Elaboration of library tasks
27845
27846 @noindent
27847 In this section we examine special elaboration issues that arise for
27848 programs that declare library level tasks.
27849
27850 Generally the model of execution of an Ada program is that all units are
27851 elaborated, and then execution of the program starts. However, the
27852 declaration of library tasks definitely does not fit this model. The
27853 reason for this is that library tasks start as soon as they are declared
27854 (more precisely, as soon as the statement part of the enclosing package
27855 body is reached), that is to say before elaboration
27856 of the program is complete. This means that if such a task calls a
27857 subprogram, or an entry in another task, the callee may or may not be
27858 elaborated yet, and in the standard
27859 Reference Manual model of dynamic elaboration checks, you can even
27860 get timing dependent Program_Error exceptions, since there can be
27861 a race between the elaboration code and the task code.
27862
27863 The static model of elaboration in GNAT seeks to avoid all such
27864 dynamic behavior, by being conservative, and the conservative
27865 approach in this particular case is to assume that all the code
27866 in a task body is potentially executed at elaboration time if
27867 a task is declared at the library level.
27868
27869 This can definitely result in unexpected circularities. Consider
27870 the following example
27871
27872 @smallexample @c ada
27873 package Decls is
27874   task Lib_Task is
27875      entry Start;
27876   end Lib_Task;
27877
27878   type My_Int is new Integer;
27879
27880   function Ident (M : My_Int) return My_Int;
27881 end Decls;
27882
27883 with Utils;
27884 package body Decls is
27885   task body Lib_Task is
27886   begin
27887      accept Start;
27888      Utils.Put_Val (2);
27889   end Lib_Task;
27890
27891   function Ident (M : My_Int) return My_Int is
27892   begin
27893      return M;
27894   end Ident;
27895 end Decls;
27896
27897 with Decls;
27898 package Utils is
27899   procedure Put_Val (Arg : Decls.My_Int);
27900 end Utils;
27901
27902 with Text_IO;
27903 package body Utils is
27904   procedure Put_Val (Arg : Decls.My_Int) is
27905   begin
27906      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
27907   end Put_Val;
27908 end Utils;
27909
27910 with Decls;
27911 procedure Main is
27912 begin
27913    Decls.Lib_Task.Start;
27914 end;
27915 @end smallexample
27916
27917 @noindent
27918 If the above example is compiled in the default static elaboration
27919 mode, then a circularity occurs. The circularity comes from the call
27920 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
27921 this call occurs in elaboration code, we need an implicit pragma
27922 @code{Elaborate_All} for @code{Utils}. This means that not only must
27923 the spec and body of @code{Utils} be elaborated before the body
27924 of @code{Decls}, but also the spec and body of any unit that is
27925 @code{with'ed} by the body of @code{Utils} must also be elaborated before
27926 the body of @code{Decls}. This is the transitive implication of
27927 pragma @code{Elaborate_All} and it makes sense, because in general
27928 the body of @code{Put_Val} might have a call to something in a
27929 @code{with'ed} unit.
27930
27931 In this case, the body of Utils (actually its spec) @code{with's}
27932 @code{Decls}. Unfortunately this means that the body of @code{Decls}
27933 must be elaborated before itself, in case there is a call from the
27934 body of @code{Utils}.
27935
27936 Here is the exact chain of events we are worrying about:
27937
27938 @enumerate
27939 @item
27940 In the body of @code{Decls} a call is made from within the body of a library
27941 task to a subprogram in the package @code{Utils}. Since this call may
27942 occur at elaboration time (given that the task is activated at elaboration
27943 time), we have to assume the worst, i.e., that the
27944 call does happen at elaboration time.
27945
27946 @item
27947 This means that the body and spec of @code{Util} must be elaborated before
27948 the body of @code{Decls} so that this call does not cause an access before
27949 elaboration.
27950
27951 @item
27952 Within the body of @code{Util}, specifically within the body of
27953 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
27954 by this package.
27955
27956 @item
27957 One such @code{with}'ed package is package @code{Decls}, so there
27958 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
27959 In fact there is such a call in this example, but we would have to
27960 assume that there was such a call even if it were not there, since
27961 we are not supposed to write the body of @code{Decls} knowing what
27962 is in the body of @code{Utils}; certainly in the case of the
27963 static elaboration model, the compiler does not know what is in
27964 other bodies and must assume the worst.
27965
27966 @item
27967 This means that the spec and body of @code{Decls} must also be
27968 elaborated before we elaborate the unit containing the call, but
27969 that unit is @code{Decls}! This means that the body of @code{Decls}
27970 must be elaborated before itself, and that's a circularity.
27971 @end enumerate
27972
27973 @noindent
27974 Indeed, if you add an explicit pragma @code{Elaborate_All} for @code{Utils} in
27975 the body of @code{Decls} you will get a true Ada Reference Manual
27976 circularity that makes the program illegal.
27977
27978 In practice, we have found that problems with the static model of
27979 elaboration in existing code often arise from library tasks, so
27980 we must address this particular situation.
27981
27982 Note that if we compile and run the program above, using the dynamic model of
27983 elaboration (that is to say use the @option{-gnatE} switch),
27984 then it compiles, binds,
27985 links, and runs, printing the expected result of 2. Therefore in some sense
27986 the circularity here is only apparent, and we need to capture
27987 the properties of this program that  distinguish it from other library-level
27988 tasks that have real elaboration problems.
27989
27990 We have four possible answers to this question:
27991
27992 @itemize @bullet
27993
27994 @item
27995 Use the dynamic model of elaboration.
27996
27997 If we use the @option{-gnatE} switch, then as noted above, the program works.
27998 Why is this? If we examine the task body, it is apparent that the task cannot
27999 proceed past the
28000 @code{accept} statement until after elaboration has been completed, because
28001 the corresponding entry call comes from the main program, not earlier.
28002 This is why the dynamic model works here. But that's really giving
28003 up on a precise analysis, and we prefer to take this approach only if we cannot
28004 solve the
28005 problem in any other manner. So let us examine two ways to reorganize
28006 the program to avoid the potential elaboration problem.
28007
28008 @item
28009 Split library tasks into separate packages.
28010
28011 Write separate packages, so that library tasks are isolated from
28012 other declarations as much as possible. Let us look at a variation on
28013 the above program.
28014
28015 @smallexample @c ada
28016 package Decls1 is
28017   task Lib_Task is
28018      entry Start;
28019   end Lib_Task;
28020 end Decls1;
28021
28022 with Utils;
28023 package body Decls1 is
28024   task body Lib_Task is
28025   begin
28026      accept Start;
28027      Utils.Put_Val (2);
28028   end Lib_Task;
28029 end Decls1;
28030
28031 package Decls2 is
28032   type My_Int is new Integer;
28033   function Ident (M : My_Int) return My_Int;
28034 end Decls2;
28035
28036 with Utils;
28037 package body Decls2 is
28038   function Ident (M : My_Int) return My_Int is
28039   begin
28040      return M;
28041   end Ident;
28042 end Decls2;
28043
28044 with Decls2;
28045 package Utils is
28046   procedure Put_Val (Arg : Decls2.My_Int);
28047 end Utils;
28048
28049 with Text_IO;
28050 package body Utils is
28051   procedure Put_Val (Arg : Decls2.My_Int) is
28052   begin
28053      Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
28054   end Put_Val;
28055 end Utils;
28056
28057 with Decls1;
28058 procedure Main is
28059 begin
28060    Decls1.Lib_Task.Start;
28061 end;
28062 @end smallexample
28063
28064 @noindent
28065 All we have done is to split @code{Decls} into two packages, one
28066 containing the library task, and one containing everything else. Now
28067 there is no cycle, and the program compiles, binds, links and executes
28068 using the default static model of elaboration.
28069
28070 @item
28071 Declare separate task types.
28072
28073 A significant part of the problem arises because of the use of the
28074 single task declaration form. This means that the elaboration of
28075 the task type, and the elaboration of the task itself (i.e.@: the
28076 creation of the task) happen at the same time. A good rule
28077 of style in Ada is to always create explicit task types. By
28078 following the additional step of placing task objects in separate
28079 packages from the task type declaration, many elaboration problems
28080 are avoided. Here is another modified example of the example program:
28081
28082 @smallexample @c ada
28083 package Decls is
28084   task type Lib_Task_Type is
28085      entry Start;
28086   end Lib_Task_Type;
28087
28088   type My_Int is new Integer;
28089
28090   function Ident (M : My_Int) return My_Int;
28091 end Decls;
28092
28093 with Utils;
28094 package body Decls is
28095   task body Lib_Task_Type is
28096   begin
28097      accept Start;
28098      Utils.Put_Val (2);
28099   end Lib_Task_Type;
28100
28101   function Ident (M : My_Int) return My_Int is
28102   begin
28103      return M;
28104   end Ident;
28105 end Decls;
28106
28107 with Decls;
28108 package Utils is
28109   procedure Put_Val (Arg : Decls.My_Int);
28110 end Utils;
28111
28112 with Text_IO;
28113 package body Utils is
28114   procedure Put_Val (Arg : Decls.My_Int) is
28115   begin
28116      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
28117   end Put_Val;
28118 end Utils;
28119
28120 with Decls;
28121 package Declst is
28122    Lib_Task : Decls.Lib_Task_Type;
28123 end Declst;
28124
28125 with Declst;
28126 procedure Main is
28127 begin
28128    Declst.Lib_Task.Start;
28129 end;
28130 @end smallexample
28131
28132 @noindent
28133 What we have done here is to replace the @code{task} declaration in
28134 package @code{Decls} with a @code{task type} declaration. Then we
28135 introduce a separate package @code{Declst} to contain the actual
28136 task object. This separates the elaboration issues for
28137 the @code{task type}
28138 declaration, which causes no trouble, from the elaboration issues
28139 of the task object, which is also unproblematic, since it is now independent
28140 of the elaboration of  @code{Utils}.
28141 This separation of concerns also corresponds to
28142 a generally sound engineering principle of separating declarations
28143 from instances. This version of the program also compiles, binds, links,
28144 and executes, generating the expected output.
28145
28146 @item
28147 Use No_Entry_Calls_In_Elaboration_Code restriction.
28148 @cindex No_Entry_Calls_In_Elaboration_Code
28149
28150 The previous two approaches described how a program can be restructured
28151 to avoid the special problems caused by library task bodies. in practice,
28152 however, such restructuring may be difficult to apply to existing legacy code,
28153 so we must consider solutions that do not require massive rewriting.
28154
28155 Let us consider more carefully why our original sample program works
28156 under the dynamic model of elaboration. The reason is that the code
28157 in the task body blocks immediately on the @code{accept}
28158 statement. Now of course there is nothing to prohibit elaboration
28159 code from making entry calls (for example from another library level task),
28160 so we cannot tell in isolation that
28161 the task will not execute the accept statement  during elaboration.
28162
28163 However, in practice it is very unusual to see elaboration code
28164 make any entry calls, and the pattern of tasks starting
28165 at elaboration time and then immediately blocking on @code{accept} or
28166 @code{select} statements is very common. What this means is that
28167 the compiler is being too pessimistic when it analyzes the
28168 whole package body as though it might be executed at elaboration
28169 time.
28170
28171 If we know that the elaboration code contains no entry calls, (a very safe
28172 assumption most of the time, that could almost be made the default
28173 behavior), then we can compile all units of the program under control
28174 of the following configuration pragma:
28175
28176 @smallexample
28177 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
28178 @end smallexample
28179
28180 @noindent
28181 This pragma can be placed in the @file{gnat.adc} file in the usual
28182 manner. If we take our original unmodified program and compile it
28183 in the presence of a @file{gnat.adc} containing the above pragma,
28184 then once again, we can compile, bind, link, and execute, obtaining
28185 the expected result. In the presence of this pragma, the compiler does
28186 not trace calls in a task body, that appear after the first @code{accept}
28187 or @code{select} statement, and therefore does not report a potential
28188 circularity in the original program.
28189
28190 The compiler will check to the extent it can that the above
28191 restriction is not violated, but it is not always possible to do a
28192 complete check at compile time, so it is important to use this
28193 pragma only if the stated restriction is in fact met, that is to say
28194 no task receives an entry call before elaboration of all units is completed.
28195
28196 @end itemize
28197
28198 @node Mixing Elaboration Models
28199 @section Mixing Elaboration Models
28200 @noindent
28201 So far, we have assumed that the entire program is either compiled
28202 using the dynamic model or static model, ensuring consistency. It
28203 is possible to mix the two models, but rules have to be followed
28204 if this mixing is done to ensure that elaboration checks are not
28205 omitted.
28206
28207 The basic rule is that @emph{a unit compiled with the static model cannot
28208 be @code{with'ed} by a unit compiled with the dynamic model}. The
28209 reason for this is that in the static model, a unit assumes that
28210 its clients guarantee to use (the equivalent of) pragma
28211 @code{Elaborate_All} so that no elaboration checks are required
28212 in inner subprograms, and this assumption is violated if the
28213 client is compiled with dynamic checks.
28214
28215 The precise rule is as follows. A unit that is compiled with dynamic
28216 checks can only @code{with} a unit that meets at least one of the
28217 following criteria:
28218
28219 @itemize @bullet
28220
28221 @item
28222 The @code{with'ed} unit is itself compiled with dynamic elaboration
28223 checks (that is with the @option{-gnatE} switch.
28224
28225 @item
28226 The @code{with'ed} unit is an internal GNAT implementation unit from
28227 the System, Interfaces, Ada, or GNAT hierarchies.
28228
28229 @item
28230 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
28231
28232 @item
28233 The @code{with'ing} unit (that is the client) has an explicit pragma
28234 @code{Elaborate_All} for the @code{with'ed} unit.
28235
28236 @end itemize
28237
28238 @noindent
28239 If this rule is violated, that is if a unit with dynamic elaboration
28240 checks @code{with's} a unit that does not meet one of the above four
28241 criteria, then the binder (@code{gnatbind}) will issue a warning
28242 similar to that in the following example:
28243
28244 @smallexample
28245 warning: "x.ads" has dynamic elaboration checks and with's
28246 warning:   "y.ads" which has static elaboration checks
28247 @end smallexample
28248
28249 @noindent
28250 These warnings indicate that the rule has been violated, and that as a result
28251 elaboration checks may be missed in the resulting executable file.
28252 This warning may be suppressed using the @option{-ws} binder switch
28253 in the usual manner.
28254
28255 One useful application of this mixing rule is in the case of a subsystem
28256 which does not itself @code{with} units from the remainder of the
28257 application. In this case, the entire subsystem can be compiled with
28258 dynamic checks to resolve a circularity in the subsystem, while
28259 allowing the main application that uses this subsystem to be compiled
28260 using the more reliable default static model.
28261
28262 @node What to Do If the Default Elaboration Behavior Fails
28263 @section What to Do If the Default Elaboration Behavior Fails
28264
28265 @noindent
28266 If the binder cannot find an acceptable order, it outputs detailed
28267 diagnostics. For example:
28268 @smallexample
28269 @group
28270 @iftex
28271 @leftskip=0cm
28272 @end iftex
28273 error: elaboration circularity detected
28274 info:   "proc (body)" must be elaborated before "pack (body)"
28275 info:     reason: Elaborate_All probably needed in unit "pack (body)"
28276 info:     recompile "pack (body)" with -gnatwl
28277 info:                             for full details
28278 info:       "proc (body)"
28279 info:         is needed by its spec:
28280 info:       "proc (spec)"
28281 info:         which is withed by:
28282 info:       "pack (body)"
28283 info:  "pack (body)" must be elaborated before "proc (body)"
28284 info:     reason: pragma Elaborate in unit "proc (body)"
28285 @end group
28286
28287 @end smallexample
28288
28289 @noindent
28290 In this case we have a cycle that the binder cannot break. On the one
28291 hand, there is an explicit pragma Elaborate in @code{proc} for
28292 @code{pack}. This means that the body of @code{pack} must be elaborated
28293 before the body of @code{proc}. On the other hand, there is elaboration
28294 code in @code{pack} that calls a subprogram in @code{proc}. This means
28295 that for maximum safety, there should really be a pragma
28296 Elaborate_All in @code{pack} for @code{proc} which would require that
28297 the body of @code{proc} be elaborated before the body of
28298 @code{pack}. Clearly both requirements cannot be satisfied.
28299 Faced with a circularity of this kind, you have three different options.
28300
28301 @table @asis
28302 @item Fix the program
28303 The most desirable option from the point of view of long-term maintenance
28304 is to rearrange the program so that the elaboration problems are avoided.
28305 One useful technique is to place the elaboration code into separate
28306 child packages. Another is to move some of the initialization code to
28307 explicitly called subprograms, where the program controls the order
28308 of initialization explicitly. Although this is the most desirable option,
28309 it may be impractical and involve too much modification, especially in
28310 the case of complex legacy code.
28311
28312 @item Perform dynamic checks
28313 If the compilations are done using the
28314 @option{-gnatE}
28315 (dynamic elaboration check) switch, then GNAT behaves in a quite different
28316 manner. Dynamic checks are generated for all calls that could possibly result
28317 in raising an exception. With this switch, the compiler does not generate
28318 implicit @code{Elaborate} or @code{Elaborate_All} pragmas. The behavior then is
28319 exactly as specified in the @cite{Ada Reference Manual}.
28320 The binder will generate
28321 an executable program that may or may not raise @code{Program_Error}, and then
28322 it is the programmer's job to ensure that it does not raise an exception. Note
28323 that it is important to compile all units with the switch, it cannot be used
28324 selectively.
28325
28326 @item Suppress checks
28327 The drawback of dynamic checks is that they generate a
28328 significant overhead at run time, both in space and time. If you
28329 are absolutely sure that your program cannot raise any elaboration
28330 exceptions, and you still want to use the dynamic elaboration model,
28331 then you can use the configuration pragma
28332 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
28333 example this pragma could be placed in the @file{gnat.adc} file.
28334
28335 @item Suppress checks selectively
28336 When you know that certain calls or instantiations in elaboration code cannot
28337 possibly lead to an elaboration error, and the binder nevertheless complains
28338 about implicit @code{Elaborate} and @code{Elaborate_All} pragmas that lead to
28339 elaboration circularities, it is possible to remove those warnings locally and
28340 obtain a program that will bind. Clearly this can be unsafe, and it is the
28341 responsibility of the programmer to make sure that the resulting program has no
28342 elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can be
28343 used with different granularity to suppress warnings and break elaboration
28344 circularities:
28345
28346 @itemize @bullet
28347 @item
28348 Place the pragma that names the called subprogram in the declarative part
28349 that contains the call.
28350
28351 @item
28352 Place the pragma in the declarative part, without naming an entity. This
28353 disables warnings on all calls in the corresponding  declarative region.
28354
28355 @item
28356 Place the pragma in the package spec that declares the called subprogram,
28357 and name the subprogram. This disables warnings on all elaboration calls to
28358 that subprogram.
28359
28360 @item
28361 Place the pragma in the package spec that declares the called subprogram,
28362 without naming any entity. This disables warnings on all elaboration calls to
28363 all subprograms declared in this spec.
28364
28365 @item Use Pragma Elaborate
28366 As previously described in section @xref{Treatment of Pragma Elaborate},
28367 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
28368 that no elaboration checks are required on calls to the designated unit.
28369 There may be cases in which the caller knows that no transitive calls
28370 can occur, so that a @code{pragma Elaborate} will be sufficient in a
28371 case where @code{pragma Elaborate_All} would cause a circularity.
28372 @end itemize
28373
28374 @noindent
28375 These five cases are listed in order of decreasing safety, and therefore
28376 require increasing programmer care in their application. Consider the
28377 following program:
28378
28379 @smallexample @c adanocomment
28380 package Pack1 is
28381   function F1 return Integer;
28382   X1 : Integer;
28383 end Pack1;
28384
28385 package Pack2 is
28386   function F2 return Integer;
28387   function Pure (x : integer) return integer;
28388   --  pragma Suppress (Elaboration_Check, On => Pure);  -- (3)
28389   --  pragma Suppress (Elaboration_Check);              -- (4)
28390 end Pack2;
28391
28392 with Pack2;
28393 package body Pack1 is
28394   function F1 return Integer is
28395   begin
28396     return 100;
28397   end F1;
28398   Val : integer := Pack2.Pure (11);    --  Elab. call (1)
28399 begin
28400   declare
28401     --  pragma Suppress(Elaboration_Check, Pack2.F2);   -- (1)
28402     --  pragma Suppress(Elaboration_Check);             -- (2)
28403   begin
28404     X1 := Pack2.F2 + 1;                --  Elab. call (2)
28405   end;
28406 end Pack1;
28407
28408 with Pack1;
28409 package body Pack2 is
28410   function F2 return Integer is
28411   begin
28412      return Pack1.F1;
28413   end F2;
28414   function Pure (x : integer) return integer is
28415   begin
28416      return x ** 3 - 3 * x;
28417   end;
28418 end Pack2;
28419
28420 with Pack1, Ada.Text_IO;
28421 procedure Proc3 is
28422 begin
28423   Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
28424 end Proc3;
28425 @end smallexample
28426 In the absence of any pragmas, an attempt to bind this program produces
28427 the following diagnostics:
28428 @smallexample
28429 @group
28430 @iftex
28431 @leftskip=.5cm
28432 @end iftex
28433 error: elaboration circularity detected
28434 info:    "pack1 (body)" must be elaborated before "pack1 (body)"
28435 info:       reason: Elaborate_All probably needed in unit "pack1 (body)"
28436 info:       recompile "pack1 (body)" with -gnatwl for full details
28437 info:          "pack1 (body)"
28438 info:             must be elaborated along with its spec:
28439 info:          "pack1 (spec)"
28440 info:             which is withed by:
28441 info:          "pack2 (body)"
28442 info:             which must be elaborated along with its spec:
28443 info:          "pack2 (spec)"
28444 info:             which is withed by:
28445 info:          "pack1 (body)"
28446 @end group
28447 @end smallexample
28448 The sources of the circularity are the two calls to @code{Pack2.Pure} and
28449 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
28450 F2 is safe, even though F2 calls F1, because the call appears after the
28451 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
28452 remove the warning on the call. It is also possible to use pragma (2)
28453 because there are no other potentially unsafe calls in the block.
28454
28455 @noindent
28456 The call to @code{Pure} is safe because this function does not depend on the
28457 state of @code{Pack2}. Therefore any call to this function is safe, and it
28458 is correct to place pragma (3) in the corresponding package spec.
28459
28460 @noindent
28461 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
28462 warnings on all calls to functions declared therein. Note that this is not
28463 necessarily safe, and requires more detailed examination of the subprogram
28464 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
28465 be already elaborated.
28466 @end table
28467
28468 @noindent
28469 It is hard to generalize on which of these four approaches should be
28470 taken. Obviously if it is possible to fix the program so that the default
28471 treatment works, this is preferable, but this may not always be practical.
28472 It is certainly simple enough to use
28473 @option{-gnatE}
28474 but the danger in this case is that, even if the GNAT binder
28475 finds a correct elaboration order, it may not always do so,
28476 and certainly a binder from another Ada compiler might not. A
28477 combination of testing and analysis (for which the warnings generated
28478 with the
28479 @option{-gnatwl}
28480 switch can be useful) must be used to ensure that the program is free
28481 of errors. One switch that is useful in this testing is the
28482 @option{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
28483 switch for
28484 @code{gnatbind}.
28485 Normally the binder tries to find an order that has the best chance
28486 of avoiding elaboration problems. However, if this switch is used, the binder
28487 plays a devil's advocate role, and tries to choose the order that
28488 has the best chance of failing. If your program works even with this
28489 switch, then it has a better chance of being error free, but this is still
28490 not a guarantee.
28491
28492 For an example of this approach in action, consider the C-tests (executable
28493 tests) from the ACVC suite. If these are compiled and run with the default
28494 treatment, then all but one of them succeed without generating any error
28495 diagnostics from the binder. However, there is one test that fails, and
28496 this is not surprising, because the whole point of this test is to ensure
28497 that the compiler can handle cases where it is impossible to determine
28498 a correct order statically, and it checks that an exception is indeed
28499 raised at run time.
28500
28501 This one test must be compiled and run using the
28502 @option{-gnatE}
28503 switch, and then it passes. Alternatively, the entire suite can
28504 be run using this switch. It is never wrong to run with the dynamic
28505 elaboration switch if your code is correct, and we assume that the
28506 C-tests are indeed correct (it is less efficient, but efficiency is
28507 not a factor in running the ACVC tests.)
28508
28509 @node Elaboration for Access-to-Subprogram Values
28510 @section Elaboration for Access-to-Subprogram Values
28511 @cindex Access-to-subprogram
28512
28513 @noindent
28514 Access-to-subprogram types (introduced in Ada 95) complicate
28515 the handling of elaboration. The trouble is that it becomes
28516 impossible to tell at compile time which procedure
28517 is being called. This means that it is not possible for the binder
28518 to analyze the elaboration requirements in this case.
28519
28520 If at the point at which the access value is created
28521 (i.e., the evaluation of @code{P'Access} for a subprogram @code{P}),
28522 the body of the subprogram is
28523 known to have been elaborated, then the access value is safe, and its use
28524 does not require a check. This may be achieved by appropriate arrangement
28525 of the order of declarations if the subprogram is in the current unit,
28526 or, if the subprogram is in another unit, by using pragma
28527 @code{Pure}, @code{Preelaborate}, or @code{Elaborate_Body}
28528 on the referenced unit.
28529
28530 If the referenced body is not known to have been elaborated at the point
28531 the access value is created, then any use of the access value must do a
28532 dynamic check, and this dynamic check will fail and raise a
28533 @code{Program_Error} exception if the body has not been elaborated yet.
28534 GNAT will generate the necessary checks, and in addition, if the
28535 @option{-gnatwl}
28536 switch is set, will generate warnings that such checks are required.
28537
28538 The use of dynamic dispatching for tagged types similarly generates
28539 a requirement for dynamic checks, and premature calls to any primitive
28540 operation of a tagged type before the body of the operation has been
28541 elaborated, will result in the raising of @code{Program_Error}.
28542
28543 @node Summary of Procedures for Elaboration Control
28544 @section Summary of Procedures for Elaboration Control
28545 @cindex Elaboration control
28546
28547 @noindent
28548 First, compile your program with the default options, using none of
28549 the special elaboration control switches. If the binder successfully
28550 binds your program, then you can be confident that, apart from issues
28551 raised by the use of access-to-subprogram types and dynamic dispatching,
28552 the program is free of elaboration errors. If it is important that the
28553 program be portable, then use the
28554 @option{-gnatwl}
28555 switch to generate warnings about missing @code{Elaborate} or
28556 @code{Elaborate_All} pragmas, and supply the missing pragmas.
28557
28558 If the program fails to bind using the default static elaboration
28559 handling, then you can fix the program to eliminate the binder
28560 message, or recompile the entire program with the
28561 @option{-gnatE} switch to generate dynamic elaboration checks,
28562 and, if you are sure there really are no elaboration problems,
28563 use a global pragma @code{Suppress (Elaboration_Check)}.
28564
28565 @node Other Elaboration Order Considerations
28566 @section Other Elaboration Order Considerations
28567 @noindent
28568 This section has been entirely concerned with the issue of finding a valid
28569 elaboration order, as defined by the Ada Reference Manual. In a case
28570 where several elaboration orders are valid, the task is to find one
28571 of the possible valid elaboration orders (and the static model in GNAT
28572 will ensure that this is achieved).
28573
28574 The purpose of the elaboration rules in the Ada Reference Manual is to
28575 make sure that no entity is accessed before it has been elaborated. For
28576 a subprogram, this means that the spec and body must have been elaborated
28577 before the subprogram is called. For an object, this means that the object
28578 must have been elaborated before its value is read or written. A violation
28579 of either of these two requirements is an access before elaboration order,
28580 and this section has been all about avoiding such errors.
28581
28582 In the case where more than one order of elaboration is possible, in the
28583 sense that access before elaboration errors are avoided, then any one of
28584 the orders is ``correct'' in the sense that it meets the requirements of
28585 the Ada Reference Manual, and no such error occurs.
28586
28587 However, it may be the case for a given program, that there are
28588 constraints on the order of elaboration that come not from consideration
28589 of avoiding elaboration errors, but rather from extra-lingual logic
28590 requirements. Consider this example:
28591
28592 @smallexample @c ada
28593 with Init_Constants;
28594 package Constants is
28595    X : Integer := 0;
28596    Y : Integer := 0;
28597 end Constants;
28598
28599 package Init_Constants is
28600    procedure P; -- require a body
28601 end Init_Constants;
28602
28603 with Constants;
28604 package body Init_Constants is
28605    procedure P is begin null; end;
28606 begin
28607    Constants.X := 3;
28608    Constants.Y := 4;
28609 end Init_Constants;
28610
28611 with Constants;
28612 package Calc is
28613    Z : Integer := Constants.X + Constants.Y;
28614 end Calc;
28615
28616 with Calc;
28617 with Text_IO; use Text_IO;
28618 procedure Main is
28619 begin
28620    Put_Line (Calc.Z'Img);
28621 end Main;
28622 @end smallexample
28623
28624 @noindent
28625 In this example, there is more than one valid order of elaboration. For
28626 example both the following are correct orders:
28627
28628 @smallexample
28629 Init_Constants spec
28630 Constants spec
28631 Calc spec
28632 Init_Constants body
28633 Main body
28634
28635   and
28636
28637 Init_Constants spec
28638 Init_Constants body
28639 Constants spec
28640 Calc spec
28641 Main body
28642 @end smallexample
28643
28644 @noindent
28645 There is no language rule to prefer one or the other, both are correct
28646 from an order of elaboration point of view. But the programmatic effects
28647 of the two orders are very different. In the first, the elaboration routine
28648 of @code{Calc} initializes @code{Z} to zero, and then the main program
28649 runs with this value of zero. But in the second order, the elaboration
28650 routine of @code{Calc} runs after the body of Init_Constants has set
28651 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
28652 runs.
28653
28654 One could perhaps by applying pretty clever non-artificial intelligence
28655 to the situation guess that it is more likely that the second order of
28656 elaboration is the one desired, but there is no formal linguistic reason
28657 to prefer one over the other. In fact in this particular case, GNAT will
28658 prefer the second order, because of the rule that bodies are elaborated
28659 as soon as possible, but it's just luck that this is what was wanted
28660 (if indeed the second order was preferred).
28661
28662 If the program cares about the order of elaboration routines in a case like
28663 this, it is important to specify the order required. In this particular
28664 case, that could have been achieved by adding to the spec of Calc:
28665
28666 @smallexample @c ada
28667 pragma Elaborate_All (Constants);
28668 @end smallexample
28669
28670 @noindent
28671 which requires that the body (if any) and spec of @code{Constants},
28672 as well as the body and spec of any unit @code{with}'ed by
28673 @code{Constants} be elaborated before @code{Calc} is elaborated.
28674
28675 Clearly no automatic method can always guess which alternative you require,
28676 and if you are working with legacy code that had constraints of this kind
28677 which were not properly specified by adding @code{Elaborate} or
28678 @code{Elaborate_All} pragmas, then indeed it is possible that two different
28679 compilers can choose different orders.
28680
28681 However, GNAT does attempt to diagnose the common situation where there
28682 are uninitialized variables in the visible part of a package spec, and the
28683 corresponding package body has an elaboration block that directly or
28684 indirectly initialized one or more of these variables. This is the situation
28685 in which a pragma Elaborate_Body is usually desirable, and GNAT will generate
28686 a warning that suggests this addition if it detects this situation.
28687
28688 The @code{gnatbind}
28689 @option{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
28690 out problems. This switch causes bodies to be elaborated as late as possible
28691 instead of as early as possible. In the example above, it would have forced
28692 the choice of the first elaboration order. If you get different results
28693 when using this switch, and particularly if one set of results is right,
28694 and one is wrong as far as you are concerned, it shows that you have some
28695 missing @code{Elaborate} pragmas. For the example above, we have the
28696 following output:
28697
28698 @smallexample
28699 gnatmake -f -q main
28700 main
28701  7
28702 gnatmake -f -q main -bargs -p
28703 main
28704  0
28705 @end smallexample
28706
28707 @noindent
28708 It is of course quite unlikely that both these results are correct, so
28709 it is up to you in a case like this to investigate the source of the
28710 difference, by looking at the two elaboration orders that are chosen,
28711 and figuring out which is correct, and then adding the necessary
28712 @code{Elaborate} or @code{Elaborate_All} pragmas to ensure the desired order.
28713
28714
28715
28716 @c *******************************
28717 @node Conditional Compilation
28718 @appendix Conditional Compilation
28719 @c *******************************
28720 @cindex Conditional compilation
28721
28722 @noindent
28723 It is often necessary to arrange for a single source program
28724 to serve multiple purposes, where it is compiled in different
28725 ways to achieve these different goals. Some examples of the
28726 need for this feature are
28727
28728 @itemize @bullet
28729 @item  Adapting a program to a different hardware environment
28730 @item  Adapting a program to a different target architecture
28731 @item  Turning debugging features on and off
28732 @item  Arranging for a program to compile with different compilers
28733 @end itemize
28734
28735 @noindent
28736 In C, or C++, the typical approach would be to use the preprocessor
28737 that is defined as part of the language. The Ada language does not
28738 contain such a feature. This is not an oversight, but rather a very
28739 deliberate design decision, based on the experience that overuse of
28740 the preprocessing features in C and C++ can result in programs that
28741 are extremely difficult to maintain. For example, if we have ten
28742 switches that can be on or off, this means that there are a thousand
28743 separate programs, any one of which might not even be syntactically
28744 correct, and even if syntactically correct, the resulting program
28745 might not work correctly. Testing all combinations can quickly become
28746 impossible.
28747
28748 Nevertheless, the need to tailor programs certainly exists, and in
28749 this Appendix we will discuss how this can
28750 be achieved using Ada in general, and GNAT in particular.
28751
28752 @menu
28753 * Use of Boolean Constants::
28754 * Debugging - A Special Case::
28755 * Conditionalizing Declarations::
28756 * Use of Alternative Implementations::
28757 * Preprocessing::
28758 @end menu
28759
28760 @node Use of Boolean Constants
28761 @section Use of Boolean Constants
28762
28763 @noindent
28764 In the case where the difference is simply which code
28765 sequence is executed, the cleanest solution is to use Boolean
28766 constants to control which code is executed.
28767
28768 @smallexample @c ada
28769 @group
28770 FP_Initialize_Required : constant Boolean := True;
28771 @dots{}
28772 if FP_Initialize_Required then
28773 @dots{}
28774 end if;
28775 @end group
28776 @end smallexample
28777
28778 @noindent
28779 Not only will the code inside the @code{if} statement not be executed if
28780 the constant Boolean is @code{False}, but it will also be completely
28781 deleted from the program.
28782 However, the code is only deleted after the @code{if} statement
28783 has been checked for syntactic and semantic correctness.
28784 (In contrast, with preprocessors the code is deleted before the
28785 compiler ever gets to see it, so it is not checked until the switch
28786 is turned on.)
28787 @cindex Preprocessors (contrasted with conditional compilation)
28788
28789 Typically the Boolean constants will be in a separate package,
28790 something like:
28791
28792 @smallexample @c ada
28793 @group
28794 package Config is
28795    FP_Initialize_Required : constant Boolean := True;
28796    Reset_Available        : constant Boolean := False;
28797    @dots{}
28798 end Config;
28799 @end group
28800 @end smallexample
28801
28802 @noindent
28803 The @code{Config} package exists in multiple forms for the various targets,
28804 with an appropriate script selecting the version of @code{Config} needed.
28805 Then any other unit requiring conditional compilation can do a @code{with}
28806 of @code{Config} to make the constants visible.
28807
28808
28809 @node Debugging - A Special Case
28810 @section Debugging - A Special Case
28811
28812 @noindent
28813 A common use of conditional code is to execute statements (for example
28814 dynamic checks, or output of intermediate results) under control of a
28815 debug switch, so that the debugging behavior can be turned on and off.
28816 This can be done using a Boolean constant to control whether the code
28817 is active:
28818
28819 @smallexample @c ada
28820 @group
28821 if Debugging then
28822    Put_Line ("got to the first stage!");
28823 end if;
28824 @end group
28825 @end smallexample
28826
28827 @noindent
28828 or
28829
28830 @smallexample @c ada
28831 @group
28832 if Debugging and then Temperature > 999.0 then
28833    raise Temperature_Crazy;
28834 end if;
28835 @end group
28836 @end smallexample
28837
28838 @noindent
28839 Since this is a common case, there are special features to deal with
28840 this in a convenient manner. For the case of tests, Ada 2005 has added
28841 a pragma @code{Assert} that can be used for such tests. This pragma is modeled
28842 @cindex pragma @code{Assert}
28843 on the @code{Assert} pragma that has always been available in GNAT, so this
28844 feature may be used with GNAT even if you are not using Ada 2005 features.
28845 The use of pragma @code{Assert} is described in
28846 @ref{Pragma Assert,,, gnat_rm, GNAT Reference Manual}, but as an
28847 example, the last test could be written:
28848
28849 @smallexample @c ada
28850 pragma Assert (Temperature <= 999.0, "Temperature Crazy");
28851 @end smallexample
28852
28853 @noindent
28854 or simply
28855
28856 @smallexample @c ada
28857 pragma Assert (Temperature <= 999.0);
28858 @end smallexample
28859
28860 @noindent
28861 In both cases, if assertions are active and the temperature is excessive,
28862 the exception @code{Assert_Failure} will be raised, with the given string in
28863 the first case or a string indicating the location of the pragma in the second
28864 case used as the exception message.
28865
28866 You can turn assertions on and off by using the @code{Assertion_Policy}
28867 pragma.
28868 @cindex pragma @code{Assertion_Policy}
28869 This is an Ada 2005 pragma which is implemented in all modes by
28870 GNAT, but only in the latest versions of GNAT which include Ada 2005
28871 capability. Alternatively, you can use the @option{-gnata} switch
28872 @cindex @option{-gnata} switch
28873 to enable assertions from the command line (this is recognized by all versions
28874 of GNAT).
28875
28876 For the example above with the @code{Put_Line}, the GNAT-specific pragma
28877 @code{Debug} can be used:
28878 @cindex pragma @code{Debug}
28879
28880 @smallexample @c ada
28881 pragma Debug (Put_Line ("got to the first stage!"));
28882 @end smallexample
28883
28884 @noindent
28885 If debug pragmas are enabled, the argument, which must be of the form of
28886 a procedure call, is executed (in this case, @code{Put_Line} will be called).
28887 Only one call can be present, but of course a special debugging procedure
28888 containing any code you like can be included in the program and then
28889 called in a pragma @code{Debug} argument as needed.
28890
28891 One advantage of pragma @code{Debug} over the @code{if Debugging then}
28892 construct is that pragma @code{Debug} can appear in declarative contexts,
28893 such as at the very beginning of a procedure, before local declarations have
28894 been elaborated.
28895
28896 Debug pragmas are enabled using either the @option{-gnata} switch that also
28897 controls assertions, or with a separate Debug_Policy pragma.
28898 @cindex pragma @code{Debug_Policy}
28899 The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
28900 in Ada 95 and Ada 83 programs as well), and is analogous to
28901 pragma @code{Assertion_Policy} to control assertions.
28902
28903 @code{Assertion_Policy} and @code{Debug_Policy} are configuration pragmas,
28904 and thus they can appear in @file{gnat.adc} if you are not using a
28905 project file, or in the file designated to contain configuration pragmas
28906 in a project file.
28907 They then apply to all subsequent compilations. In practice the use of
28908 the @option{-gnata} switch is often the most convenient method of controlling
28909 the status of these pragmas.
28910
28911 Note that a pragma is not a statement, so in contexts where a statement
28912 sequence is required, you can't just write a pragma on its own. You have
28913 to add a @code{null} statement.
28914
28915 @smallexample @c ada
28916 @group
28917 if @dots{} then
28918    @dots{} -- some statements
28919 else
28920    pragma Assert (Num_Cases < 10);
28921    null;
28922 end if;
28923 @end group
28924 @end smallexample
28925
28926
28927 @node Conditionalizing Declarations
28928 @section Conditionalizing Declarations
28929
28930 @noindent
28931 In some cases, it may be necessary to conditionalize declarations to meet
28932 different requirements. For example we might want a bit string whose length
28933 is set to meet some hardware message requirement.
28934
28935 In some cases, it may be possible to do this using declare blocks controlled
28936 by conditional constants:
28937
28938 @smallexample @c ada
28939 @group
28940 if Small_Machine then
28941    declare
28942       X : Bit_String (1 .. 10);
28943    begin
28944       @dots{}
28945    end;
28946 else
28947    declare
28948       X : Large_Bit_String (1 .. 1000);
28949    begin
28950       @dots{}
28951    end;
28952 end if;
28953 @end group
28954 @end smallexample
28955
28956 @noindent
28957 Note that in this approach, both declarations are analyzed by the
28958 compiler so this can only be used where both declarations are legal,
28959 even though one of them will not be used.
28960
28961 Another approach is to define integer constants, e.g.@: @code{Bits_Per_Word}, or
28962 Boolean constants, e.g.@: @code{Little_Endian}, and then write declarations
28963 that are parameterized by these constants. For example
28964
28965 @smallexample @c ada
28966 @group
28967 for Rec use
28968   Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
28969 end record;
28970 @end group
28971 @end smallexample
28972
28973 @noindent
28974 If @code{Bits_Per_Word} is set to 32, this generates either
28975
28976 @smallexample @c ada
28977 @group
28978 for Rec use
28979   Field1 at 0 range 0 .. 32;
28980 end record;
28981 @end group
28982 @end smallexample
28983
28984 @noindent
28985 for the big endian case, or
28986
28987 @smallexample @c ada
28988 @group
28989 for Rec use record
28990   Field1 at 0 range 10 .. 32;
28991 end record;
28992 @end group
28993 @end smallexample
28994
28995 @noindent
28996 for the little endian case. Since a powerful subset of Ada expression
28997 notation is usable for creating static constants, clever use of this
28998 feature can often solve quite difficult problems in conditionalizing
28999 compilation (note incidentally that in Ada 95, the little endian
29000 constant was introduced as @code{System.Default_Bit_Order}, so you do not
29001 need to define this one yourself).
29002
29003
29004 @node Use of Alternative Implementations
29005 @section Use of Alternative Implementations
29006
29007 @noindent
29008 In some cases, none of the approaches described above are adequate. This
29009 can occur for example if the set of declarations required is radically
29010 different for two different configurations.
29011
29012 In this situation, the official Ada way of dealing with conditionalizing
29013 such code is to write separate units for the different cases. As long as
29014 this does not result in excessive duplication of code, this can be done
29015 without creating maintenance problems. The approach is to share common
29016 code as far as possible, and then isolate the code and declarations
29017 that are different. Subunits are often a convenient method for breaking
29018 out a piece of a unit that is to be conditionalized, with separate files
29019 for different versions of the subunit for different targets, where the
29020 build script selects the right one to give to the compiler.
29021 @cindex Subunits (and conditional compilation)
29022
29023 As an example, consider a situation where a new feature in Ada 2005
29024 allows something to be done in a really nice way. But your code must be able
29025 to compile with an Ada 95 compiler. Conceptually you want to say:
29026
29027 @smallexample @c ada
29028 @group
29029 if Ada_2005 then
29030    @dots{} neat Ada 2005 code
29031 else
29032    @dots{} not quite as neat Ada 95 code
29033 end if;
29034 @end group
29035 @end smallexample
29036
29037 @noindent
29038 where @code{Ada_2005} is a Boolean constant.
29039
29040 But this won't work when @code{Ada_2005} is set to @code{False},
29041 since the @code{then} clause will be illegal for an Ada 95 compiler.
29042 (Recall that although such unreachable code would eventually be deleted
29043 by the compiler, it still needs to be legal.  If it uses features
29044 introduced in Ada 2005, it will be illegal in Ada 95.)
29045
29046 So instead we write
29047
29048 @smallexample @c ada
29049 procedure Insert is separate;
29050 @end smallexample
29051
29052 @noindent
29053 Then we have two files for the subunit @code{Insert}, with the two sets of
29054 code.
29055 If the package containing this is called @code{File_Queries}, then we might
29056 have two files
29057
29058 @itemize @bullet
29059 @item    @file{file_queries-insert-2005.adb}
29060 @item    @file{file_queries-insert-95.adb}
29061 @end itemize
29062
29063 @noindent
29064 and the build script renames the appropriate file to
29065
29066 @smallexample
29067 file_queries-insert.adb
29068 @end smallexample
29069
29070 @noindent
29071 and then carries out the compilation.
29072
29073 This can also be done with project files' naming schemes. For example:
29074
29075 @smallexample @c project
29076 For Body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
29077 @end smallexample
29078
29079 @noindent
29080 Note also that with project files it is desirable to use a different extension
29081 than @file{ads} / @file{adb} for alternative versions. Otherwise a naming
29082 conflict may arise through another commonly used feature: to declare as part
29083 of the project a set of directories containing all the sources obeying the
29084 default naming scheme.
29085
29086 The use of alternative units is certainly feasible in all situations,
29087 and for example the Ada part of the GNAT run-time is conditionalized
29088 based on the target architecture using this approach. As a specific example,
29089 consider the implementation of the AST feature in VMS. There is one
29090 spec:
29091
29092 @smallexample
29093 s-asthan.ads
29094 @end smallexample
29095
29096 @noindent
29097 which is the same for all architectures, and three bodies:
29098
29099 @table @file
29100 @item    s-asthan.adb
29101 used for all non-VMS operating systems
29102 @item    s-asthan-vms-alpha.adb
29103 used for VMS on the Alpha
29104 @item    s-asthan-vms-ia64.adb
29105 used for VMS on the ia64
29106 @end table
29107
29108 @noindent
29109 The dummy version @file{s-asthan.adb} simply raises exceptions noting that
29110 this operating system feature is not available, and the two remaining
29111 versions interface with the corresponding versions of VMS to provide
29112 VMS-compatible AST handling. The GNAT build script knows the architecture
29113 and operating system, and automatically selects the right version,
29114 renaming it if necessary to @file{s-asthan.adb} before the run-time build.
29115
29116 Another style for arranging alternative implementations is through Ada's
29117 access-to-subprogram facility.
29118 In case some functionality is to be conditionally included,
29119 you can declare an access-to-procedure variable @code{Ref} that is initialized
29120 to designate a ``do nothing'' procedure, and then invoke @code{Ref.all}
29121 when appropriate.
29122 In some library package, set @code{Ref} to @code{Proc'Access} for some
29123 procedure @code{Proc} that performs the relevant processing.
29124 The initialization only occurs if the library package is included in the
29125 program.
29126 The same idea can also be implemented using tagged types and dispatching
29127 calls.
29128
29129
29130 @node Preprocessing
29131 @section Preprocessing
29132 @cindex Preprocessing
29133
29134 @noindent
29135 Although it is quite possible to conditionalize code without the use of
29136 C-style preprocessing, as described earlier in this section, it is
29137 nevertheless convenient in some cases to use the C approach. Moreover,
29138 older Ada compilers have often provided some preprocessing capability,
29139 so legacy code may depend on this approach, even though it is not
29140 standard.
29141
29142 To accommodate such use, GNAT provides a preprocessor (modeled to a large
29143 extent on the various preprocessors that have been used
29144 with legacy code on other compilers, to enable easier transition).
29145
29146 The preprocessor may be used in two separate modes. It can be used quite
29147 separately from the compiler, to generate a separate output source file
29148 that is then fed to the compiler as a separate step. This is the
29149 @code{gnatprep} utility, whose use is fully described in
29150 @ref{Preprocessing Using gnatprep}.
29151 @cindex @code{gnatprep}
29152
29153 The preprocessing language allows such constructs as
29154
29155 @smallexample
29156 @group
29157 #if DEBUG or PRIORITY > 4 then
29158    bunch of declarations
29159 #else
29160    completely different bunch of declarations
29161 #end if;
29162 @end group
29163 @end smallexample
29164
29165 @noindent
29166 The values of the symbols @code{DEBUG} and @code{PRIORITY} can be
29167 defined either on the command line or in a separate file.
29168
29169 The other way of running the preprocessor is even closer to the C style and
29170 often more convenient. In this approach the preprocessing is integrated into
29171 the compilation process. The compiler is fed the preprocessor input which
29172 includes @code{#if} lines etc, and then the compiler carries out the
29173 preprocessing internally and processes the resulting output.
29174 For more details on this approach, see @ref{Integrated Preprocessing}.
29175
29176
29177 @c *******************************
29178 @node Inline Assembler
29179 @appendix Inline Assembler
29180 @c *******************************
29181
29182 @noindent
29183 If you need to write low-level software that interacts directly
29184 with the hardware, Ada provides two ways to incorporate assembly
29185 language code into your program.  First, you can import and invoke
29186 external routines written in assembly language, an Ada feature fully
29187 supported by GNAT@.  However, for small sections of code it may be simpler
29188 or more efficient to include assembly language statements directly
29189 in your Ada source program, using the facilities of the implementation-defined
29190 package @code{System.Machine_Code}, which incorporates the gcc
29191 Inline Assembler.  The Inline Assembler approach offers a number of advantages,
29192 including the following:
29193
29194 @itemize @bullet
29195 @item No need to use non-Ada tools
29196 @item Consistent interface over different targets
29197 @item Automatic usage of the proper calling conventions
29198 @item Access to Ada constants and variables
29199 @item Definition of intrinsic routines
29200 @item Possibility of inlining a subprogram comprising assembler code
29201 @item Code optimizer can take Inline Assembler code into account
29202 @end itemize
29203
29204 This chapter presents a series of examples to show you how to use
29205 the Inline Assembler.  Although it focuses on the Intel x86,
29206 the general approach applies also to other processors.
29207 It is assumed that you are familiar with Ada
29208 and with assembly language programming.
29209
29210 @menu
29211 * Basic Assembler Syntax::
29212 * A Simple Example of Inline Assembler::
29213 * Output Variables in Inline Assembler::
29214 * Input Variables in Inline Assembler::
29215 * Inlining Inline Assembler Code::
29216 * Other Asm Functionality::
29217 @end menu
29218
29219 @c ---------------------------------------------------------------------------
29220 @node Basic Assembler Syntax
29221 @section Basic Assembler Syntax
29222
29223 @noindent
29224 The assembler used by GNAT and gcc is based not on the Intel assembly
29225 language, but rather on a language that descends from the AT&T Unix
29226 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
29227 The following table summarizes the main features of @emph{as} syntax
29228 and points out the differences from the Intel conventions.
29229 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
29230 pre-processor) documentation for further information.
29231
29232 @table @asis
29233 @item Register names
29234 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
29235 @*
29236 Intel: No extra punctuation; for example @code{eax}
29237
29238 @item Immediate operand
29239 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
29240 @*
29241 Intel: No extra punctuation; for example @code{4}
29242
29243 @item Address
29244 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
29245 @*
29246 Intel: No extra punctuation; for example @code{loc}
29247
29248 @item Memory contents
29249 gcc / @emph{as}: No extra punctuation; for example @code{loc}
29250 @*
29251 Intel: Square brackets; for example @code{[loc]}
29252
29253 @item Register contents
29254 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
29255 @*
29256 Intel: Square brackets; for example @code{[eax]}
29257
29258 @item Hexadecimal numbers
29259 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
29260 @*
29261 Intel: Trailing ``h''; for example @code{A0h}
29262
29263 @item Operand size
29264 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
29265 a 16-bit word
29266 @*
29267 Intel: Implicit, deduced by assembler; for example @code{mov}
29268
29269 @item Instruction repetition
29270 gcc / @emph{as}: Split into two lines; for example
29271 @*
29272 @code{rep}
29273 @*
29274 @code{stosl}
29275 @*
29276 Intel: Keep on one line; for example @code{rep stosl}
29277
29278 @item Order of operands
29279 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
29280 @*
29281 Intel: Destination first; for example @code{mov eax, 4}
29282 @end table
29283
29284 @c ---------------------------------------------------------------------------
29285 @node A Simple Example of Inline Assembler
29286 @section A Simple Example of Inline Assembler
29287
29288 @noindent
29289 The following example will generate a single assembly language statement,
29290 @code{nop}, which does nothing.  Despite its lack of run-time effect,
29291 the example will be useful in illustrating the basics of
29292 the Inline Assembler facility.
29293
29294 @smallexample @c ada
29295 @group
29296 with System.Machine_Code; use System.Machine_Code;
29297 procedure Nothing is
29298 begin
29299    Asm ("nop");
29300 end Nothing;
29301 @end group
29302 @end smallexample
29303
29304 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
29305 here it takes one parameter, a @emph{template string} that must be a static
29306 expression and that will form the generated instruction.
29307 @code{Asm} may be regarded as a compile-time procedure that parses
29308 the template string and additional parameters (none here),
29309 from which it generates a sequence of assembly language instructions.
29310
29311 The examples in this chapter will illustrate several of the forms
29312 for invoking @code{Asm}; a complete specification of the syntax
29313 is found in @ref{Machine Code Insertions,,, gnat_rm, GNAT Reference
29314 Manual}.
29315
29316 Under the standard GNAT conventions, the @code{Nothing} procedure
29317 should be in a file named @file{nothing.adb}.
29318 You can build the executable in the usual way:
29319 @smallexample
29320 gnatmake nothing
29321 @end smallexample
29322 However, the interesting aspect of this example is not its run-time behavior
29323 but rather the generated assembly code.
29324 To see this output, invoke the compiler as follows:
29325 @smallexample
29326    gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
29327 @end smallexample
29328 where the options are:
29329
29330 @table @code
29331 @item -c
29332 compile only (no bind or link)
29333 @item -S
29334 generate assembler listing
29335 @item -fomit-frame-pointer
29336 do not set up separate stack frames
29337 @item -gnatp
29338 do not add runtime checks
29339 @end table
29340
29341 This gives a human-readable assembler version of the code. The resulting
29342 file will have the same name as the Ada source file, but with a @code{.s}
29343 extension. In our example, the file @file{nothing.s} has the following
29344 contents:
29345
29346 @smallexample
29347 @group
29348 .file "nothing.adb"
29349 gcc2_compiled.:
29350 ___gnu_compiled_ada:
29351 .text
29352    .align 4
29353 .globl __ada_nothing
29354 __ada_nothing:
29355 #APP
29356    nop
29357 #NO_APP
29358    jmp L1
29359    .align 2,0x90
29360 L1:
29361    ret
29362 @end group
29363 @end smallexample
29364
29365 The assembly code you included is clearly indicated by
29366 the compiler, between the @code{#APP} and @code{#NO_APP}
29367 delimiters. The character before the 'APP' and 'NOAPP'
29368 can differ on different targets. For example, GNU/Linux uses '#APP' while
29369 on NT you will see '/APP'.
29370
29371 If you make a mistake in your assembler code (such as using the
29372 wrong size modifier, or using a wrong operand for the instruction) GNAT
29373 will report this error in a temporary file, which will be deleted when
29374 the compilation is finished.  Generating an assembler file will help
29375 in such cases, since you can assemble this file separately using the
29376 @emph{as} assembler that comes with gcc.
29377
29378 Assembling the file using the command
29379
29380 @smallexample
29381 as @file{nothing.s}
29382 @end smallexample
29383 @noindent
29384 will give you error messages whose lines correspond to the assembler
29385 input file, so you can easily find and correct any mistakes you made.
29386 If there are no errors, @emph{as} will generate an object file
29387 @file{nothing.out}.
29388
29389 @c ---------------------------------------------------------------------------
29390 @node Output Variables in Inline Assembler
29391 @section Output Variables in Inline Assembler
29392
29393 @noindent
29394 The examples in this section, showing how to access the processor flags,
29395 illustrate how to specify the destination operands for assembly language
29396 statements.
29397
29398 @smallexample @c ada
29399 @group
29400 with Interfaces; use Interfaces;
29401 with Ada.Text_IO; use Ada.Text_IO;
29402 with System.Machine_Code; use System.Machine_Code;
29403 procedure Get_Flags is
29404    Flags : Unsigned_32;
29405    use ASCII;
29406 begin
29407    Asm ("pushfl"          & LF & HT & -- push flags on stack
29408         "popl %%eax"      & LF & HT & -- load eax with flags
29409         "movl %%eax, %0",             -- store flags in variable
29410         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
29411    Put_Line ("Flags register:" & Flags'Img);
29412 end Get_Flags;
29413 @end group
29414 @end smallexample
29415
29416 In order to have a nicely aligned assembly listing, we have separated
29417 multiple assembler statements in the Asm template string with linefeed
29418 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
29419 The resulting section of the assembly output file is:
29420
29421 @smallexample
29422 @group
29423 #APP
29424    pushfl
29425    popl %eax
29426    movl %eax, -40(%ebp)
29427 #NO_APP
29428 @end group
29429 @end smallexample
29430
29431 It would have been legal to write the Asm invocation as:
29432
29433 @smallexample
29434 Asm ("pushfl popl %%eax movl %%eax, %0")
29435 @end smallexample
29436
29437 but in the generated assembler file, this would come out as:
29438
29439 @smallexample
29440 #APP
29441    pushfl popl %eax movl %eax, -40(%ebp)
29442 #NO_APP
29443 @end smallexample
29444
29445 which is not so convenient for the human reader.
29446
29447 We use Ada comments
29448 at the end of each line to explain what the assembler instructions
29449 actually do.  This is a useful convention.
29450
29451 When writing Inline Assembler instructions, you need to precede each register
29452 and variable name with a percent sign.  Since the assembler already requires
29453 a percent sign at the beginning of a register name, you need two consecutive
29454 percent signs for such names in the Asm template string, thus @code{%%eax}.
29455 In the generated assembly code, one of the percent signs will be stripped off.
29456
29457 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
29458 variables: operands you later define using @code{Input} or @code{Output}
29459 parameters to @code{Asm}.
29460 An output variable is illustrated in
29461 the third statement in the Asm template string:
29462 @smallexample
29463 movl %%eax, %0
29464 @end smallexample
29465 The intent is to store the contents of the eax register in a variable that can
29466 be accessed in Ada.  Simply writing @code{movl %%eax, Flags} would not
29467 necessarily work, since the compiler might optimize by using a register
29468 to hold Flags, and the expansion of the @code{movl} instruction would not be
29469 aware of this optimization.  The solution is not to store the result directly
29470 but rather to advise the compiler to choose the correct operand form;
29471 that is the purpose of the @code{%0} output variable.
29472
29473 Information about the output variable is supplied in the @code{Outputs}
29474 parameter to @code{Asm}:
29475 @smallexample
29476 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
29477 @end smallexample
29478
29479 The output is defined by the @code{Asm_Output} attribute of the target type;
29480 the general format is
29481 @smallexample
29482 Type'Asm_Output (constraint_string, variable_name)
29483 @end smallexample
29484
29485 The constraint string directs the compiler how
29486 to store/access the associated variable.  In the example
29487 @smallexample
29488 Unsigned_32'Asm_Output ("=m", Flags);
29489 @end smallexample
29490 the @code{"m"} (memory) constraint tells the compiler that the variable
29491 @code{Flags} should be stored in a memory variable, thus preventing
29492 the optimizer from keeping it in a register.  In contrast,
29493 @smallexample
29494 Unsigned_32'Asm_Output ("=r", Flags);
29495 @end smallexample
29496 uses the @code{"r"} (register) constraint, telling the compiler to
29497 store the variable in a register.
29498
29499 If the constraint is preceded by the equal character (@strong{=}), it tells
29500 the compiler that the variable will be used to store data into it.
29501
29502 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
29503 allowing the optimizer to choose whatever it deems best.
29504
29505 There are a fairly large number of constraints, but the ones that are
29506 most useful (for the Intel x86 processor) are the following:
29507
29508 @table @code
29509 @item =
29510 output constraint
29511 @item g
29512 global (i.e.@: can be stored anywhere)
29513 @item m
29514 in memory
29515 @item I
29516 a constant
29517 @item a
29518 use eax
29519 @item b
29520 use ebx
29521 @item c
29522 use ecx
29523 @item d
29524 use edx
29525 @item S
29526 use esi
29527 @item D
29528 use edi
29529 @item r
29530 use one of eax, ebx, ecx or edx
29531 @item q
29532 use one of eax, ebx, ecx, edx, esi or edi
29533 @end table
29534
29535 The full set of constraints is described in the gcc and @emph{as}
29536 documentation; note that it is possible to combine certain constraints
29537 in one constraint string.
29538
29539 You specify the association of an output variable with an assembler operand
29540 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
29541 integer.  Thus in
29542 @smallexample @c ada
29543 @group
29544 Asm ("pushfl"          & LF & HT & -- push flags on stack
29545      "popl %%eax"      & LF & HT & -- load eax with flags
29546      "movl %%eax, %0",             -- store flags in variable
29547      Outputs => Unsigned_32'Asm_Output ("=g", Flags));
29548 @end group
29549 @end smallexample
29550 @noindent
29551 @code{%0} will be replaced in the expanded code by the appropriate operand,
29552 whatever
29553 the compiler decided for the @code{Flags} variable.
29554
29555 In general, you may have any number of output variables:
29556 @itemize @bullet
29557 @item
29558 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
29559 @item
29560 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
29561 of @code{Asm_Output} attributes
29562 @end itemize
29563
29564 For example:
29565 @smallexample @c ada
29566 @group
29567 Asm ("movl %%eax, %0" & LF & HT &
29568      "movl %%ebx, %1" & LF & HT &
29569      "movl %%ecx, %2",
29570      Outputs => (Unsigned_32'Asm_Output ("=g", Var_A),   --  %0 = Var_A
29571                  Unsigned_32'Asm_Output ("=g", Var_B),   --  %1 = Var_B
29572                  Unsigned_32'Asm_Output ("=g", Var_C))); --  %2 = Var_C
29573 @end group
29574 @end smallexample
29575 @noindent
29576 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
29577 in the Ada program.
29578
29579 As a variation on the @code{Get_Flags} example, we can use the constraints
29580 string to direct the compiler to store the eax register into the @code{Flags}
29581 variable, instead of including the store instruction explicitly in the
29582 @code{Asm} template string:
29583
29584 @smallexample @c ada
29585 @group
29586 with Interfaces; use Interfaces;
29587 with Ada.Text_IO; use Ada.Text_IO;
29588 with System.Machine_Code; use System.Machine_Code;
29589 procedure Get_Flags_2 is
29590    Flags : Unsigned_32;
29591    use ASCII;
29592 begin
29593    Asm ("pushfl"      & LF & HT & -- push flags on stack
29594         "popl %%eax",             -- save flags in eax
29595         Outputs => Unsigned_32'Asm_Output ("=a", Flags));
29596    Put_Line ("Flags register:" & Flags'Img);
29597 end Get_Flags_2;
29598 @end group
29599 @end smallexample
29600
29601 @noindent
29602 The @code{"a"} constraint tells the compiler that the @code{Flags}
29603 variable will come from the eax register. Here is the resulting code:
29604
29605 @smallexample
29606 @group
29607 #APP
29608    pushfl
29609    popl %eax
29610 #NO_APP
29611    movl %eax,-40(%ebp)
29612 @end group
29613 @end smallexample
29614
29615 @noindent
29616 The compiler generated the store of eax into Flags after
29617 expanding the assembler code.
29618
29619 Actually, there was no need to pop the flags into the eax register;
29620 more simply, we could just pop the flags directly into the program variable:
29621
29622 @smallexample @c ada
29623 @group
29624 with Interfaces; use Interfaces;
29625 with Ada.Text_IO; use Ada.Text_IO;
29626 with System.Machine_Code; use System.Machine_Code;
29627 procedure Get_Flags_3 is
29628    Flags : Unsigned_32;
29629    use ASCII;
29630 begin
29631    Asm ("pushfl"  & LF & HT & -- push flags on stack
29632         "pop %0",             -- save flags in Flags
29633         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
29634    Put_Line ("Flags register:" & Flags'Img);
29635 end Get_Flags_3;
29636 @end group
29637 @end smallexample
29638
29639 @c ---------------------------------------------------------------------------
29640 @node Input Variables in Inline Assembler
29641 @section Input Variables in Inline Assembler
29642
29643 @noindent
29644 The example in this section illustrates how to specify the source operands
29645 for assembly language statements.
29646 The program simply increments its input value by 1:
29647
29648 @smallexample @c ada
29649 @group
29650 with Interfaces; use Interfaces;
29651 with Ada.Text_IO; use Ada.Text_IO;
29652 with System.Machine_Code; use System.Machine_Code;
29653 procedure Increment is
29654
29655    function Incr (Value : Unsigned_32) return Unsigned_32 is
29656       Result : Unsigned_32;
29657    begin
29658       Asm ("incl %0",
29659            Inputs  => Unsigned_32'Asm_Input ("a", Value),
29660            Outputs => Unsigned_32'Asm_Output ("=a", Result));
29661       return Result;
29662    end Incr;
29663
29664    Value : Unsigned_32;
29665
29666 begin
29667    Value := 5;
29668    Put_Line ("Value before is" & Value'Img);
29669    Value := Incr (Value);
29670    Put_Line ("Value after is" & Value'Img);
29671 end Increment;
29672 @end group
29673 @end smallexample
29674
29675 The @code{Outputs} parameter to @code{Asm} specifies
29676 that the result will be in the eax register and that it is to be stored
29677 in the @code{Result} variable.
29678
29679 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
29680 but with an @code{Asm_Input} attribute.
29681 The @code{"="} constraint, indicating an output value, is not present.
29682
29683 You can have multiple input variables, in the same way that you can have more
29684 than one output variable.
29685
29686 The parameter count (%0, %1) etc, now starts at the first input
29687 statement, and continues with the output statements.
29688 When both parameters use the same variable, the
29689 compiler will treat them as the same %n operand, which is the case here.
29690
29691 Just as the @code{Outputs} parameter causes the register to be stored into the
29692 target variable after execution of the assembler statements, so does the
29693 @code{Inputs} parameter cause its variable to be loaded into the register
29694 before execution of the assembler statements.
29695
29696 Thus the effect of the @code{Asm} invocation is:
29697 @enumerate
29698 @item load the 32-bit value of @code{Value} into eax
29699 @item execute the @code{incl %eax} instruction
29700 @item store the contents of eax into the @code{Result} variable
29701 @end enumerate
29702
29703 The resulting assembler file (with @option{-O2} optimization) contains:
29704 @smallexample
29705 @group
29706 _increment__incr.1:
29707    subl $4,%esp
29708    movl 8(%esp),%eax
29709 #APP
29710    incl %eax
29711 #NO_APP
29712    movl %eax,%edx
29713    movl %ecx,(%esp)
29714    addl $4,%esp
29715    ret
29716 @end group
29717 @end smallexample
29718
29719 @c ---------------------------------------------------------------------------
29720 @node Inlining Inline Assembler Code
29721 @section Inlining Inline Assembler Code
29722
29723 @noindent
29724 For a short subprogram such as the @code{Incr} function in the previous
29725 section, the overhead of the call and return (creating / deleting the stack
29726 frame) can be significant, compared to the amount of code in the subprogram
29727 body.  A solution is to apply Ada's @code{Inline} pragma to the subprogram,
29728 which directs the compiler to expand invocations of the subprogram at the
29729 point(s) of call, instead of setting up a stack frame for out-of-line calls.
29730 Here is the resulting program:
29731
29732 @smallexample @c ada
29733 @group
29734 with Interfaces; use Interfaces;
29735 with Ada.Text_IO; use Ada.Text_IO;
29736 with System.Machine_Code; use System.Machine_Code;
29737 procedure Increment_2 is
29738
29739    function Incr (Value : Unsigned_32) return Unsigned_32 is
29740       Result : Unsigned_32;
29741    begin
29742       Asm ("incl %0",
29743            Inputs  => Unsigned_32'Asm_Input ("a", Value),
29744            Outputs => Unsigned_32'Asm_Output ("=a", Result));
29745       return Result;
29746    end Incr;
29747    pragma Inline (Increment);
29748
29749    Value : Unsigned_32;
29750
29751 begin
29752    Value := 5;
29753    Put_Line ("Value before is" & Value'Img);
29754    Value := Increment (Value);
29755    Put_Line ("Value after is" & Value'Img);
29756 end Increment_2;
29757 @end group
29758 @end smallexample
29759
29760 Compile the program with both optimization (@option{-O2}) and inlining
29761 (@option{-gnatn}) enabled.
29762
29763 The @code{Incr} function is still compiled as usual, but at the
29764 point in @code{Increment} where our function used to be called:
29765
29766 @smallexample
29767 @group
29768 pushl %edi
29769 call _increment__incr.1
29770 @end group
29771 @end smallexample
29772
29773 @noindent
29774 the code for the function body directly appears:
29775
29776 @smallexample
29777 @group
29778 movl %esi,%eax
29779 #APP
29780    incl %eax
29781 #NO_APP
29782    movl %eax,%edx
29783 @end group
29784 @end smallexample
29785
29786 @noindent
29787 thus saving the overhead of stack frame setup and an out-of-line call.
29788
29789 @c ---------------------------------------------------------------------------
29790 @node Other Asm Functionality
29791 @section Other @code{Asm} Functionality
29792
29793 @noindent
29794 This section describes two important parameters to the @code{Asm}
29795 procedure: @code{Clobber}, which identifies register usage;
29796 and @code{Volatile}, which inhibits unwanted optimizations.
29797
29798 @menu
29799 * The Clobber Parameter::
29800 * The Volatile Parameter::
29801 @end menu
29802
29803 @c ---------------------------------------------------------------------------
29804 @node The Clobber Parameter
29805 @subsection The @code{Clobber} Parameter
29806
29807 @noindent
29808 One of the dangers of intermixing assembly language and a compiled language
29809 such as Ada is that the compiler needs to be aware of which registers are
29810 being used by the assembly code.  In some cases, such as the earlier examples,
29811 the constraint string is sufficient to indicate register usage (e.g.,
29812 @code{"a"} for
29813 the eax register).  But more generally, the compiler needs an explicit
29814 identification of the registers that are used by the Inline Assembly
29815 statements.
29816
29817 Using a register that the compiler doesn't know about
29818 could be a side effect of an instruction (like @code{mull}
29819 storing its result in both eax and edx).
29820 It can also arise from explicit register usage in your
29821 assembly code; for example:
29822 @smallexample
29823 @group
29824 Asm ("movl %0, %%ebx" & LF & HT &
29825      "movl %%ebx, %1",
29826      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
29827      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out));
29828 @end group
29829 @end smallexample
29830 @noindent
29831 where the compiler (since it does not analyze the @code{Asm} template string)
29832 does not know you are using the ebx register.
29833
29834 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
29835 to identify the registers that will be used by your assembly code:
29836
29837 @smallexample
29838 @group
29839 Asm ("movl %0, %%ebx" & LF & HT &
29840      "movl %%ebx, %1",
29841      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
29842      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
29843      Clobber => "ebx");
29844 @end group
29845 @end smallexample
29846
29847 The Clobber parameter is a static string expression specifying the
29848 register(s) you are using.  Note that register names are @emph{not} prefixed
29849 by a percent sign. Also, if more than one register is used then their names
29850 are separated by commas; e.g., @code{"eax, ebx"}
29851
29852 The @code{Clobber} parameter has several additional uses:
29853 @enumerate
29854 @item Use ``register'' name @code{cc} to indicate that flags might have changed
29855 @item Use ``register'' name @code{memory} if you changed a memory location
29856 @end enumerate
29857
29858 @c ---------------------------------------------------------------------------
29859 @node The Volatile Parameter
29860 @subsection The @code{Volatile} Parameter
29861 @cindex Volatile parameter
29862
29863 @noindent
29864 Compiler optimizations in the presence of Inline Assembler may sometimes have
29865 unwanted effects.  For example, when an @code{Asm} invocation with an input
29866 variable is inside a loop, the compiler might move the loading of the input
29867 variable outside the loop, regarding it as a one-time initialization.
29868
29869 If this effect is not desired, you can disable such optimizations by setting
29870 the @code{Volatile} parameter to @code{True}; for example:
29871
29872 @smallexample @c ada
29873 @group
29874 Asm ("movl %0, %%ebx" & LF & HT &
29875      "movl %%ebx, %1",
29876      Inputs   => Unsigned_32'Asm_Input  ("g", Var_In),
29877      Outputs  => Unsigned_32'Asm_Output ("=g", Var_Out),
29878      Clobber  => "ebx",
29879      Volatile => True);
29880 @end group
29881 @end smallexample
29882
29883 By default, @code{Volatile} is set to @code{False} unless there is no
29884 @code{Outputs} parameter.
29885
29886 Although setting @code{Volatile} to @code{True} prevents unwanted
29887 optimizations, it will also disable other optimizations that might be
29888 important for efficiency. In general, you should set @code{Volatile}
29889 to @code{True} only if the compiler's optimizations have created
29890 problems.
29891 @c END OF INLINE ASSEMBLER CHAPTER
29892 @c ===============================
29893
29894 @c ***********************************
29895 @c * Compatibility and Porting Guide *
29896 @c ***********************************
29897 @node Compatibility and Porting Guide
29898 @appendix Compatibility and Porting Guide
29899
29900 @noindent
29901 This chapter describes the compatibility issues that may arise between
29902 GNAT and other Ada compilation systems (including those for Ada 83),
29903 and shows how GNAT can expedite porting
29904 applications developed in other Ada environments.
29905
29906 @menu
29907 * Compatibility with Ada 83::
29908 * Compatibility between Ada 95 and Ada 2005::
29909 * Implementation-dependent characteristics::
29910 * Compatibility with Other Ada Systems::
29911 * Representation Clauses::
29912 @ifclear vms
29913 @c Brief section is only in non-VMS version
29914 @c Full chapter is in VMS version
29915 * Compatibility with HP Ada 83::
29916 @end ifclear
29917 @ifset vms
29918 * Transitioning to 64-Bit GNAT for OpenVMS::
29919 @end ifset
29920 @end menu
29921
29922 @node Compatibility with Ada 83
29923 @section Compatibility with Ada 83
29924 @cindex Compatibility (between Ada 83 and Ada 95 / Ada 2005)
29925
29926 @noindent
29927 Ada 95 and Ada 2005 are highly upwards compatible with Ada 83.  In
29928 particular, the design intention was that the difficulties associated
29929 with moving from Ada 83 to Ada 95 or Ada 2005 should be no greater than those
29930 that occur when moving from one Ada 83 system to another.
29931
29932 However, there are a number of points at which there are minor
29933 incompatibilities.  The @cite{Ada 95 Annotated Reference Manual} contains
29934 full details of these issues,
29935 and should be consulted for a complete treatment.
29936 In practice the
29937 following subsections treat the most likely issues to be encountered.
29938
29939 @menu
29940 * Legal Ada 83 programs that are illegal in Ada 95::
29941 * More deterministic semantics::
29942 * Changed semantics::
29943 * Other language compatibility issues::
29944 @end menu
29945
29946 @node Legal Ada 83 programs that are illegal in Ada 95
29947 @subsection Legal Ada 83 programs that are illegal in Ada 95
29948
29949 Some legal Ada 83 programs are illegal (i.e., they will fail to compile) in
29950 Ada 95 and thus also in Ada 2005:
29951
29952 @table @emph
29953 @item Character literals
29954 Some uses of character literals are ambiguous.  Since Ada 95 has introduced
29955 @code{Wide_Character} as a new predefined character type, some uses of
29956 character literals that were legal in Ada 83 are illegal in Ada 95.
29957 For example:
29958 @smallexample @c ada
29959    for Char in 'A' .. 'Z' loop @dots{} end loop;
29960 @end smallexample
29961
29962 @noindent
29963 The problem is that @code{'A'} and @code{'Z'} could be from either
29964 @code{Character} or @code{Wide_Character}.  The simplest correction
29965 is to make the type explicit; e.g.:
29966 @smallexample @c ada
29967    for Char in Character range 'A' .. 'Z' loop @dots{} end loop;
29968 @end smallexample
29969
29970 @item New reserved words
29971 The identifiers @code{abstract}, @code{aliased}, @code{protected},
29972 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
29973 Existing Ada 83 code using any of these identifiers must be edited to
29974 use some alternative name.
29975
29976 @item Freezing rules
29977 The rules in Ada 95 are slightly different with regard to the point at
29978 which entities are frozen, and representation pragmas and clauses are
29979 not permitted past the freeze point.  This shows up most typically in
29980 the form of an error message complaining that a representation item
29981 appears too late, and the appropriate corrective action is to move
29982 the item nearer to the declaration of the entity to which it refers.
29983
29984 A particular case is that representation pragmas
29985 @ifset vms
29986 (including the
29987 extended HP Ada 83 compatibility pragmas such as @code{Export_Procedure})
29988 @end ifset
29989 cannot be applied to a subprogram body.  If necessary, a separate subprogram
29990 declaration must be introduced to which the pragma can be applied.
29991
29992 @item Optional bodies for library packages
29993 In Ada 83, a package that did not require a package body was nevertheless
29994 allowed to have one.  This lead to certain surprises in compiling large
29995 systems (situations in which the body could be unexpectedly ignored by the
29996 binder).  In Ada 95, if a package does not require a body then it is not
29997 permitted to have a body.  To fix this problem, simply remove a redundant
29998 body if it is empty, or, if it is non-empty, introduce a dummy declaration
29999 into the spec that makes the body required.  One approach is to add a private
30000 part to the package declaration (if necessary), and define a parameterless
30001 procedure called @code{Requires_Body}, which must then be given a dummy
30002 procedure body in the package body, which then becomes required.
30003 Another approach (assuming that this does not introduce elaboration
30004 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
30005 since one effect of this pragma is to require the presence of a package body.
30006
30007 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
30008 In Ada 95, the exception @code{Numeric_Error} is a renaming of
30009 @code{Constraint_Error}.
30010 This means that it is illegal to have separate exception handlers for
30011 the two exceptions.  The fix is simply to remove the handler for the
30012 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
30013 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
30014
30015 @item Indefinite subtypes in generics
30016 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
30017 as the actual for a generic formal private type, but then the instantiation
30018 would be illegal if there were any instances of declarations of variables
30019 of this type in the generic body.  In Ada 95, to avoid this clear violation
30020 of the methodological principle known as the ``contract model'',
30021 the generic declaration explicitly indicates whether
30022 or not such instantiations are permitted.  If a generic formal parameter
30023 has explicit unknown discriminants, indicated by using @code{(<>)} after the
30024 type name, then it can be instantiated with indefinite types, but no
30025 stand-alone variables can be declared of this type.  Any attempt to declare
30026 such a variable will result in an illegality at the time the generic is
30027 declared.  If the @code{(<>)} notation is not used, then it is illegal
30028 to instantiate the generic with an indefinite type.
30029 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
30030 It will show up as a compile time error, and
30031 the fix is usually simply to add the @code{(<>)} to the generic declaration.
30032 @end table
30033
30034 @node More deterministic semantics
30035 @subsection More deterministic semantics
30036
30037 @table @emph
30038 @item Conversions
30039 Conversions from real types to integer types round away from 0.  In Ada 83
30040 the conversion Integer(2.5) could deliver either 2 or 3 as its value.  This
30041 implementation freedom was intended to support unbiased rounding in
30042 statistical applications, but in practice it interfered with portability.
30043 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
30044 is required.  Numeric code may be affected by this change in semantics.
30045 Note, though, that this issue is no worse than already existed in Ada 83
30046 when porting code from one vendor to another.
30047
30048 @item Tasking
30049 The Real-Time Annex introduces a set of policies that define the behavior of
30050 features that were implementation dependent in Ada 83, such as the order in
30051 which open select branches are executed.
30052 @end table
30053
30054 @node Changed semantics
30055 @subsection Changed semantics
30056
30057 @noindent
30058 The worst kind of incompatibility is one where a program that is legal in
30059 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
30060 possible in Ada 83.  Fortunately this is extremely rare, but the one
30061 situation that you should be alert to is the change in the predefined type
30062 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
30063
30064 @table @emph
30065 @item Range of type @code{Character}
30066 The range of @code{Standard.Character} is now the full 256 characters
30067 of Latin-1, whereas in most Ada 83 implementations it was restricted
30068 to 128 characters. Although some of the effects of
30069 this change will be manifest in compile-time rejection of legal
30070 Ada 83 programs it is possible for a working Ada 83 program to have
30071 a different effect in Ada 95, one that was not permitted in Ada 83.
30072 As an example, the expression
30073 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
30074 delivers @code{255} as its value.
30075 In general, you should look at the logic of any
30076 character-processing Ada 83 program and see whether it needs to be adapted
30077 to work correctly with Latin-1.  Note that the predefined Ada 95 API has a
30078 character handling package that may be relevant if code needs to be adapted
30079 to account for the additional Latin-1 elements.
30080 The desirable fix is to
30081 modify the program to accommodate the full character set, but in some cases
30082 it may be convenient to define a subtype or derived type of Character that
30083 covers only the restricted range.
30084 @cindex Latin-1
30085 @end table
30086
30087 @node Other language compatibility issues
30088 @subsection Other language compatibility issues
30089
30090 @table @emph
30091 @item @option{-gnat83} switch
30092 All implementations of GNAT provide a switch that causes GNAT to operate
30093 in Ada 83 mode.  In this mode, some but not all compatibility problems
30094 of the type described above are handled automatically.  For example, the
30095 new reserved words introduced in Ada 95 and Ada 2005 are treated simply
30096 as identifiers as in Ada 83.
30097 However,
30098 in practice, it is usually advisable to make the necessary modifications
30099 to the program to remove the need for using this switch.
30100 See @ref{Compiling Different Versions of Ada}.
30101
30102 @item Support for removed Ada 83 pragmas and attributes
30103 A number of pragmas and attributes from Ada 83 were removed from Ada 95,
30104 generally because they were replaced by other mechanisms.  Ada 95 and Ada 2005
30105 compilers are allowed, but not required, to implement these missing
30106 elements.  In contrast with some other compilers, GNAT implements all
30107 such pragmas and attributes, eliminating this compatibility concern.  These
30108 include @code{pragma Interface} and the floating point type attributes
30109 (@code{Emax}, @code{Mantissa}, etc.), among other items.
30110 @end table
30111
30112
30113 @node Compatibility between Ada 95 and Ada 2005
30114 @section Compatibility between Ada 95 and Ada 2005
30115 @cindex Compatibility between Ada 95 and Ada 2005
30116
30117 @noindent
30118 Although Ada 2005 was designed to be upwards compatible with Ada 95, there are
30119 a number of incompatibilities. Several are enumerated below;
30120 for a complete description please see the
30121 Annotated Ada 2005 Reference Manual, or section 9.1.1 in
30122 @cite{Rationale for Ada 2005}.
30123
30124 @table @emph
30125 @item New reserved words.
30126 The words @code{interface}, @code{overriding} and @code{synchronized} are
30127 reserved in Ada 2005.
30128 A pre-Ada 2005 program that uses any of these as an identifier will be
30129 illegal.
30130
30131 @item New declarations in predefined packages.
30132 A number of packages in the predefined environment contain new declarations:
30133 @code{Ada.Exceptions}, @code{Ada.Real_Time}, @code{Ada.Strings},
30134 @code{Ada.Strings.Fixed}, @code{Ada.Strings.Bounded},
30135 @code{Ada.Strings.Unbounded}, @code{Ada.Strings.Wide_Fixed},
30136 @code{Ada.Strings.Wide_Bounded}, @code{Ada.Strings.Wide_Unbounded},
30137 @code{Ada.Tags}, @code{Ada.Text_IO}, and @code{Interfaces.C}.
30138 If an Ada 95 program does a @code{with} and @code{use} of any of these
30139 packages, the new declarations may cause name clashes.
30140
30141 @item Access parameters.
30142 A nondispatching subprogram with an access parameter cannot be renamed
30143 as a dispatching operation.  This was permitted in Ada 95.
30144
30145 @item Access types, discriminants, and constraints.
30146 Rule changes in this area have led to some incompatibilities; for example,
30147 constrained subtypes of some access types are not permitted in Ada 2005.
30148
30149 @item Aggregates for limited types.
30150 The allowance of aggregates for limited types in Ada 2005 raises the
30151 possibility of ambiguities in legal Ada 95 programs, since additional types
30152 now need to be considered in expression resolution.
30153
30154 @item Fixed-point multiplication and division.
30155 Certain expressions involving ``*'' or ``/'' for a fixed-point type, which
30156 were legal in Ada 95 and invoked the predefined versions of these operations,
30157 are now ambiguous.
30158 The ambiguity may be resolved either by applying a type conversion to the
30159 expression, or by explicitly invoking the operation from package
30160 @code{Standard}.
30161
30162 @item Return-by-reference types.
30163 The Ada 95 return-by-reference mechanism has been removed.  Instead, the user
30164 can declare a function returning a value from an anonymous access type.
30165 @end table
30166
30167
30168 @node Implementation-dependent characteristics
30169 @section Implementation-dependent characteristics
30170 @noindent
30171 Although the Ada language defines the semantics of each construct as
30172 precisely as practical, in some situations (for example for reasons of
30173 efficiency, or where the effect is heavily dependent on the host or target
30174 platform) the implementation is allowed some freedom.  In porting Ada 83
30175 code to GNAT, you need to be aware of whether / how the existing code
30176 exercised such implementation dependencies.  Such characteristics fall into
30177 several categories, and GNAT offers specific support in assisting the
30178 transition from certain Ada 83 compilers.
30179
30180 @menu
30181 * Implementation-defined pragmas::
30182 * Implementation-defined attributes::
30183 * Libraries::
30184 * Elaboration order::
30185 * Target-specific aspects::
30186 @end menu
30187
30188 @node Implementation-defined pragmas
30189 @subsection Implementation-defined pragmas
30190
30191 @noindent
30192 Ada compilers are allowed to supplement the language-defined pragmas, and
30193 these are a potential source of non-portability.  All GNAT-defined pragmas
30194 are described in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT
30195 Reference Manual}, and these include several that are specifically
30196 intended to correspond to other vendors' Ada 83 pragmas.
30197 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
30198 For compatibility with HP Ada 83, GNAT supplies the pragmas
30199 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
30200 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
30201 and @code{Volatile}.
30202 Other relevant pragmas include @code{External} and @code{Link_With}.
30203 Some vendor-specific
30204 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
30205 recognized, thus
30206 avoiding compiler rejection of units that contain such pragmas; they are not
30207 relevant in a GNAT context and hence are not otherwise implemented.
30208
30209 @node Implementation-defined attributes
30210 @subsection Implementation-defined attributes
30211
30212 Analogous to pragmas, the set of attributes may be extended by an
30213 implementation.  All GNAT-defined attributes are described in
30214 @ref{Implementation Defined Attributes,,, gnat_rm, GNAT Reference
30215 Manual}, and these include several that are specifically intended
30216 to correspond to other vendors' Ada 83 attributes.  For migrating from VADS,
30217 the attribute @code{VADS_Size} may be useful.  For compatibility with HP
30218 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
30219 @code{Type_Class}.
30220
30221 @node Libraries
30222 @subsection Libraries
30223 @noindent
30224 Vendors may supply libraries to supplement the standard Ada API.  If Ada 83
30225 code uses vendor-specific libraries then there are several ways to manage
30226 this in Ada 95 or Ada 2005:
30227 @enumerate
30228 @item
30229 If the source code for the libraries (specs and bodies) are
30230 available, then the libraries can be migrated in the same way as the
30231 application.
30232 @item
30233 If the source code for the specs but not the bodies are
30234 available, then you can reimplement the bodies.
30235 @item
30236 Some features introduced by Ada 95 obviate the need for library support.  For
30237 example most Ada 83 vendors supplied a package for unsigned integers.  The
30238 Ada 95 modular type feature is the preferred way to handle this need, so
30239 instead of migrating or reimplementing the unsigned integer package it may
30240 be preferable to retrofit the application using modular types.
30241 @end enumerate
30242
30243 @node Elaboration order
30244 @subsection Elaboration order
30245 @noindent
30246 The implementation can choose any elaboration order consistent with the unit
30247 dependency relationship.  This freedom means that some orders can result in
30248 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
30249 to invoke a subprogram its body has been elaborated, or to instantiate a
30250 generic before the generic body has been elaborated.  By default GNAT
30251 attempts to choose a safe order (one that will not encounter access before
30252 elaboration problems) by implicitly inserting @code{Elaborate} or
30253 @code{Elaborate_All} pragmas where
30254 needed.  However, this can lead to the creation of elaboration circularities
30255 and a resulting rejection of the program by gnatbind.  This issue is
30256 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
30257 In brief, there are several
30258 ways to deal with this situation:
30259
30260 @itemize @bullet
30261 @item
30262 Modify the program to eliminate the circularities, e.g.@: by moving
30263 elaboration-time code into explicitly-invoked procedures
30264 @item
30265 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
30266 @code{Elaborate} pragmas, and then inhibit the generation of implicit
30267 @code{Elaborate_All}
30268 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
30269 (by selectively suppressing elaboration checks via pragma
30270 @code{Suppress(Elaboration_Check)} when it is safe to do so).
30271 @end itemize
30272
30273 @node Target-specific aspects
30274 @subsection Target-specific aspects
30275 @noindent
30276 Low-level applications need to deal with machine addresses, data
30277 representations, interfacing with assembler code, and similar issues.  If
30278 such an Ada 83 application is being ported to different target hardware (for
30279 example where the byte endianness has changed) then you will need to
30280 carefully examine the program logic; the porting effort will heavily depend
30281 on the robustness of the original design.  Moreover, Ada 95 (and thus
30282 Ada 2005) are sometimes
30283 incompatible with typical Ada 83 compiler practices regarding implicit
30284 packing, the meaning of the Size attribute, and the size of access values.
30285 GNAT's approach to these issues is described in @ref{Representation Clauses}.
30286
30287 @node Compatibility with Other Ada Systems
30288 @section Compatibility with Other Ada Systems
30289
30290 @noindent
30291 If programs avoid the use of implementation dependent and
30292 implementation defined features, as documented in the @cite{Ada
30293 Reference Manual}, there should be a high degree of portability between
30294 GNAT and other Ada systems.  The following are specific items which
30295 have proved troublesome in moving Ada 95 programs from GNAT to other Ada 95
30296 compilers, but do not affect porting code to GNAT@.
30297 (As of @value{NOW}, GNAT is the only compiler available for Ada 2005;
30298 the following issues may or may not arise for Ada 2005 programs
30299 when other compilers appear.)
30300
30301 @table @emph
30302 @item Ada 83 Pragmas and Attributes
30303 Ada 95 compilers are allowed, but not required, to implement the missing
30304 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
30305 GNAT implements all such pragmas and attributes, eliminating this as
30306 a compatibility concern, but some other Ada 95 compilers reject these
30307 pragmas and attributes.
30308
30309 @item Specialized Needs Annexes
30310 GNAT implements the full set of special needs annexes.  At the
30311 current time, it is the only Ada 95 compiler to do so.  This means that
30312 programs making use of these features may not be portable to other Ada
30313 95 compilation systems.
30314
30315 @item Representation Clauses
30316 Some other Ada 95 compilers implement only the minimal set of
30317 representation clauses required by the Ada 95 reference manual.  GNAT goes
30318 far beyond this minimal set, as described in the next section.
30319 @end table
30320
30321 @node Representation Clauses
30322 @section Representation Clauses
30323
30324 @noindent
30325 The Ada 83 reference manual was quite vague in describing both the minimal
30326 required implementation of representation clauses, and also their precise
30327 effects.  Ada 95 (and thus also Ada 2005) are much more explicit, but the
30328 minimal set of capabilities required is still quite limited.
30329
30330 GNAT implements the full required set of capabilities in
30331 Ada 95 and Ada 2005, but also goes much further, and in particular
30332 an effort has been made to be compatible with existing Ada 83 usage to the
30333 greatest extent possible.
30334
30335 A few cases exist in which Ada 83 compiler behavior is incompatible with
30336 the requirements in Ada 95 (and thus also Ada 2005).  These are instances of
30337 intentional or accidental dependence on specific implementation dependent
30338 characteristics of these Ada 83 compilers.  The following is a list of
30339 the cases most likely to arise in existing Ada 83 code.
30340
30341 @table @emph
30342 @item Implicit Packing
30343 Some Ada 83 compilers allowed a Size specification to cause implicit
30344 packing of an array or record.  This could cause expensive implicit
30345 conversions for change of representation in the presence of derived
30346 types, and the Ada design intends to avoid this possibility.
30347 Subsequent AI's were issued to make it clear that such implicit
30348 change of representation in response to a Size clause is inadvisable,
30349 and this recommendation is represented explicitly in the Ada 95 (and Ada 2005)
30350 Reference Manuals as implementation advice that is followed by GNAT@.
30351 The problem will show up as an error
30352 message rejecting the size clause.  The fix is simply to provide
30353 the explicit pragma @code{Pack}, or for more fine tuned control, provide
30354 a Component_Size clause.
30355
30356 @item Meaning of Size Attribute
30357 The Size attribute in Ada 95 (and Ada 2005) for discrete types is defined as
30358 the minimal number of bits required to hold values of the type.  For example,
30359 on a 32-bit machine, the size of @code{Natural} will typically be 31 and not
30360 32 (since no sign bit is required).  Some Ada 83 compilers gave 31, and
30361 some 32 in this situation.  This problem will usually show up as a compile
30362 time error, but not always.  It is a good idea to check all uses of the
30363 'Size attribute when porting Ada 83 code.  The GNAT specific attribute
30364 Object_Size can provide a useful way of duplicating the behavior of
30365 some Ada 83 compiler systems.
30366
30367 @item Size of Access Types
30368 A common assumption in Ada 83 code is that an access type is in fact a pointer,
30369 and that therefore it will be the same size as a System.Address value.  This
30370 assumption is true for GNAT in most cases with one exception.  For the case of
30371 a pointer to an unconstrained array type (where the bounds may vary from one
30372 value of the access type to another), the default is to use a ``fat pointer'',
30373 which is represented as two separate pointers, one to the bounds, and one to
30374 the array.  This representation has a number of advantages, including improved
30375 efficiency.  However, it may cause some difficulties in porting existing Ada 83
30376 code which makes the assumption that, for example, pointers fit in 32 bits on
30377 a machine with 32-bit addressing.
30378
30379 To get around this problem, GNAT also permits the use of ``thin pointers'' for
30380 access types in this case (where the designated type is an unconstrained array
30381 type).  These thin pointers are indeed the same size as a System.Address value.
30382 To specify a thin pointer, use a size clause for the type, for example:
30383
30384 @smallexample @c ada
30385 type X is access all String;
30386 for X'Size use Standard'Address_Size;
30387 @end smallexample
30388
30389 @noindent
30390 which will cause the type X to be represented using a single pointer.
30391 When using this representation, the bounds are right behind the array.
30392 This representation is slightly less efficient, and does not allow quite
30393 such flexibility in the use of foreign pointers or in using the
30394 Unrestricted_Access attribute to create pointers to non-aliased objects.
30395 But for any standard portable use of the access type it will work in
30396 a functionally correct manner and allow porting of existing code.
30397 Note that another way of forcing a thin pointer representation
30398 is to use a component size clause for the element size in an array,
30399 or a record representation clause for an access field in a record.
30400 @end table
30401
30402 @ifclear vms
30403 @c This brief section is only in the non-VMS version
30404 @c The complete chapter on HP Ada is in the VMS version
30405 @node Compatibility with HP Ada 83
30406 @section Compatibility with HP Ada 83
30407
30408 @noindent
30409 The VMS version of GNAT fully implements all the pragmas and attributes
30410 provided by HP Ada 83, as well as providing the standard HP Ada 83
30411 libraries, including Starlet.  In addition, data layouts and parameter
30412 passing conventions are highly compatible.  This means that porting
30413 existing HP Ada 83 code to GNAT in VMS systems should be easier than
30414 most other porting efforts.  The following are some of the most
30415 significant differences between GNAT and HP Ada 83.
30416
30417 @table @emph
30418 @item Default floating-point representation
30419 In GNAT, the default floating-point format is IEEE, whereas in HP Ada 83,
30420 it is VMS format.  GNAT does implement the necessary pragmas
30421 (Long_Float, Float_Representation) for changing this default.
30422
30423 @item System
30424 The package System in GNAT exactly corresponds to the definition in the
30425 Ada 95 reference manual, which means that it excludes many of the
30426 HP Ada 83 extensions.  However, a separate package Aux_DEC is provided
30427 that contains the additional definitions, and a special pragma,
30428 Extend_System allows this package to be treated transparently as an
30429 extension of package System.
30430
30431 @item To_Address
30432 The definitions provided by Aux_DEC are exactly compatible with those
30433 in the HP Ada 83 version of System, with one exception.
30434 HP Ada provides the following declarations:
30435
30436 @smallexample @c ada
30437 TO_ADDRESS (INTEGER)
30438 TO_ADDRESS (UNSIGNED_LONGWORD)
30439 TO_ADDRESS (@i{universal_integer})
30440 @end smallexample
30441
30442 @noindent
30443 The version of TO_ADDRESS taking a @i{universal integer} argument is in fact
30444 an extension to Ada 83 not strictly compatible with the reference manual.
30445 In GNAT, we are constrained to be exactly compatible with the standard,
30446 and this means we cannot provide this capability.  In HP Ada 83, the
30447 point of this definition is to deal with a call like:
30448
30449 @smallexample @c ada
30450 TO_ADDRESS (16#12777#);
30451 @end smallexample
30452
30453 @noindent
30454 Normally, according to the Ada 83 standard, one would expect this to be
30455 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
30456 of TO_ADDRESS@.  However, in HP Ada 83, there is no ambiguity, since the
30457 definition using @i{universal_integer} takes precedence.
30458
30459 In GNAT, since the version with @i{universal_integer} cannot be supplied, it
30460 is not possible to be 100% compatible.  Since there are many programs using
30461 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
30462 to change the name of the function in the UNSIGNED_LONGWORD case, so the
30463 declarations provided in the GNAT version of AUX_Dec are:
30464
30465 @smallexample @c ada
30466 function To_Address (X : Integer) return Address;
30467 pragma Pure_Function (To_Address);
30468
30469 function To_Address_Long (X : Unsigned_Longword)
30470  return Address;
30471 pragma Pure_Function (To_Address_Long);
30472 @end smallexample
30473
30474 @noindent
30475 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
30476 change the name to TO_ADDRESS_LONG@.
30477
30478 @item Task_Id values
30479 The Task_Id values assigned will be different in the two systems, and GNAT
30480 does not provide a specified value for the Task_Id of the environment task,
30481 which in GNAT is treated like any other declared task.
30482 @end table
30483
30484 @noindent
30485 For full details on these and other less significant compatibility issues,
30486 see appendix E of the HP publication entitled @cite{HP Ada, Technical
30487 Overview and Comparison on HP Platforms}.
30488
30489 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
30490 attributes are recognized, although only a subset of them can sensibly
30491 be implemented.  The description of pragmas in @ref{Implementation
30492 Defined Pragmas,,, gnat_rm, GNAT Reference Manual}
30493 indicates whether or not they are applicable to non-VMS systems.
30494 @end ifclear
30495
30496 @ifset vms
30497 @node Transitioning to 64-Bit GNAT for OpenVMS
30498 @section Transitioning to 64-Bit @value{EDITION} for OpenVMS
30499
30500 @noindent
30501 This section is meant to assist users of pre-2006 @value{EDITION}
30502 for Alpha OpenVMS who are transitioning to 64-bit @value{EDITION},
30503 the version of the GNAT technology supplied in 2006 and later for
30504 OpenVMS on both Alpha and I64.
30505
30506 @menu
30507 * Introduction to transitioning::
30508 * Migration of 32 bit code::
30509 * Taking advantage of 64 bit addressing::
30510 * Technical details::
30511 @end menu
30512
30513 @node Introduction to transitioning
30514 @subsection Introduction
30515
30516 @noindent
30517 64-bit @value{EDITION} for Open VMS has been designed to meet
30518 three main goals:
30519
30520 @enumerate
30521 @item
30522 Providing a full conforming implementation of Ada 95 and Ada 2005
30523
30524 @item
30525 Allowing maximum backward compatibility, thus easing migration of existing
30526 Ada source code
30527
30528 @item
30529 Supplying a path for exploiting the full 64-bit address range
30530 @end enumerate
30531
30532 @noindent
30533 Ada's strong typing semantics has made it
30534 impractical to have different 32-bit and 64-bit modes. As soon as
30535 one object could possibly be outside the 32-bit address space, this
30536 would make it necessary for the @code{System.Address} type to be 64 bits.
30537 In particular, this would cause inconsistencies if 32-bit code is
30538 called from 64-bit code that raises an exception.
30539
30540 This issue has been resolved by always using 64-bit addressing
30541 at the system level, but allowing for automatic conversions between
30542 32-bit and 64-bit addresses where required. Thus users who
30543 do not currently require 64-bit addressing capabilities, can
30544 recompile their code with only minimal changes (and indeed
30545 if the code is written in portable Ada, with no assumptions about
30546 the size of the @code{Address} type, then no changes at all are necessary).
30547 At the same time,
30548 this approach provides a simple, gradual upgrade path to future
30549 use of larger memories than available for 32-bit systems.
30550 Also, newly written applications or libraries will by default
30551 be fully compatible with future systems exploiting 64-bit
30552 addressing capabilities.
30553
30554 @ref{Migration of 32 bit code}, will focus on porting applications
30555 that do not require more than 2 GB of
30556 addressable memory. This code will be referred to as
30557 @emph{32-bit code}.
30558 For applications intending to exploit the full 64-bit address space,
30559 @ref{Taking advantage of 64 bit addressing},
30560 will consider further changes that may be required.
30561 Such code will be referred to below as @emph{64-bit code}.
30562
30563 @node Migration of 32 bit code
30564 @subsection Migration of 32-bit code
30565
30566 @menu
30567 * Address types::
30568 * Access types::
30569 * Unchecked conversions::
30570 * Predefined constants::
30571 * Interfacing with C::
30572 * Experience with source compatibility::
30573 @end menu
30574
30575 @node Address types
30576 @subsubsection Address types
30577
30578 @noindent
30579 To solve the problem of mixing 64-bit and 32-bit addressing,
30580 while maintaining maximum backward compatibility, the following
30581 approach has been taken:
30582
30583 @itemize @bullet
30584 @item
30585 @code{System.Address} always has a size of 64 bits
30586
30587 @item
30588 @code{System.Short_Address} is a 32-bit subtype of @code{System.Address}
30589 @end itemize
30590
30591 @noindent
30592 Since @code{System.Short_Address} is a subtype of @code{System.Address},
30593 a @code{Short_Address}
30594 may be used where an @code{Address} is required, and vice versa, without
30595 needing explicit type conversions.
30596 By virtue of the Open VMS parameter passing conventions,
30597 even imported
30598 and exported subprograms that have 32-bit address parameters are
30599 compatible with those that have 64-bit address parameters.
30600 (See @ref{Making code 64 bit clean} for details.)
30601
30602 The areas that may need attention are those where record types have
30603 been defined that contain components of the type @code{System.Address}, and
30604 where objects of this type are passed to code expecting a record layout with
30605 32-bit addresses.
30606
30607 Different compilers on different platforms cannot be
30608 expected to represent the same type in the same way,
30609 since alignment constraints
30610 and other system-dependent properties affect the compiler's decision.
30611 For that reason, Ada code
30612 generally uses representation clauses to specify the expected
30613 layout where required.
30614
30615 If such a representation clause uses 32 bits for a component having
30616 the type @code{System.Address}, 64-bit @value{EDITION} for OpenVMS
30617 will detect that error and produce a specific diagnostic message.
30618 The developer should then determine whether the representation
30619 should be 64 bits or not and make either of two changes:
30620 change the size to 64 bits and leave the type as @code{System.Address}, or
30621 leave the size as 32 bits and change the type to @code{System.Short_Address}.
30622 Since @code{Short_Address} is a subtype of @code{Address}, no changes are
30623 required in any code setting or accessing the field; the compiler will
30624 automatically perform any needed conversions between address
30625 formats.
30626
30627 @node Access types
30628 @subsubsection Access types
30629
30630 @noindent
30631 By default, objects designated by access values are always
30632 allocated in the 32-bit
30633 address space. Thus legacy code will never contain
30634 any objects that are not addressable with 32-bit addresses, and
30635 the compiler will never raise exceptions as result of mixing
30636 32-bit and 64-bit addresses.
30637
30638 However, the access values themselves are represented in 64 bits, for optimum
30639 performance and future compatibility with 64-bit code. As was
30640 the case with @code{System.Address}, the compiler will give an error message
30641 if an object or record component has a representation clause that
30642 requires the access value to fit in 32 bits. In such a situation,
30643 an explicit size clause for the access type, specifying 32 bits,
30644 will have the desired effect.
30645
30646 General access types (declared with @code{access all}) can never be
30647 32 bits, as values of such types must be able to refer to any object
30648 of the  designated type,
30649 including objects residing outside the 32-bit address range.
30650 Existing Ada 83 code will not contain such type definitions,
30651 however, since general access types were introduced in Ada 95.
30652
30653 @node Unchecked conversions
30654 @subsubsection Unchecked conversions
30655
30656 @noindent
30657 In the case of an @code{Unchecked_Conversion} where the source type is a
30658 64-bit access type or the type @code{System.Address}, and the target
30659 type is a 32-bit type, the compiler will generate a warning.
30660 Even though the generated code will still perform the required
30661 conversions, it is highly recommended in these cases to use
30662 respectively a 32-bit access type or @code{System.Short_Address}
30663 as the source type.
30664
30665 @node Predefined constants
30666 @subsubsection Predefined constants
30667
30668 @noindent
30669 The following table shows the correspondence between pre-2006 versions of
30670 @value{EDITION} on Alpha OpenVMS (``Old'') and 64-bit @value{EDITION}
30671 (``New''):
30672
30673 @multitable {@code{System.Short_Memory_Size}} {2**32} {2**64}
30674 @item   @b{Constant}                     @tab @b{Old} @tab @b{New}
30675 @item   @code{System.Word_Size}          @tab 32      @tab 64
30676 @item   @code{System.Memory_Size}        @tab 2**32   @tab 2**64
30677 @item   @code{System.Short_Memory_Size}  @tab 2**32   @tab 2**32
30678 @item   @code{System.Address_Size}       @tab 32      @tab 64
30679 @end multitable
30680
30681 @noindent
30682 If you need to refer to the specific
30683 memory size of a 32-bit implementation, instead of the
30684 actual memory size, use @code{System.Short_Memory_Size}
30685 rather than @code{System.Memory_Size}.
30686 Similarly, references to @code{System.Address_Size} may need
30687 to be replaced by @code{System.Short_Address'Size}.
30688 The program @command{gnatfind} may be useful for locating
30689 references to the above constants, so that you can verify that they
30690 are still correct.
30691
30692 @node Interfacing with C
30693 @subsubsection Interfacing with C
30694
30695 @noindent
30696 In order to minimize the impact of the transition to 64-bit addresses on
30697 legacy programs, some fundamental types in the @code{Interfaces.C}
30698 package hierarchy continue to be represented in 32 bits.
30699 These types are: @code{ptrdiff_t}, @code{size_t}, and @code{chars_ptr}.
30700 This eases integration with the default HP C layout choices, for example
30701 as found in the system routines in @code{DECC$SHR.EXE}.
30702 Because of this implementation choice, the type fully compatible with
30703 @code{chars_ptr} is now @code{Short_Address} and not @code{Address}.
30704 Depending on the context the compiler will issue a
30705 warning or an error when type @code{Address} is used, alerting the user to a
30706 potential problem. Otherwise 32-bit programs that use
30707 @code{Interfaces.C} should normally not require code modifications
30708
30709 The other issue arising with C interfacing concerns pragma @code{Convention}.
30710 For VMS 64-bit systems, there is an issue of the appropriate default size
30711 of C convention pointers in the absence of an explicit size clause. The HP
30712 C compiler can choose either 32 or 64 bits depending on compiler options.
30713 GNAT chooses 32-bits rather than 64-bits in the default case where no size
30714 clause is given. This proves a better choice for porting 32-bit legacy
30715 applications. In order to have a 64-bit representation, it is necessary to
30716 specify a size representation clause. For example:
30717
30718 @smallexample @c ada
30719 type int_star is access Interfaces.C.int;
30720 pragma Convention(C, int_star);
30721 for int_star'Size use 64;  -- Necessary to get 64 and not 32 bits
30722 @end smallexample
30723
30724 @node Experience with source compatibility
30725 @subsubsection Experience with source compatibility
30726
30727 @noindent
30728 The Security Server and STARLET on I64 provide an interesting ``test case''
30729 for source compatibility issues, since it is in such system code
30730 where assumptions about @code{Address} size might be expected to occur.
30731 Indeed, there were a small number of occasions in the Security Server
30732 file @file{jibdef.ads}
30733 where a representation clause for a record type specified
30734 32 bits for a component of type @code{Address}.
30735 All of these errors were detected by the compiler.
30736 The repair was obvious and immediate; to simply replace @code{Address} by
30737 @code{Short_Address}.
30738
30739 In the case of STARLET, there were several record types that should
30740 have had representation clauses but did not.  In these record types
30741 there was an implicit assumption that an @code{Address} value occupied
30742 32 bits.
30743 These compiled without error, but their usage resulted in run-time error
30744 returns from STARLET system calls.
30745 Future GNAT technology enhancements may include a tool that detects and flags
30746 these sorts of potential source code porting problems.
30747
30748 @c ****************************************
30749 @node Taking advantage of 64 bit addressing
30750 @subsection Taking advantage of 64-bit addressing
30751
30752 @menu
30753 * Making code 64 bit clean::
30754 * Allocating memory from the 64 bit storage pool::
30755 * Restrictions on use of 64 bit objects::
30756 * Using 64 bit storage pools by default::
30757 * General access types::
30758 * STARLET and other predefined libraries::
30759 @end menu
30760
30761 @node Making code 64 bit clean
30762 @subsubsection Making code 64-bit clean
30763
30764 @noindent
30765 In order to prevent problems that may occur when (parts of) a
30766 system start using memory outside the 32-bit address range,
30767 we recommend some additional guidelines:
30768
30769 @itemize @bullet
30770 @item
30771 For imported subprograms that take parameters of the
30772 type @code{System.Address}, ensure that these subprograms can
30773 indeed handle 64-bit addresses. If not, or when in doubt,
30774 change the subprogram declaration to specify
30775 @code{System.Short_Address} instead.
30776
30777 @item
30778 Resolve all warnings related to size mismatches in
30779 unchecked conversions. Failing to do so causes
30780 erroneous execution if the source object is outside
30781 the 32-bit address space.
30782
30783 @item
30784 (optional) Explicitly use the 32-bit storage pool
30785 for access types used in a 32-bit context, or use
30786 generic access types where possible
30787 (@pxref{Restrictions on use of 64 bit objects}).
30788 @end itemize
30789
30790 @noindent
30791 If these rules are followed, the compiler will automatically insert
30792 any necessary checks to ensure that no addresses or access values
30793 passed to 32-bit code ever refer to objects outside the 32-bit
30794 address range.
30795 Any attempt to do this will raise @code{Constraint_Error}.
30796
30797 @node Allocating memory from the 64 bit storage pool
30798 @subsubsection Allocating memory from the 64-bit storage pool
30799
30800 @noindent
30801 For any access type @code{T} that potentially requires memory allocations
30802 beyond the 32-bit address space,
30803 use the following representation clause:
30804
30805 @smallexample @c ada
30806    for T'Storage_Pool use System.Pool_64;
30807 @end smallexample
30808
30809 @node Restrictions on use of 64 bit objects
30810 @subsubsection Restrictions on use of 64-bit objects
30811
30812 @noindent
30813 Taking the address of an object allocated from a 64-bit storage pool,
30814 and then passing this address to a subprogram expecting
30815 @code{System.Short_Address},
30816 or assigning it to a variable of type @code{Short_Address}, will cause
30817 @code{Constraint_Error} to be raised. In case the code is not 64-bit clean
30818 (@pxref{Making code 64 bit clean}), or checks are suppressed,
30819 no exception is raised and execution
30820 will become erroneous.
30821
30822 @node Using 64 bit storage pools by default
30823 @subsubsection Using 64-bit storage pools by default
30824
30825 @noindent
30826 In some cases it may be desirable to have the compiler allocate
30827 from 64-bit storage pools by default. This may be the case for
30828 libraries that are 64-bit clean, but may be used in both 32-bit
30829 and 64-bit contexts. For these cases the following configuration
30830 pragma may be specified:
30831
30832 @smallexample @c ada
30833   pragma Pool_64_Default;
30834 @end smallexample
30835
30836 @noindent
30837 Any code compiled in the context of this pragma will by default
30838 use the @code{System.Pool_64} storage pool. This default may be overridden
30839 for a specific access type @code{T} by the representation clause:
30840
30841 @smallexample @c ada
30842    for T'Storage_Pool use System.Pool_32;
30843 @end smallexample
30844
30845 @noindent
30846 Any object whose address may be passed to a subprogram with a
30847 @code{Short_Address} argument, or assigned to a variable of type
30848 @code{Short_Address}, needs to be allocated from this pool.
30849
30850 @node General access types
30851 @subsubsection General access types
30852
30853 @noindent
30854 Objects designated by access values from a
30855 general access type (declared with @code{access all}) are never allocated
30856 from a 64-bit storage pool. Code that uses general access types will
30857 accept objects allocated in either 32-bit or 64-bit address spaces,
30858 but never allocate objects outside the 32-bit address space.
30859 Using general access types ensures maximum compatibility with both
30860 32-bit and 64-bit code.
30861
30862 @node STARLET and other predefined libraries
30863 @subsubsection STARLET and other predefined libraries
30864
30865 @noindent
30866 All code that comes as part of GNAT is 64-bit clean, but the
30867 restrictions given in @ref{Restrictions on use of 64 bit objects},
30868 still apply. Look at the package
30869 specs to see in which contexts objects allocated
30870 in 64-bit address space are acceptable.
30871
30872 @node Technical details
30873 @subsection Technical details
30874
30875 @noindent
30876 64-bit @value{EDITION} for Open VMS takes advantage of the freedom given in the
30877 Ada standard with respect to the type of @code{System.Address}. Previous
30878 versions of GNAT Pro have defined this type as private and implemented it as a
30879 modular type.
30880
30881 In order to allow defining @code{System.Short_Address} as a proper subtype,
30882 and to match the implicit sign extension in parameter passing,
30883 in 64-bit @value{EDITION} for Open VMS, @code{System.Address} is defined as a
30884 visible (i.e., non-private) integer type.
30885 Standard operations on the type, such as the binary operators ``+'', ``-'',
30886 etc., that take @code{Address} operands and return an @code{Address} result,
30887 have been hidden by declaring these
30888 @code{abstract}, a feature introduced in Ada 95 that helps avoid the potential
30889 ambiguities that would otherwise result from overloading.
30890 (Note that, although @code{Address} is a visible integer type,
30891 good programming practice dictates against exploiting the type's
30892 integer properties such as literals, since this will compromise
30893 code portability.)
30894
30895 Defining @code{Address} as a visible integer type helps achieve
30896 maximum compatibility for existing Ada code,
30897 without sacrificing the capabilities of the 64-bit architecture.
30898 @end ifset
30899
30900 @c ************************************************
30901 @ifset unw
30902 @node Microsoft Windows Topics
30903 @appendix Microsoft Windows Topics
30904 @cindex Windows NT
30905 @cindex Windows 95
30906 @cindex Windows 98
30907
30908 @noindent
30909 This chapter describes topics that are specific to the Microsoft Windows
30910 platforms (NT, 2000, and XP Professional).
30911
30912 @menu
30913 * Using GNAT on Windows::
30914 * Using a network installation of GNAT::
30915 * CONSOLE and WINDOWS subsystems::
30916 * Temporary Files::
30917 * Mixed-Language Programming on Windows::
30918 * Windows Calling Conventions::
30919 * Introduction to Dynamic Link Libraries (DLLs)::
30920 * Using DLLs with GNAT::
30921 * Building DLLs with GNAT::
30922 * Building DLLs with GNAT Project files::
30923 * Building DLLs with gnatdll::
30924 * GNAT and Windows Resources::
30925 * Debugging a DLL::
30926 * Setting Stack Size from gnatlink::
30927 * Setting Heap Size from gnatlink::
30928 @end menu
30929
30930 @node Using GNAT on Windows
30931 @section Using GNAT on Windows
30932
30933 @noindent
30934 One of the strengths of the GNAT technology is that its tool set
30935 (@command{gcc}, @command{gnatbind}, @command{gnatlink}, @command{gnatmake}, the
30936 @code{gdb} debugger, etc.) is used in the same way regardless of the
30937 platform.
30938
30939 On Windows this tool set is complemented by a number of Microsoft-specific
30940 tools that have been provided to facilitate interoperability with Windows
30941 when this is required. With these tools:
30942
30943 @itemize @bullet
30944
30945 @item
30946 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
30947 subsystems.
30948
30949 @item
30950 You can use any Dynamically Linked Library (DLL) in your Ada code (both
30951 relocatable and non-relocatable DLLs are supported).
30952
30953 @item
30954 You can build Ada DLLs for use in other applications. These applications
30955 can be written in a language other than Ada (e.g., C, C++, etc). Again both
30956 relocatable and non-relocatable Ada DLLs are supported.
30957
30958 @item
30959 You can include Windows resources in your Ada application.
30960
30961 @item
30962 You can use or create COM/DCOM objects.
30963 @end itemize
30964
30965 @noindent
30966 Immediately below are listed all known general GNAT-for-Windows restrictions.
30967 Other restrictions about specific features like Windows Resources and DLLs
30968 are listed in separate sections below.
30969
30970 @itemize @bullet
30971
30972 @item
30973 It is not possible to use @code{GetLastError} and @code{SetLastError}
30974 when tasking, protected records, or exceptions are used. In these
30975 cases, in order to implement Ada semantics, the GNAT run-time system
30976 calls certain Win32 routines that set the last error variable to 0 upon
30977 success. It should be possible to use @code{GetLastError} and
30978 @code{SetLastError} when tasking, protected record, and exception
30979 features are not used, but it is not guaranteed to work.
30980
30981 @item
30982 It is not possible to link against Microsoft libraries except for
30983 import libraries. The library must be built to be compatible with
30984 @file{MSVCRT.LIB} (/MD Microsoft compiler option), @file{LIBC.LIB} and
30985 @file{LIBCMT.LIB} (/ML or /MT Microsoft compiler options) are known to
30986 not be compatible with the GNAT runtime. Even if the library is
30987 compatible with @file{MSVCRT.LIB} it is not guaranteed to work.
30988
30989 @item
30990 When the compilation environment is located on FAT32 drives, users may
30991 experience recompilations of the source files that have not changed if
30992 Daylight Saving Time (DST) state has changed since the last time files
30993 were compiled. NTFS drives do not have this problem.
30994
30995 @item
30996 No components of the GNAT toolset use any entries in the Windows
30997 registry. The only entries that can be created are file associations and
30998 PATH settings, provided the user has chosen to create them at installation
30999 time, as well as some minimal book-keeping information needed to correctly
31000 uninstall or integrate different GNAT products.
31001 @end itemize
31002
31003 @node Using a network installation of GNAT
31004 @section Using a network installation of GNAT
31005
31006 @noindent
31007 Make sure the system on which GNAT is installed is accessible from the
31008 current machine, i.e., the install location is shared over the network.
31009 Shared resources are accessed on Windows by means of UNC paths, which
31010 have the format @code{\\server\sharename\path}
31011
31012 In order to use such a network installation, simply add the UNC path of the
31013 @file{bin} directory of your GNAT installation in front of your PATH. For
31014 example, if GNAT is installed in @file{\GNAT} directory of a share location
31015 called @file{c-drive} on a machine @file{LOKI}, the following command will
31016 make it available:
31017
31018 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
31019
31020 Be aware that every compilation using the network installation results in the
31021 transfer of large amounts of data across the network and will likely cause
31022 serious performance penalty.
31023
31024 @node CONSOLE and WINDOWS subsystems
31025 @section CONSOLE and WINDOWS subsystems
31026 @cindex CONSOLE Subsystem
31027 @cindex WINDOWS Subsystem
31028 @cindex -mwindows
31029
31030 @noindent
31031 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
31032 (which is the default subsystem) will always create a console when
31033 launching the application. This is not something desirable when the
31034 application has a Windows GUI. To get rid of this console the
31035 application must be using the @code{WINDOWS} subsystem. To do so
31036 the @option{-mwindows} linker option must be specified.
31037
31038 @smallexample
31039 $ gnatmake winprog -largs -mwindows
31040 @end smallexample
31041
31042 @node Temporary Files
31043 @section Temporary Files
31044 @cindex Temporary files
31045
31046 @noindent
31047 It is possible to control where temporary files gets created by setting
31048 the @env{TMP} environment variable. The file will be created:
31049
31050 @itemize
31051 @item Under the directory pointed to by the @env{TMP} environment variable if
31052 this directory exists.
31053
31054 @item Under @file{c:\temp}, if the @env{TMP} environment variable is not
31055 set (or not pointing to a directory) and if this directory exists.
31056
31057 @item Under the current working directory otherwise.
31058 @end itemize
31059
31060 @noindent
31061 This allows you to determine exactly where the temporary
31062 file will be created. This is particularly useful in networked
31063 environments where you may not have write access to some
31064 directories.
31065
31066 @node Mixed-Language Programming on Windows
31067 @section Mixed-Language Programming on Windows
31068
31069 @noindent
31070 Developing pure Ada applications on Windows is no different than on
31071 other GNAT-supported platforms. However, when developing or porting an
31072 application that contains a mix of Ada and C/C++, the choice of your
31073 Windows C/C++ development environment conditions your overall
31074 interoperability strategy.
31075
31076 If you use @command{gcc} to compile the non-Ada part of your application,
31077 there are no Windows-specific restrictions that affect the overall
31078 interoperability with your Ada code. If you plan to use
31079 Microsoft tools (e.g.@: Microsoft Visual C/C++), you should be aware of
31080 the following limitations:
31081
31082 @itemize @bullet
31083 @item
31084 You cannot link your Ada code with an object or library generated with
31085 Microsoft tools if these use the @code{.tls} section (Thread Local
31086 Storage section) since the GNAT linker does not yet support this section.
31087
31088 @item
31089 You cannot link your Ada code with an object or library generated with
31090 Microsoft tools if these use I/O routines other than those provided in
31091 the Microsoft DLL: @code{msvcrt.dll}. This is because the GNAT run time
31092 uses the services of @code{msvcrt.dll} for its I/Os. Use of other I/O
31093 libraries can cause a conflict with @code{msvcrt.dll} services. For
31094 instance Visual C++ I/O stream routines conflict with those in
31095 @code{msvcrt.dll}.
31096 @end itemize
31097
31098 @noindent
31099 If you do want to use the Microsoft tools for your non-Ada code and hit one
31100 of the above limitations, you have two choices:
31101
31102 @enumerate
31103 @item
31104 Encapsulate your non-Ada code in a DLL to be linked with your Ada
31105 application. In this case, use the Microsoft or whatever environment to
31106 build the DLL and use GNAT to build your executable
31107 (@pxref{Using DLLs with GNAT}).
31108
31109 @item
31110 Or you can encapsulate your Ada code in a DLL to be linked with the
31111 other part of your application. In this case, use GNAT to build the DLL
31112 (@pxref{Building DLLs with GNAT}) and use the Microsoft or whatever
31113 environment to build your executable.
31114 @end enumerate
31115
31116 @node Windows Calling Conventions
31117 @section Windows Calling Conventions
31118 @findex Stdcall
31119 @findex APIENTRY
31120
31121 @menu
31122 * C Calling Convention::
31123 * Stdcall Calling Convention::
31124 * Win32 Calling Convention::
31125 * DLL Calling Convention::
31126 @end menu
31127
31128 @noindent
31129 When a subprogram @code{F} (caller) calls a subprogram @code{G}
31130 (callee), there are several ways to push @code{G}'s parameters on the
31131 stack and there are several possible scenarios to clean up the stack
31132 upon @code{G}'s return. A calling convention is an agreed upon software
31133 protocol whereby the responsibilities between the caller (@code{F}) and
31134 the callee (@code{G}) are clearly defined. Several calling conventions
31135 are available for Windows:
31136
31137 @itemize @bullet
31138 @item
31139 @code{C} (Microsoft defined)
31140
31141 @item
31142 @code{Stdcall} (Microsoft defined)
31143
31144 @item
31145 @code{Win32} (GNAT specific)
31146
31147 @item
31148 @code{DLL} (GNAT specific)
31149 @end itemize
31150
31151 @node C Calling Convention
31152 @subsection @code{C} Calling Convention
31153
31154 @noindent
31155 This is the default calling convention used when interfacing to C/C++
31156 routines compiled with either @command{gcc} or Microsoft Visual C++.
31157
31158 In the @code{C} calling convention subprogram parameters are pushed on the
31159 stack by the caller from right to left. The caller itself is in charge of
31160 cleaning up the stack after the call. In addition, the name of a routine
31161 with @code{C} calling convention is mangled by adding a leading underscore.
31162
31163 The name to use on the Ada side when importing (or exporting) a routine
31164 with @code{C} calling convention is the name of the routine. For
31165 instance the C function:
31166
31167 @smallexample
31168 int get_val (long);
31169 @end smallexample
31170
31171 @noindent
31172 should be imported from Ada as follows:
31173
31174 @smallexample @c ada
31175 @group
31176 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
31177 pragma Import (C, Get_Val, External_Name => "get_val");
31178 @end group
31179 @end smallexample
31180
31181 @noindent
31182 Note that in this particular case the @code{External_Name} parameter could
31183 have been omitted since, when missing, this parameter is taken to be the
31184 name of the Ada entity in lower case. When the @code{Link_Name} parameter
31185 is missing, as in the above example, this parameter is set to be the
31186 @code{External_Name} with a leading underscore.
31187
31188 When importing a variable defined in C, you should always use the @code{C}
31189 calling convention unless the object containing the variable is part of a
31190 DLL (in which case you should use the @code{Stdcall} calling
31191 convention, @pxref{Stdcall Calling Convention}).
31192
31193 @node Stdcall Calling Convention
31194 @subsection @code{Stdcall} Calling Convention
31195
31196 @noindent
31197 This convention, which was the calling convention used for Pascal
31198 programs, is used by Microsoft for all the routines in the Win32 API for
31199 efficiency reasons. It must be used to import any routine for which this
31200 convention was specified.
31201
31202 In the @code{Stdcall} calling convention subprogram parameters are pushed
31203 on the stack by the caller from right to left. The callee (and not the
31204 caller) is in charge of cleaning the stack on routine exit. In addition,
31205 the name of a routine with @code{Stdcall} calling convention is mangled by
31206 adding a leading underscore (as for the @code{C} calling convention) and a
31207 trailing @code{@@}@code{@var{nn}}, where @var{nn} is the overall size (in
31208 bytes) of the parameters passed to the routine.
31209
31210 The name to use on the Ada side when importing a C routine with a
31211 @code{Stdcall} calling convention is the name of the C routine. The leading
31212 underscore and trailing @code{@@}@code{@var{nn}} are added automatically by
31213 the compiler. For instance the Win32 function:
31214
31215 @smallexample
31216 @b{APIENTRY} int get_val (long);
31217 @end smallexample
31218
31219 @noindent
31220 should be imported from Ada as follows:
31221
31222 @smallexample @c ada
31223 @group
31224 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
31225 pragma Import (Stdcall, Get_Val);
31226 --  On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
31227 @end group
31228 @end smallexample
31229
31230 @noindent
31231 As for the @code{C} calling convention, when the @code{External_Name}
31232 parameter is missing, it is taken to be the name of the Ada entity in lower
31233 case. If instead of writing the above import pragma you write:
31234
31235 @smallexample @c ada
31236 @group
31237 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
31238 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
31239 @end group
31240 @end smallexample
31241
31242 @noindent
31243 then the imported routine is @code{_retrieve_val@@4}. However, if instead
31244 of specifying the @code{External_Name} parameter you specify the
31245 @code{Link_Name} as in the following example:
31246
31247 @smallexample @c ada
31248 @group
31249 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
31250 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
31251 @end group
31252 @end smallexample
31253
31254 @noindent
31255 then the imported routine is @code{retrieve_val}, that is, there is no
31256 decoration at all. No leading underscore and no Stdcall suffix
31257 @code{@@}@code{@var{nn}}.
31258
31259 @noindent
31260 This is especially important as in some special cases a DLL's entry
31261 point name lacks a trailing @code{@@}@code{@var{nn}} while the exported
31262 name generated for a call has it.
31263
31264 @noindent
31265 It is also possible to import variables defined in a DLL by using an
31266 import pragma for a variable. As an example, if a DLL contains a
31267 variable defined as:
31268
31269 @smallexample
31270 int my_var;
31271 @end smallexample
31272
31273 @noindent
31274 then, to access this variable from Ada you should write:
31275
31276 @smallexample @c ada
31277 @group
31278 My_Var : Interfaces.C.int;
31279 pragma Import (Stdcall, My_Var);
31280 @end group
31281 @end smallexample
31282
31283 @noindent
31284 Note that to ease building cross-platform bindings this convention
31285 will be handled as a @code{C} calling convention on non-Windows platforms.
31286
31287 @node Win32 Calling Convention
31288 @subsection @code{Win32} Calling Convention
31289
31290 @noindent
31291 This convention, which is GNAT-specific is fully equivalent to the
31292 @code{Stdcall} calling convention described above.
31293
31294 @node DLL Calling Convention
31295 @subsection @code{DLL} Calling Convention
31296
31297 @noindent
31298 This convention, which is GNAT-specific is fully equivalent to the
31299 @code{Stdcall} calling convention described above.
31300
31301 @node Introduction to Dynamic Link Libraries (DLLs)
31302 @section Introduction to Dynamic Link Libraries (DLLs)
31303 @findex DLL
31304
31305 @noindent
31306 A Dynamically Linked Library (DLL) is a library that can be shared by
31307 several applications running under Windows. A DLL can contain any number of
31308 routines and variables.
31309
31310 One advantage of DLLs is that you can change and enhance them without
31311 forcing all the applications that depend on them to be relinked or
31312 recompiled. However, you should be aware than all calls to DLL routines are
31313 slower since, as you will understand below, such calls are indirect.
31314
31315 To illustrate the remainder of this section, suppose that an application
31316 wants to use the services of a DLL @file{API.dll}. To use the services
31317 provided by @file{API.dll} you must statically link against the DLL or
31318 an import library which contains a jump table with an entry for each
31319 routine and variable exported by the DLL. In the Microsoft world this
31320 import library is called @file{API.lib}. When using GNAT this import
31321 library is called either @file{libAPI.dll.a}, @file{libapi.dll.a},
31322 @file{libAPI.a} or @file{libapi.a} (names are case insensitive).
31323
31324 After you have linked your application with the DLL or the import library
31325 and you run your application, here is what happens:
31326
31327 @enumerate
31328 @item
31329 Your application is loaded into memory.
31330
31331 @item
31332 The DLL @file{API.dll} is mapped into the address space of your
31333 application. This means that:
31334
31335 @itemize @bullet
31336 @item
31337 The DLL will use the stack of the calling thread.
31338
31339 @item
31340 The DLL will use the virtual address space of the calling process.
31341
31342 @item
31343 The DLL will allocate memory from the virtual address space of the calling
31344 process.
31345
31346 @item
31347 Handles (pointers) can be safely exchanged between routines in the DLL
31348 routines and routines in the application using the DLL.
31349 @end itemize
31350
31351 @item
31352 The entries in the jump table (from the import library @file{libAPI.dll.a}
31353 or @file{API.lib} or automatically created when linking against a DLL)
31354 which is part of your application are initialized with the addresses
31355 of the routines and variables in @file{API.dll}.
31356
31357 @item
31358 If present in @file{API.dll}, routines @code{DllMain} or
31359 @code{DllMainCRTStartup} are invoked. These routines typically contain
31360 the initialization code needed for the well-being of the routines and
31361 variables exported by the DLL.
31362 @end enumerate
31363
31364 @noindent
31365 There is an additional point which is worth mentioning. In the Windows
31366 world there are two kind of DLLs: relocatable and non-relocatable
31367 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
31368 in the target application address space. If the addresses of two
31369 non-relocatable DLLs overlap and these happen to be used by the same
31370 application, a conflict will occur and the application will run
31371 incorrectly. Hence, when possible, it is always preferable to use and
31372 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
31373 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
31374 User's Guide) removes the debugging symbols from the DLL but the DLL can
31375 still be relocated.
31376
31377 As a side note, an interesting difference between Microsoft DLLs and
31378 Unix shared libraries, is the fact that on most Unix systems all public
31379 routines are exported by default in a Unix shared library, while under
31380 Windows it is possible (but not required) to list exported routines in
31381 a definition file (@pxref{The Definition File}).
31382
31383 @node Using DLLs with GNAT
31384 @section Using DLLs with GNAT
31385
31386 @menu
31387 * Creating an Ada Spec for the DLL Services::
31388 * Creating an Import Library::
31389 @end menu
31390
31391 @noindent
31392 To use the services of a DLL, say @file{API.dll}, in your Ada application
31393 you must have:
31394
31395 @enumerate
31396 @item
31397 The Ada spec for the routines and/or variables you want to access in
31398 @file{API.dll}. If not available this Ada spec must be built from the C/C++
31399 header files provided with the DLL.
31400
31401 @item
31402 The import library (@file{libAPI.dll.a} or @file{API.lib}). As previously
31403 mentioned an import library is a statically linked library containing the
31404 import table which will be filled at load time to point to the actual
31405 @file{API.dll} routines. Sometimes you don't have an import library for the
31406 DLL you want to use. The following sections will explain how to build
31407 one. Note that this is optional.
31408
31409 @item
31410 The actual DLL, @file{API.dll}.
31411 @end enumerate
31412
31413 @noindent
31414 Once you have all the above, to compile an Ada application that uses the
31415 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
31416 you simply issue the command
31417
31418 @smallexample
31419 $ gnatmake my_ada_app -largs -lAPI
31420 @end smallexample
31421
31422 @noindent
31423 The argument @option{-largs -lAPI} at the end of the @command{gnatmake} command
31424 tells the GNAT linker to look first for a library named @file{API.lib}
31425 (Microsoft-style name) and if not found for a libraries named
31426 @file{libAPI.dll.a}, @file{API.dll.a} or @file{libAPI.a}.
31427 (GNAT-style name). Note that if the Ada package spec for @file{API.dll}
31428 contains the following pragma
31429
31430 @smallexample @c ada
31431 pragma Linker_Options ("-lAPI");
31432 @end smallexample
31433
31434 @noindent
31435 you do not have to add @option{-largs -lAPI} at the end of the
31436 @command{gnatmake} command.
31437
31438 If any one of the items above is missing you will have to create it
31439 yourself. The following sections explain how to do so using as an
31440 example a fictitious DLL called @file{API.dll}.
31441
31442 @node Creating an Ada Spec for the DLL Services
31443 @subsection Creating an Ada Spec for the DLL Services
31444
31445 @noindent
31446 A DLL typically comes with a C/C++ header file which provides the
31447 definitions of the routines and variables exported by the DLL. The Ada
31448 equivalent of this header file is a package spec that contains definitions
31449 for the imported entities. If the DLL you intend to use does not come with
31450 an Ada spec you have to generate one such spec yourself. For example if
31451 the header file of @file{API.dll} is a file @file{api.h} containing the
31452 following two definitions:
31453
31454 @smallexample
31455 @group
31456 @cartouche
31457 int some_var;
31458 int get (char *);
31459 @end cartouche
31460 @end group
31461 @end smallexample
31462
31463 @noindent
31464 then the equivalent Ada spec could be:
31465
31466 @smallexample @c ada
31467 @group
31468 @cartouche
31469 with Interfaces.C.Strings;
31470 package API is
31471    use Interfaces;
31472
31473    Some_Var : C.int;
31474    function Get (Str : C.Strings.Chars_Ptr) return C.int;
31475
31476 private
31477    pragma Import (C, Get);
31478    pragma Import (DLL, Some_Var);
31479 end API;
31480 @end cartouche
31481 @end group
31482 @end smallexample
31483
31484 @noindent
31485 Note that a variable is
31486 @strong{always imported with a Stdcall convention}. A function
31487 can have @code{C} or @code{Stdcall} convention.
31488 (@pxref{Windows Calling Conventions}).
31489
31490 @node Creating an Import Library
31491 @subsection Creating an Import Library
31492 @cindex Import library
31493
31494 @menu
31495 * The Definition File::
31496 * GNAT-Style Import Library::
31497 * Microsoft-Style Import Library::
31498 @end menu
31499
31500 @noindent
31501 If a Microsoft-style import library @file{API.lib} or a GNAT-style
31502 import library @file{libAPI.dll.a} or @file{libAPI.a} is available
31503 with @file{API.dll} you can skip this section. You can also skip this
31504 section if @file{API.dll} or @file{libAPI.dll} is built with GNU tools
31505 as in this case it is possible to link directly against the
31506 DLL. Otherwise read on.
31507
31508 @node The Definition File
31509 @subsubsection The Definition File
31510 @cindex Definition file
31511 @findex .def
31512
31513 @noindent
31514 As previously mentioned, and unlike Unix systems, the list of symbols
31515 that are exported from a DLL must be provided explicitly in Windows.
31516 The main goal of a definition file is precisely that: list the symbols
31517 exported by a DLL. A definition file (usually a file with a @code{.def}
31518 suffix) has the following structure:
31519
31520 @smallexample
31521 @group
31522 @cartouche
31523 @r{[}LIBRARY @var{name}@r{]}
31524 @r{[}DESCRIPTION @var{string}@r{]}
31525 EXPORTS
31526    @var{symbol1}
31527    @var{symbol2}
31528    @dots{}
31529 @end cartouche
31530 @end group
31531 @end smallexample
31532
31533 @table @code
31534 @item LIBRARY @var{name}
31535 This section, which is optional, gives the name of the DLL.
31536
31537 @item DESCRIPTION @var{string}
31538 This section, which is optional, gives a description string that will be
31539 embedded in the import library.
31540
31541 @item EXPORTS
31542 This section gives the list of exported symbols (procedures, functions or
31543 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
31544 section of @file{API.def} looks like:
31545
31546 @smallexample
31547 @group
31548 @cartouche
31549 EXPORTS
31550    some_var
31551    get
31552 @end cartouche
31553 @end group
31554 @end smallexample
31555 @end table
31556
31557 @noindent
31558 Note that you must specify the correct suffix (@code{@@}@code{@var{nn}})
31559 (@pxref{Windows Calling Conventions}) for a Stdcall
31560 calling convention function in the exported symbols list.
31561
31562 @noindent
31563 There can actually be other sections in a definition file, but these
31564 sections are not relevant to the discussion at hand.
31565
31566 @node GNAT-Style Import Library
31567 @subsubsection GNAT-Style Import Library
31568
31569 @noindent
31570 To create a static import library from @file{API.dll} with the GNAT tools
31571 you should proceed as follows:
31572
31573 @enumerate
31574 @item
31575 Create the definition file @file{API.def} (@pxref{The Definition File}).
31576 For that use the @code{dll2def} tool as follows:
31577
31578 @smallexample
31579 $ dll2def API.dll > API.def
31580 @end smallexample
31581
31582 @noindent
31583 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
31584 to standard output the list of entry points in the DLL. Note that if
31585 some routines in the DLL have the @code{Stdcall} convention
31586 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@var{nn}
31587 suffix then you'll have to edit @file{api.def} to add it, and specify
31588 @option{-k} to @command{gnatdll} when creating the import library.
31589
31590 @noindent
31591 Here are some hints to find the right @code{@@}@var{nn} suffix.
31592
31593 @enumerate
31594 @item
31595 If you have the Microsoft import library (.lib), it is possible to get
31596 the right symbols by using Microsoft @code{dumpbin} tool (see the
31597 corresponding Microsoft documentation for further details).
31598
31599 @smallexample
31600 $ dumpbin /exports api.lib
31601 @end smallexample
31602
31603 @item
31604 If you have a message about a missing symbol at link time the compiler
31605 tells you what symbol is expected. You just have to go back to the
31606 definition file and add the right suffix.
31607 @end enumerate
31608
31609 @item
31610 Build the import library @code{libAPI.dll.a}, using @code{gnatdll}
31611 (@pxref{Using gnatdll}) as follows:
31612
31613 @smallexample
31614 $ gnatdll -e API.def -d API.dll
31615 @end smallexample
31616
31617 @noindent
31618 @code{gnatdll} takes as input a definition file @file{API.def} and the
31619 name of the DLL containing the services listed in the definition file
31620 @file{API.dll}. The name of the static import library generated is
31621 computed from the name of the definition file as follows: if the
31622 definition file name is @var{xyz}@code{.def}, the import library name will
31623 be @code{lib}@var{xyz}@code{.a}. Note that in the previous example option
31624 @option{-e} could have been removed because the name of the definition
31625 file (before the ``@code{.def}'' suffix) is the same as the name of the
31626 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
31627 @end enumerate
31628
31629 @node Microsoft-Style Import Library
31630 @subsubsection Microsoft-Style Import Library
31631
31632 @noindent
31633 With GNAT you can either use a GNAT-style or Microsoft-style import
31634 library. A Microsoft import library is needed only if you plan to make an
31635 Ada DLL available to applications developed with Microsoft
31636 tools (@pxref{Mixed-Language Programming on Windows}).
31637
31638 To create a Microsoft-style import library for @file{API.dll} you
31639 should proceed as follows:
31640
31641 @enumerate
31642 @item
31643 Create the definition file @file{API.def} from the DLL. For this use either
31644 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
31645 tool (see the corresponding Microsoft documentation for further details).
31646
31647 @item
31648 Build the actual import library using Microsoft's @code{lib} utility:
31649
31650 @smallexample
31651 $ lib -machine:IX86 -def:API.def -out:API.lib
31652 @end smallexample
31653
31654 @noindent
31655 If you use the above command the definition file @file{API.def} must
31656 contain a line giving the name of the DLL:
31657
31658 @smallexample
31659 LIBRARY      "API"
31660 @end smallexample
31661
31662 @noindent
31663 See the Microsoft documentation for further details about the usage of
31664 @code{lib}.
31665 @end enumerate
31666
31667 @node Building DLLs with GNAT
31668 @section Building DLLs with GNAT
31669 @cindex DLLs, building
31670
31671 @noindent
31672 This section explain how to build DLLs using the GNAT built-in DLL
31673 support. With the following procedure it is straight forward to build
31674 and use DLLs with GNAT.
31675
31676 @enumerate
31677
31678 @item building object files
31679
31680 The first step is to build all objects files that are to be included
31681 into the DLL. This is done by using the standard @command{gnatmake} tool.
31682
31683 @item building the DLL
31684
31685 To build the DLL you must use @command{gcc}'s @option{-shared}
31686 option. It is quite simple to use this method:
31687
31688 @smallexample
31689 $ gcc -shared -o api.dll obj1.o obj2.o @dots{}
31690 @end smallexample
31691
31692 It is important to note that in this case all symbols found in the
31693 object files are automatically exported. It is possible to restrict
31694 the set of symbols to export by passing to @command{gcc} a definition
31695 file, @pxref{The Definition File}. For example:
31696
31697 @smallexample
31698 $ gcc -shared -o api.dll api.def obj1.o obj2.o @dots{}
31699 @end smallexample
31700
31701 If you use a definition file you must export the elaboration procedures
31702 for every package that required one. Elaboration procedures are named
31703 using the package name followed by "_E".
31704
31705 @item preparing DLL to be used
31706
31707 For the DLL to be used by client programs the bodies must be hidden
31708 from it and the .ali set with read-only attribute. This is very important
31709 otherwise GNAT will recompile all packages and will not actually use
31710 the code in the DLL. For example:
31711
31712 @smallexample
31713 $ mkdir apilib
31714 $ copy *.ads *.ali api.dll apilib
31715 $ attrib +R apilib\*.ali
31716 @end smallexample
31717
31718 @end enumerate
31719
31720 At this point it is possible to use the DLL by directly linking
31721 against it. Note that you must use the GNAT shared runtime when using
31722 GNAT shared libraries. This is achieved by using @option{-shared} binder's
31723 option.
31724
31725 @smallexample
31726 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
31727 @end smallexample
31728
31729 @node Building DLLs with GNAT Project files
31730 @section Building DLLs with GNAT Project files
31731 @cindex DLLs, building
31732
31733 @noindent
31734 There is nothing specific to Windows in the build process.
31735 @pxref{Library Projects}.
31736
31737 @noindent
31738 Due to a system limitation, it is not possible under Windows to create threads
31739 when inside the @code{DllMain} routine which is used for auto-initialization
31740 of shared libraries, so it is not possible to have library level tasks in SALs.
31741
31742 @node Building DLLs with gnatdll
31743 @section Building DLLs with gnatdll
31744 @cindex DLLs, building
31745
31746 @menu
31747 * Limitations When Using Ada DLLs from Ada::
31748 * Exporting Ada Entities::
31749 * Ada DLLs and Elaboration::
31750 * Ada DLLs and Finalization::
31751 * Creating a Spec for Ada DLLs::
31752 * Creating the Definition File::
31753 * Using gnatdll::
31754 @end menu
31755
31756 @noindent
31757 Note that it is preferred to use the built-in GNAT DLL support
31758 (@pxref{Building DLLs with GNAT}) or GNAT Project files
31759 (@pxref{Building DLLs with GNAT Project files}) to build DLLs.
31760
31761 This section explains how to build DLLs containing Ada code using
31762 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
31763 remainder of this section.
31764
31765 The steps required to build an Ada DLL that is to be used by Ada as well as
31766 non-Ada applications are as follows:
31767
31768 @enumerate
31769 @item
31770 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
31771 @code{Stdcall} calling convention to avoid any Ada name mangling for the
31772 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
31773 skip this step if you plan to use the Ada DLL only from Ada applications.
31774
31775 @item
31776 Your Ada code must export an initialization routine which calls the routine
31777 @code{adainit} generated by @command{gnatbind} to perform the elaboration of
31778 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
31779 routine exported by the Ada DLL must be invoked by the clients of the DLL
31780 to initialize the DLL.
31781
31782 @item
31783 When useful, the DLL should also export a finalization routine which calls
31784 routine @code{adafinal} generated by @command{gnatbind} to perform the
31785 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
31786 The finalization routine exported by the Ada DLL must be invoked by the
31787 clients of the DLL when the DLL services are no further needed.
31788
31789 @item
31790 You must provide a spec for the services exported by the Ada DLL in each
31791 of the programming languages to which you plan to make the DLL available.
31792
31793 @item
31794 You must provide a definition file listing the exported entities
31795 (@pxref{The Definition File}).
31796
31797 @item
31798 Finally you must use @code{gnatdll} to produce the DLL and the import
31799 library (@pxref{Using gnatdll}).
31800 @end enumerate
31801
31802 @noindent
31803 Note that a relocatable DLL stripped using the @code{strip}
31804 binutils tool will not be relocatable anymore. To build a DLL without
31805 debug information pass @code{-largs -s} to @code{gnatdll}. This
31806 restriction does not apply to a DLL built using a Library Project.
31807 @pxref{Library Projects}.
31808
31809 @node Limitations When Using Ada DLLs from Ada
31810 @subsection Limitations When Using Ada DLLs from Ada
31811
31812 @noindent
31813 When using Ada DLLs from Ada applications there is a limitation users
31814 should be aware of. Because on Windows the GNAT run time is not in a DLL of
31815 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
31816 each Ada DLL includes the services of the GNAT run time that are necessary
31817 to the Ada code inside the DLL. As a result, when an Ada program uses an
31818 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
31819 one in the main program.
31820
31821 It is therefore not possible to exchange GNAT run-time objects between the
31822 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
31823 handles (e.g.@: @code{Text_IO.File_Type}), tasks types, protected objects
31824 types, etc.
31825
31826 It is completely safe to exchange plain elementary, array or record types,
31827 Windows object handles, etc.
31828
31829 @node Exporting Ada Entities
31830 @subsection Exporting Ada Entities
31831 @cindex Export table
31832
31833 @noindent
31834 Building a DLL is a way to encapsulate a set of services usable from any
31835 application. As a result, the Ada entities exported by a DLL should be
31836 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
31837 any Ada name mangling. As an example here is an Ada package
31838 @code{API}, spec and body, exporting two procedures, a function, and a
31839 variable:
31840
31841 @smallexample @c ada
31842 @group
31843 @cartouche
31844 with Interfaces.C; use Interfaces;
31845 package API is
31846    Count : C.int := 0;
31847    function Factorial (Val : C.int) return C.int;
31848
31849    procedure Initialize_API;
31850    procedure Finalize_API;
31851    --  Initialization & Finalization routines. More in the next section.
31852 private
31853    pragma Export (C, Initialize_API);
31854    pragma Export (C, Finalize_API);
31855    pragma Export (C, Count);
31856    pragma Export (C, Factorial);
31857 end API;
31858 @end cartouche
31859 @end group
31860 @end smallexample
31861
31862 @smallexample @c ada
31863 @group
31864 @cartouche
31865 package body API is
31866    function Factorial (Val : C.int) return C.int is
31867       Fact : C.int := 1;
31868    begin
31869       Count := Count + 1;
31870       for K in 1 .. Val loop
31871          Fact := Fact * K;
31872       end loop;
31873       return Fact;
31874    end Factorial;
31875
31876    procedure Initialize_API is
31877       procedure Adainit;
31878       pragma Import (C, Adainit);
31879    begin
31880       Adainit;
31881    end Initialize_API;
31882
31883    procedure Finalize_API is
31884       procedure Adafinal;
31885       pragma Import (C, Adafinal);
31886    begin
31887       Adafinal;
31888    end Finalize_API;
31889 end API;
31890 @end cartouche
31891 @end group
31892 @end smallexample
31893
31894 @noindent
31895 If the Ada DLL you are building will only be used by Ada applications
31896 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
31897 convention. As an example, the previous package could be written as
31898 follows:
31899
31900 @smallexample @c ada
31901 @group
31902 @cartouche
31903 package API is
31904    Count : Integer := 0;
31905    function Factorial (Val : Integer) return Integer;
31906
31907    procedure Initialize_API;
31908    procedure Finalize_API;
31909    --  Initialization and Finalization routines.
31910 end API;
31911 @end cartouche
31912 @end group
31913 @end smallexample
31914
31915 @smallexample @c ada
31916 @group
31917 @cartouche
31918 package body API is
31919    function Factorial (Val : Integer) return Integer is
31920       Fact : Integer := 1;
31921    begin
31922       Count := Count + 1;
31923       for K in 1 .. Val loop
31924          Fact := Fact * K;
31925       end loop;
31926       return Fact;
31927    end Factorial;
31928
31929    @dots{}
31930    --  The remainder of this package body is unchanged.
31931 end API;
31932 @end cartouche
31933 @end group
31934 @end smallexample
31935
31936 @noindent
31937 Note that if you do not export the Ada entities with a @code{C} or
31938 @code{Stdcall} convention you will have to provide the mangled Ada names
31939 in the definition file of the Ada DLL
31940 (@pxref{Creating the Definition File}).
31941
31942 @node Ada DLLs and Elaboration
31943 @subsection Ada DLLs and Elaboration
31944 @cindex DLLs and elaboration
31945
31946 @noindent
31947 The DLL that you are building contains your Ada code as well as all the
31948 routines in the Ada library that are needed by it. The first thing a
31949 user of your DLL must do is elaborate the Ada code
31950 (@pxref{Elaboration Order Handling in GNAT}).
31951
31952 To achieve this you must export an initialization routine
31953 (@code{Initialize_API} in the previous example), which must be invoked
31954 before using any of the DLL services. This elaboration routine must call
31955 the Ada elaboration routine @code{adainit} generated by the GNAT binder
31956 (@pxref{Binding with Non-Ada Main Programs}). See the body of
31957 @code{Initialize_Api} for an example. Note that the GNAT binder is
31958 automatically invoked during the DLL build process by the @code{gnatdll}
31959 tool (@pxref{Using gnatdll}).
31960
31961 When a DLL is loaded, Windows systematically invokes a routine called
31962 @code{DllMain}. It would therefore be possible to call @code{adainit}
31963 directly from @code{DllMain} without having to provide an explicit
31964 initialization routine. Unfortunately, it is not possible to call
31965 @code{adainit} from the @code{DllMain} if your program has library level
31966 tasks because access to the @code{DllMain} entry point is serialized by
31967 the system (that is, only a single thread can execute ``through'' it at a
31968 time), which means that the GNAT run time will deadlock waiting for the
31969 newly created task to complete its initialization.
31970
31971 @node Ada DLLs and Finalization
31972 @subsection Ada DLLs and Finalization
31973 @cindex DLLs and finalization
31974
31975 @noindent
31976 When the services of an Ada DLL are no longer needed, the client code should
31977 invoke the DLL finalization routine, if available. The DLL finalization
31978 routine is in charge of releasing all resources acquired by the DLL. In the
31979 case of the Ada code contained in the DLL, this is achieved by calling
31980 routine @code{adafinal} generated by the GNAT binder
31981 (@pxref{Binding with Non-Ada Main Programs}).
31982 See the body of @code{Finalize_Api} for an
31983 example. As already pointed out the GNAT binder is automatically invoked
31984 during the DLL build process by the @code{gnatdll} tool
31985 (@pxref{Using gnatdll}).
31986
31987 @node Creating a Spec for Ada DLLs
31988 @subsection Creating a Spec for Ada DLLs
31989
31990 @noindent
31991 To use the services exported by the Ada DLL from another programming
31992 language (e.g.@: C), you have to translate the specs of the exported Ada
31993 entities in that language. For instance in the case of @code{API.dll},
31994 the corresponding C header file could look like:
31995
31996 @smallexample
31997 @group
31998 @cartouche
31999 extern int *_imp__count;
32000 #define count (*_imp__count)
32001 int factorial (int);
32002 @end cartouche
32003 @end group
32004 @end smallexample
32005
32006 @noindent
32007 It is important to understand that when building an Ada DLL to be used by
32008 other Ada applications, you need two different specs for the packages
32009 contained in the DLL: one for building the DLL and the other for using
32010 the DLL. This is because the @code{DLL} calling convention is needed to
32011 use a variable defined in a DLL, but when building the DLL, the variable
32012 must have either the @code{Ada} or @code{C} calling convention. As an
32013 example consider a DLL comprising the following package @code{API}:
32014
32015 @smallexample @c ada
32016 @group
32017 @cartouche
32018 package API is
32019    Count : Integer := 0;
32020    @dots{}
32021    --  Remainder of the package omitted.
32022 end API;
32023 @end cartouche
32024 @end group
32025 @end smallexample
32026
32027 @noindent
32028 After producing a DLL containing package @code{API}, the spec that
32029 must be used to import @code{API.Count} from Ada code outside of the
32030 DLL is:
32031
32032 @smallexample @c ada
32033 @group
32034 @cartouche
32035 package API is
32036    Count : Integer;
32037    pragma Import (DLL, Count);
32038 end API;
32039 @end cartouche
32040 @end group
32041 @end smallexample
32042
32043 @node Creating the Definition File
32044 @subsection Creating the Definition File
32045
32046 @noindent
32047 The definition file is the last file needed to build the DLL. It lists
32048 the exported symbols. As an example, the definition file for a DLL
32049 containing only package @code{API} (where all the entities are exported
32050 with a @code{C} calling convention) is:
32051
32052 @smallexample
32053 @group
32054 @cartouche
32055 EXPORTS
32056     count
32057     factorial
32058     finalize_api
32059     initialize_api
32060 @end cartouche
32061 @end group
32062 @end smallexample
32063
32064 @noindent
32065 If the @code{C} calling convention is missing from package @code{API},
32066 then the definition file contains the mangled Ada names of the above
32067 entities, which in this case are:
32068
32069 @smallexample
32070 @group
32071 @cartouche
32072 EXPORTS
32073     api__count
32074     api__factorial
32075     api__finalize_api
32076     api__initialize_api
32077 @end cartouche
32078 @end group
32079 @end smallexample
32080
32081 @node Using gnatdll
32082 @subsection Using @code{gnatdll}
32083 @findex gnatdll
32084
32085 @menu
32086 * gnatdll Example::
32087 * gnatdll behind the Scenes::
32088 * Using dlltool::
32089 @end menu
32090
32091 @noindent
32092 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
32093 and non-Ada sources that make up your DLL have been compiled.
32094 @code{gnatdll} is actually in charge of two distinct tasks: build the
32095 static import library for the DLL and the actual DLL. The form of the
32096 @code{gnatdll} command is
32097
32098 @smallexample
32099 @cartouche
32100 $ gnatdll @ovar{switches} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
32101 @end cartouche
32102 @end smallexample
32103
32104 @noindent
32105 where @var{list-of-files} is a list of ALI and object files. The object
32106 file list must be the exact list of objects corresponding to the non-Ada
32107 sources whose services are to be included in the DLL. The ALI file list
32108 must be the exact list of ALI files for the corresponding Ada sources
32109 whose services are to be included in the DLL. If @var{list-of-files} is
32110 missing, only the static import library is generated.
32111
32112 @noindent
32113 You may specify any of the following switches to @code{gnatdll}:
32114
32115 @table @code
32116 @item -a@ovar{address}
32117 @cindex @option{-a} (@code{gnatdll})
32118 Build a non-relocatable DLL at @var{address}. If @var{address} is not
32119 specified the default address @var{0x11000000} will be used. By default,
32120 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
32121 advise the reader to build relocatable DLL.
32122
32123 @item -b @var{address}
32124 @cindex @option{-b} (@code{gnatdll})
32125 Set the relocatable DLL base address. By default the address is
32126 @code{0x11000000}.
32127
32128 @item -bargs @var{opts}
32129 @cindex @option{-bargs} (@code{gnatdll})
32130 Binder options. Pass @var{opts} to the binder.
32131
32132 @item -d @var{dllfile}
32133 @cindex @option{-d} (@code{gnatdll})
32134 @var{dllfile} is the name of the DLL. This switch must be present for
32135 @code{gnatdll} to do anything. The name of the generated import library is
32136 obtained algorithmically from @var{dllfile} as shown in the following
32137 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
32138 @code{libxyz.dll.a}. The name of the definition file to use (if not specified
32139 by option @option{-e}) is obtained algorithmically from @var{dllfile}
32140 as shown in the following example:
32141 if @var{dllfile} is @code{xyz.dll}, the definition
32142 file used is @code{xyz.def}.
32143
32144 @item -e @var{deffile}
32145 @cindex @option{-e} (@code{gnatdll})
32146 @var{deffile} is the name of the definition file.
32147
32148 @item -g
32149 @cindex @option{-g} (@code{gnatdll})
32150 Generate debugging information. This information is stored in the object
32151 file and copied from there to the final DLL file by the linker,
32152 where it can be read by the debugger. You must use the
32153 @option{-g} switch if you plan on using the debugger or the symbolic
32154 stack traceback.
32155
32156 @item -h
32157 @cindex @option{-h} (@code{gnatdll})
32158 Help mode. Displays @code{gnatdll} switch usage information.
32159
32160 @item -Idir
32161 @cindex @option{-I} (@code{gnatdll})
32162 Direct @code{gnatdll} to search the @var{dir} directory for source and
32163 object files needed to build the DLL.
32164 (@pxref{Search Paths and the Run-Time Library (RTL)}).
32165
32166 @item -k
32167 @cindex @option{-k} (@code{gnatdll})
32168 Removes the @code{@@}@var{nn} suffix from the import library's exported
32169 names, but keeps them for the link names. You must specify this
32170 option if you want to use a @code{Stdcall} function in a DLL for which
32171 the @code{@@}@var{nn} suffix has been removed. This is the case for most
32172 of the Windows NT DLL for example. This option has no effect when
32173 @option{-n} option is specified.
32174
32175 @item -l @var{file}
32176 @cindex @option{-l} (@code{gnatdll})
32177 The list of ALI and object files used to build the DLL are listed in
32178 @var{file}, instead of being given in the command line. Each line in
32179 @var{file} contains the name of an ALI or object file.
32180
32181 @item -n
32182 @cindex @option{-n} (@code{gnatdll})
32183 No Import. Do not create the import library.
32184
32185 @item -q
32186 @cindex @option{-q} (@code{gnatdll})
32187 Quiet mode. Do not display unnecessary messages.
32188
32189 @item -v
32190 @cindex @option{-v} (@code{gnatdll})
32191 Verbose mode. Display extra information.
32192
32193 @item -largs @var{opts}
32194 @cindex @option{-largs} (@code{gnatdll})
32195 Linker options. Pass @var{opts} to the linker.
32196 @end table
32197
32198 @node gnatdll Example
32199 @subsubsection @code{gnatdll} Example
32200
32201 @noindent
32202 As an example the command to build a relocatable DLL from @file{api.adb}
32203 once @file{api.adb} has been compiled and @file{api.def} created is
32204
32205 @smallexample
32206 $ gnatdll -d api.dll api.ali
32207 @end smallexample
32208
32209 @noindent
32210 The above command creates two files: @file{libapi.dll.a} (the import
32211 library) and @file{api.dll} (the actual DLL). If you want to create
32212 only the DLL, just type:
32213
32214 @smallexample
32215 $ gnatdll -d api.dll -n api.ali
32216 @end smallexample
32217
32218 @noindent
32219 Alternatively if you want to create just the import library, type:
32220
32221 @smallexample
32222 $ gnatdll -d api.dll
32223 @end smallexample
32224
32225 @node gnatdll behind the Scenes
32226 @subsubsection @code{gnatdll} behind the Scenes
32227
32228 @noindent
32229 This section details the steps involved in creating a DLL. @code{gnatdll}
32230 does these steps for you. Unless you are interested in understanding what
32231 goes on behind the scenes, you should skip this section.
32232
32233 We use the previous example of a DLL containing the Ada package @code{API},
32234 to illustrate the steps necessary to build a DLL. The starting point is a
32235 set of objects that will make up the DLL and the corresponding ALI
32236 files. In the case of this example this means that @file{api.o} and
32237 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
32238 the following:
32239
32240 @enumerate
32241 @item
32242 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
32243 the information necessary to generate relocation information for the
32244 DLL.
32245
32246 @smallexample
32247 @group
32248 $ gnatbind -n api
32249 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
32250 @end group
32251 @end smallexample
32252
32253 @noindent
32254 In addition to the base file, the @command{gnatlink} command generates an
32255 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
32256 asks @command{gnatlink} to generate the routines @code{DllMain} and
32257 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
32258 is loaded into memory.
32259
32260 @item
32261 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
32262 export table (@file{api.exp}). The export table contains the relocation
32263 information in a form which can be used during the final link to ensure
32264 that the Windows loader is able to place the DLL anywhere in memory.
32265
32266 @smallexample
32267 @group
32268 $ dlltool --dllname api.dll --def api.def --base-file api.base \
32269           --output-exp api.exp
32270 @end group
32271 @end smallexample
32272
32273 @item
32274 @code{gnatdll} builds the base file using the new export table. Note that
32275 @command{gnatbind} must be called once again since the binder generated file
32276 has been deleted during the previous call to @command{gnatlink}.
32277
32278 @smallexample
32279 @group
32280 $ gnatbind -n api
32281 $ gnatlink api -o api.jnk api.exp -mdll
32282       -Wl,--base-file,api.base
32283 @end group
32284 @end smallexample
32285
32286 @item
32287 @code{gnatdll} builds the new export table using the new base file and
32288 generates the DLL import library @file{libAPI.dll.a}.
32289
32290 @smallexample
32291 @group
32292 $ dlltool --dllname api.dll --def api.def --base-file api.base \
32293           --output-exp api.exp --output-lib libAPI.a
32294 @end group
32295 @end smallexample
32296
32297 @item
32298 Finally @code{gnatdll} builds the relocatable DLL using the final export
32299 table.
32300
32301 @smallexample
32302 @group
32303 $ gnatbind -n api
32304 $ gnatlink api api.exp -o api.dll -mdll
32305 @end group
32306 @end smallexample
32307 @end enumerate
32308
32309 @node Using dlltool
32310 @subsubsection Using @code{dlltool}
32311
32312 @noindent
32313 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
32314 DLLs and static import libraries. This section summarizes the most
32315 common @code{dlltool} switches. The form of the @code{dlltool} command
32316 is
32317
32318 @smallexample
32319 $ dlltool @ovar{switches}
32320 @end smallexample
32321
32322 @noindent
32323 @code{dlltool} switches include:
32324
32325 @table @option
32326 @item --base-file @var{basefile}
32327 @cindex @option{--base-file} (@command{dlltool})
32328 Read the base file @var{basefile} generated by the linker. This switch
32329 is used to create a relocatable DLL.
32330
32331 @item --def @var{deffile}
32332 @cindex @option{--def} (@command{dlltool})
32333 Read the definition file.
32334
32335 @item --dllname @var{name}
32336 @cindex @option{--dllname} (@command{dlltool})
32337 Gives the name of the DLL. This switch is used to embed the name of the
32338 DLL in the static import library generated by @code{dlltool} with switch
32339 @option{--output-lib}.
32340
32341 @item -k
32342 @cindex @option{-k} (@command{dlltool})
32343 Kill @code{@@}@var{nn} from exported names
32344 (@pxref{Windows Calling Conventions}
32345 for a discussion about @code{Stdcall}-style symbols.
32346
32347 @item --help
32348 @cindex @option{--help} (@command{dlltool})
32349 Prints the @code{dlltool} switches with a concise description.
32350
32351 @item --output-exp @var{exportfile}
32352 @cindex @option{--output-exp} (@command{dlltool})
32353 Generate an export file @var{exportfile}. The export file contains the
32354 export table (list of symbols in the DLL) and is used to create the DLL.
32355
32356 @item --output-lib @var{libfile}
32357 @cindex @option{--output-lib} (@command{dlltool})
32358 Generate a static import library @var{libfile}.
32359
32360 @item -v
32361 @cindex @option{-v} (@command{dlltool})
32362 Verbose mode.
32363
32364 @item --as @var{assembler-name}
32365 @cindex @option{--as} (@command{dlltool})
32366 Use @var{assembler-name} as the assembler. The default is @code{as}.
32367 @end table
32368
32369 @node GNAT and Windows Resources
32370 @section GNAT and Windows Resources
32371 @cindex Resources, windows
32372
32373 @menu
32374 * Building Resources::
32375 * Compiling Resources::
32376 * Using Resources::
32377 @end menu
32378
32379 @noindent
32380 Resources are an easy way to add Windows specific objects to your
32381 application. The objects that can be added as resources include:
32382
32383 @itemize @bullet
32384 @item
32385 menus
32386
32387 @item
32388 accelerators
32389
32390 @item
32391 dialog boxes
32392
32393 @item
32394 string tables
32395
32396 @item
32397 bitmaps
32398
32399 @item
32400 cursors
32401
32402 @item
32403 icons
32404
32405 @item
32406 fonts
32407 @end itemize
32408
32409 @noindent
32410 This section explains how to build, compile and use resources.
32411
32412 @node Building Resources
32413 @subsection Building Resources
32414 @cindex Resources, building
32415
32416 @noindent
32417 A resource file is an ASCII file. By convention resource files have an
32418 @file{.rc} extension.
32419 The easiest way to build a resource file is to use Microsoft tools
32420 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
32421 @code{dlgedit.exe} to build dialogs.
32422 It is always possible to build an @file{.rc} file yourself by writing a
32423 resource script.
32424
32425 It is not our objective to explain how to write a resource file. A
32426 complete description of the resource script language can be found in the
32427 Microsoft documentation.
32428
32429 @node Compiling Resources
32430 @subsection Compiling Resources
32431 @findex rc
32432 @findex windres
32433 @cindex Resources, compiling
32434
32435 @noindent
32436 This section describes how to build a GNAT-compatible (COFF) object file
32437 containing the resources. This is done using the Resource Compiler
32438 @code{windres} as follows:
32439
32440 @smallexample
32441 $ windres -i myres.rc -o myres.o
32442 @end smallexample
32443
32444 @noindent
32445 By default @code{windres} will run @command{gcc} to preprocess the @file{.rc}
32446 file. You can specify an alternate preprocessor (usually named
32447 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
32448 parameter. A list of all possible options may be obtained by entering
32449 the command @code{windres} @option{--help}.
32450
32451 It is also possible to use the Microsoft resource compiler @code{rc.exe}
32452 to produce a @file{.res} file (binary resource file). See the
32453 corresponding Microsoft documentation for further details. In this case
32454 you need to use @code{windres} to translate the @file{.res} file to a
32455 GNAT-compatible object file as follows:
32456
32457 @smallexample
32458 $ windres -i myres.res -o myres.o
32459 @end smallexample
32460
32461 @node Using Resources
32462 @subsection Using Resources
32463 @cindex Resources, using
32464
32465 @noindent
32466 To include the resource file in your program just add the
32467 GNAT-compatible object file for the resource(s) to the linker
32468 arguments. With @command{gnatmake} this is done by using the @option{-largs}
32469 option:
32470
32471 @smallexample
32472 $ gnatmake myprog -largs myres.o
32473 @end smallexample
32474
32475 @node Debugging a DLL
32476 @section Debugging a DLL
32477 @cindex DLL debugging
32478
32479 @menu
32480 * Program and DLL Both Built with GCC/GNAT::
32481 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
32482 @end menu
32483
32484 @noindent
32485 Debugging a DLL is similar to debugging a standard program. But
32486 we have to deal with two different executable parts: the DLL and the
32487 program that uses it. We have the following four possibilities:
32488
32489 @enumerate 1
32490 @item
32491 The program and the DLL are built with @code{GCC/GNAT}.
32492 @item
32493 The program is built with foreign tools and the DLL is built with
32494 @code{GCC/GNAT}.
32495 @item
32496 The program is built with @code{GCC/GNAT} and the DLL is built with
32497 foreign tools.
32498 @item
32499 @end enumerate
32500
32501 @noindent
32502 In this section we address only cases one and two above.
32503 There is no point in trying to debug
32504 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
32505 information in it. To do so you must use a debugger compatible with the
32506 tools suite used to build the DLL.
32507
32508 @node Program and DLL Both Built with GCC/GNAT
32509 @subsection Program and DLL Both Built with GCC/GNAT
32510
32511 @noindent
32512 This is the simplest case. Both the DLL and the program have @code{GDB}
32513 compatible debugging information. It is then possible to break anywhere in
32514 the process. Let's suppose here that the main procedure is named
32515 @code{ada_main} and that in the DLL there is an entry point named
32516 @code{ada_dll}.
32517
32518 @noindent
32519 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
32520 program must have been built with the debugging information (see GNAT -g
32521 switch). Here are the step-by-step instructions for debugging it:
32522
32523 @enumerate 1
32524 @item Launch @code{GDB} on the main program.
32525
32526 @smallexample
32527 $ gdb -nw ada_main
32528 @end smallexample
32529
32530 @item Start the program and stop at the beginning of the main procedure
32531
32532 @smallexample
32533 (gdb) start
32534 @end smallexample
32535
32536 @noindent
32537 This step is required to be able to set a breakpoint inside the DLL. As long
32538 as the program is not run, the DLL is not loaded. This has the
32539 consequence that the DLL debugging information is also not loaded, so it is not
32540 possible to set a breakpoint in the DLL.
32541
32542 @item Set a breakpoint inside the DLL
32543
32544 @smallexample
32545 (gdb) break ada_dll
32546 (gdb) cont
32547 @end smallexample
32548
32549 @end enumerate
32550
32551 @noindent
32552 At this stage a breakpoint is set inside the DLL. From there on
32553 you can use the standard approach to debug the whole program
32554 (@pxref{Running and Debugging Ada Programs}).
32555
32556 @ignore
32557 @c This used to work, probably because the DLLs were non-relocatable
32558 @c keep this section around until the problem is sorted out.
32559
32560 To break on the @code{DllMain} routine it is not possible to follow
32561 the procedure above. At the time the program stop on @code{ada_main}
32562 the @code{DllMain} routine as already been called. Either you can use
32563 the procedure below @pxref{Debugging the DLL Directly} or this procedure:
32564
32565 @enumerate 1
32566 @item Launch @code{GDB} on the main program.
32567
32568 @smallexample
32569 $ gdb ada_main
32570 @end smallexample
32571
32572 @item Load DLL symbols
32573
32574 @smallexample
32575 (gdb) add-sym api.dll
32576 @end smallexample
32577
32578 @item Set a breakpoint inside the DLL
32579
32580 @smallexample
32581 (gdb) break ada_dll.adb:45
32582 @end smallexample
32583
32584 Note that at this point it is not possible to break using the routine symbol
32585 directly as the program is not yet running. The solution is to break
32586 on the proper line (break in @file{ada_dll.adb} line 45).
32587
32588 @item Start the program
32589
32590 @smallexample
32591 (gdb) run
32592 @end smallexample
32593
32594 @end enumerate
32595 @end ignore
32596
32597 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
32598 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
32599
32600 @menu
32601 * Debugging the DLL Directly::
32602 * Attaching to a Running Process::
32603 @end menu
32604
32605 @noindent
32606 In this case things are slightly more complex because it is not possible to
32607 start the main program and then break at the beginning to load the DLL and the
32608 associated DLL debugging information. It is not possible to break at the
32609 beginning of the program because there is no @code{GDB} debugging information,
32610 and therefore there is no direct way of getting initial control. This
32611 section addresses this issue by describing some methods that can be used
32612 to break somewhere in the DLL to debug it.
32613
32614 @noindent
32615 First suppose that the main procedure is named @code{main} (this is for
32616 example some C code built with Microsoft Visual C) and that there is a
32617 DLL named @code{test.dll} containing an Ada entry point named
32618 @code{ada_dll}.
32619
32620 @noindent
32621 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
32622 been built with debugging information (see GNAT -g option).
32623
32624 @node Debugging the DLL Directly
32625 @subsubsection Debugging the DLL Directly
32626
32627 @enumerate 1
32628 @item
32629 Find out the executable starting address
32630
32631 @smallexample
32632 $ objdump --file-header main.exe
32633 @end smallexample
32634
32635 The starting address is reported on the last line. For example:
32636
32637 @smallexample
32638 main.exe:     file format pei-i386
32639 architecture: i386, flags 0x0000010a:
32640 EXEC_P, HAS_DEBUG, D_PAGED
32641 start address 0x00401010
32642 @end smallexample
32643
32644 @item
32645 Launch the debugger on the executable.
32646
32647 @smallexample
32648 $ gdb main.exe
32649 @end smallexample
32650
32651 @item
32652 Set a breakpoint at the starting address, and launch the program.
32653
32654 @smallexample
32655 $ (gdb) break *0x00401010
32656 $ (gdb) run
32657 @end smallexample
32658
32659 The program will stop at the given address.
32660
32661 @item
32662 Set a breakpoint on a DLL subroutine.
32663
32664 @smallexample
32665 (gdb) break ada_dll.adb:45
32666 @end smallexample
32667
32668 Or if you want to break using a symbol on the DLL, you need first to
32669 select the Ada language (language used by the DLL).
32670
32671 @smallexample
32672 (gdb) set language ada
32673 (gdb) break ada_dll
32674 @end smallexample
32675
32676 @item
32677 Continue the program.
32678
32679 @smallexample
32680 (gdb) cont
32681 @end smallexample
32682
32683 @noindent
32684 This will run the program until it reaches the breakpoint that has been
32685 set. From that point you can use the standard way to debug a program
32686 as described in (@pxref{Running and Debugging Ada Programs}).
32687
32688 @end enumerate
32689
32690 @noindent
32691 It is also possible to debug the DLL by attaching to a running process.
32692
32693 @node Attaching to a Running Process
32694 @subsubsection Attaching to a Running Process
32695 @cindex DLL debugging, attach to process
32696
32697 @noindent
32698 With @code{GDB} it is always possible to debug a running process by
32699 attaching to it. It is possible to debug a DLL this way. The limitation
32700 of this approach is that the DLL must run long enough to perform the
32701 attach operation. It may be useful for instance to insert a time wasting
32702 loop in the code of the DLL to meet this criterion.
32703
32704 @enumerate 1
32705
32706 @item Launch the main program @file{main.exe}.
32707
32708 @smallexample
32709 $ main
32710 @end smallexample
32711
32712 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
32713 that the process PID for @file{main.exe} is 208.
32714
32715 @item Launch gdb.
32716
32717 @smallexample
32718 $ gdb
32719 @end smallexample
32720
32721 @item Attach to the running process to be debugged.
32722
32723 @smallexample
32724 (gdb) attach 208
32725 @end smallexample
32726
32727 @item Load the process debugging information.
32728
32729 @smallexample
32730 (gdb) symbol-file main.exe
32731 @end smallexample
32732
32733 @item Break somewhere in the DLL.
32734
32735 @smallexample
32736 (gdb) break ada_dll
32737 @end smallexample
32738
32739 @item Continue process execution.
32740
32741 @smallexample
32742 (gdb) cont
32743 @end smallexample
32744
32745 @end enumerate
32746
32747 @noindent
32748 This last step will resume the process execution, and stop at
32749 the breakpoint we have set. From there you can use the standard
32750 approach to debug a program as described in
32751 (@pxref{Running and Debugging Ada Programs}).
32752
32753 @node Setting Stack Size from gnatlink
32754 @section Setting Stack Size from @command{gnatlink}
32755
32756 @noindent
32757 It is possible to specify the program stack size at link time. On modern
32758 versions of Windows, starting with XP, this is mostly useful to set the size of
32759 the main stack (environment task). The other task stacks are set with pragma
32760 Storage_Size or with the @command{gnatbind -d} command.
32761
32762 Since older versions of Windows (2000, NT4, etc.) do not allow setting the
32763 reserve size of individual tasks, the link-time stack size applies to all
32764 tasks, and pragma Storage_Size has no effect.
32765 In particular, Stack Overflow checks are made against this
32766 link-time specified size.
32767
32768 This setting can be done with
32769 @command{gnatlink} using either:
32770
32771 @itemize @bullet
32772
32773 @item using @option{-Xlinker} linker option
32774
32775 @smallexample
32776 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
32777 @end smallexample
32778
32779 This sets the stack reserve size to 0x10000 bytes and the stack commit
32780 size to 0x1000 bytes.
32781
32782 @item using @option{-Wl} linker option
32783
32784 @smallexample
32785 $ gnatlink hello -Wl,--stack=0x1000000
32786 @end smallexample
32787
32788 This sets the stack reserve size to 0x1000000 bytes. Note that with
32789 @option{-Wl} option it is not possible to set the stack commit size
32790 because the coma is a separator for this option.
32791
32792 @end itemize
32793
32794 @node Setting Heap Size from gnatlink
32795 @section Setting Heap Size from @command{gnatlink}
32796
32797 @noindent
32798 Under Windows systems, it is possible to specify the program heap size from
32799 @command{gnatlink} using either:
32800
32801 @itemize @bullet
32802
32803 @item using @option{-Xlinker} linker option
32804
32805 @smallexample
32806 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
32807 @end smallexample
32808
32809 This sets the heap reserve size to 0x10000 bytes and the heap commit
32810 size to 0x1000 bytes.
32811
32812 @item using @option{-Wl} linker option
32813
32814 @smallexample
32815 $ gnatlink hello -Wl,--heap=0x1000000
32816 @end smallexample
32817
32818 This sets the heap reserve size to 0x1000000 bytes. Note that with
32819 @option{-Wl} option it is not possible to set the heap commit size
32820 because the coma is a separator for this option.
32821
32822 @end itemize
32823
32824 @end ifset
32825
32826 @c **********************************
32827 @c * GNU Free Documentation License *
32828 @c **********************************
32829 @include fdl.texi
32830 @c GNU Free Documentation License
32831
32832 @node Index,,GNU Free Documentation License, Top
32833 @unnumbered Index
32834
32835 @printindex cp
32836
32837 @contents
32838 @c Put table of contents at end, otherwise it precedes the "title page" in
32839 @c the .txt version
32840 @c Edit the pdf file to move the contents to the beginning, after the title
32841 @c page
32842
32843 @bye