OSDN Git Service

2010-05-16 Manuel López-Ibáñez <manu@gcc.gnu.org>
[pf3gnuchains/gcc-fork.git] / gcc / ada / gnat_ugn.texi
1 \input texinfo   @c -*-texinfo-*-
2 @c %**start of header
3
4 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
5 @c                                                                            o
6 @c                            GNAT DOCUMENTATION                              o
7 @c                                                                            o
8 @c                             G N A T _ U G N                                o
9 @c                                                                            o
10 @c   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-2009 Free Software Foundation,
18 Inc.
19
20 Permission is granted to copy, distribute and/or modify this document
21 under the terms of the GNU Free Documentation License, Version 1.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 * Switches for gnatxref::
394 * Switches for gnatfind::
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 * Rule exemption::
494 * Predefined Rules::
495 * Example of gnatcheck Usage::
496
497 Sample Bodies Using gnatstub
498
499 * Running gnatstub::
500 * Switches for gnatstub::
501
502 Other Utility Programs
503
504 * Using Other Utility Programs with GNAT::
505 * The External Symbol Naming Scheme of GNAT::
506 * Converting Ada Files to html with gnathtml::
507
508 @ifclear vms
509 Code Coverage and Profiling
510
511 * Code Coverage of Ada Programs using gcov::
512 * Profiling an Ada Program using gprof::
513 @end ifclear
514
515 Running and Debugging Ada Programs
516
517 * The GNAT Debugger GDB::
518 * Running GDB::
519 * Introduction to GDB Commands::
520 * Using Ada Expressions::
521 * Calling User-Defined Subprograms::
522 * Using the Next Command in a Function::
523 * Ada Exceptions::
524 * Ada Tasks::
525 * Debugging Generic Units::
526 * GNAT Abnormal Termination or Failure to Terminate::
527 * Naming Conventions for GNAT Source Files::
528 * Getting Internal Debugging Information::
529 * Stack Traceback::
530
531 @ifset vms
532 * LSE::
533 @end ifset
534
535 @ifset vms
536 Compatibility with HP Ada
537
538 * Ada Language Compatibility::
539 * Differences in the Definition of Package System::
540 * Language-Related Features::
541 * The Package STANDARD::
542 * The Package SYSTEM::
543 * Tasking and Task-Related Features::
544 * Pragmas and Pragma-Related Features::
545 * Library of Predefined Units::
546 * Bindings::
547 * Main Program Definition::
548 * Implementation-Defined Attributes::
549 * Compiler and Run-Time Interfacing::
550 * Program Compilation and Library Management::
551 * Input-Output::
552 * Implementation Limits::
553 * Tools and Utilities::
554
555 Language-Related Features
556
557 * Integer Types and Representations::
558 * Floating-Point Types and Representations::
559 * Pragmas Float_Representation and Long_Float::
560 * Fixed-Point Types and Representations::
561 * Record and Array Component Alignment::
562 * Address Clauses::
563 * Other Representation Clauses::
564
565 Tasking and Task-Related Features
566
567 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
568 * Assigning Task IDs::
569 * Task IDs and Delays::
570 * Task-Related Pragmas::
571 * Scheduling and Task Priority::
572 * The Task Stack::
573 * External Interrupts::
574
575 Pragmas and Pragma-Related Features
576
577 * Restrictions on the Pragma INLINE::
578 * Restrictions on the Pragma INTERFACE::
579 * Restrictions on the Pragma SYSTEM_NAME::
580
581 Library of Predefined Units
582
583 * Changes to DECLIB::
584
585 Bindings
586
587 * Shared Libraries and Options Files::
588 * Interfaces to C::
589 @end ifset
590
591 Platform-Specific Information for the Run-Time Libraries
592
593 * Summary of Run-Time Configurations::
594 * Specifying a Run-Time Library::
595 * Choosing the Scheduling Policy::
596 * Solaris-Specific Considerations::
597 * Linux-Specific Considerations::
598 * AIX-Specific Considerations::
599 * Irix-Specific Considerations::
600
601 Example of Binder Output File
602
603 Elaboration Order Handling in GNAT
604
605 * Elaboration Code::
606 * Checking the Elaboration Order::
607 * Controlling the Elaboration Order::
608 * Controlling Elaboration in GNAT - Internal Calls::
609 * Controlling Elaboration in GNAT - External Calls::
610 * Default Behavior in GNAT - Ensuring Safety::
611 * Treatment of Pragma Elaborate::
612 * Elaboration Issues for Library Tasks::
613 * Mixing Elaboration Models::
614 * What to Do If the Default Elaboration Behavior Fails::
615 * Elaboration for Access-to-Subprogram Values::
616 * Summary of Procedures for Elaboration Control::
617 * Other Elaboration Order Considerations::
618
619 Conditional Compilation
620 * Use of Boolean Constants::
621 * Debugging - A Special Case::
622 * Conditionalizing Declarations::
623 * Use of Alternative Implementations::
624 * Preprocessing::
625
626 Inline Assembler
627
628 * Basic Assembler Syntax::
629 * A Simple Example of Inline Assembler::
630 * Output Variables in Inline Assembler::
631 * Input Variables in Inline Assembler::
632 * Inlining Inline Assembler Code::
633 * Other Asm Functionality::
634
635 Compatibility and Porting Guide
636
637 * Compatibility with Ada 83::
638 * Compatibility between Ada 95 and Ada 2005::
639 * Implementation-dependent characteristics::
640 @ifclear vms
641 @c This brief section is only in the non-VMS version
642 @c The complete chapter on HP Ada issues is in the VMS version
643 * Compatibility with HP Ada 83::
644 @end ifclear
645 * Compatibility with Other Ada Systems::
646 * Representation Clauses::
647 @ifset vms
648 * Transitioning to 64-Bit GNAT for OpenVMS::
649 @end ifset
650
651 @ifset unw
652 Microsoft Windows Topics
653
654 * Using GNAT on Windows::
655 * CONSOLE and WINDOWS subsystems::
656 * Temporary Files::
657 * Mixed-Language Programming on Windows::
658 * Windows Calling Conventions::
659 * Introduction to Dynamic Link Libraries (DLLs)::
660 * Using DLLs with GNAT::
661 * Building DLLs with GNAT::
662 * GNAT and Windows Resources::
663 * Debugging a DLL::
664 * Setting Stack Size from gnatlink::
665 * Setting Heap Size from gnatlink::
666 @end ifset
667
668 * Index::
669 @end menu
670 @end ifnottex
671
672 @node About This Guide
673 @unnumbered About This Guide
674
675 @noindent
676 @ifset vms
677 This guide describes the use of @value{EDITION},
678 a compiler and software development toolset for the full Ada
679 programming language, implemented on OpenVMS for HP's Alpha and
680 Integrity server (I64) platforms.
681 @end ifset
682 @ifclear vms
683 This guide describes the use of @value{EDITION},
684 a compiler and software development
685 toolset for the full Ada programming language.
686 @end ifclear
687 It documents the features of the compiler and tools, and explains
688 how to use them to build Ada applications.
689
690 @value{EDITION} implements Ada 95 and Ada 2005, and it may also be invoked in
691 Ada 83 compatibility mode.
692 By default, @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION},
693 but you can override with a compiler switch
694 (@pxref{Compiling Different Versions of Ada})
695 to explicitly specify the language version.
696 Throughout this manual, references to ``Ada'' without a year suffix
697 apply to both the Ada 95 and Ada 2005 versions of the language.
698
699
700 @ifclear FSFEDITION
701 For ease of exposition, ``@value{EDITION}'' will be referred to simply as
702 ``GNAT'' in the remainder of this document.
703 @end ifclear
704
705
706
707
708 @menu
709 * What This Guide Contains::
710 * What You Should Know before Reading This Guide::
711 * Related Information::
712 * Conventions::
713 @end menu
714
715 @node What This Guide Contains
716 @unnumberedsec What This Guide Contains
717
718 @noindent
719 This guide contains the following chapters:
720 @itemize @bullet
721
722 @item
723 @ref{Getting Started with GNAT}, describes how to get started compiling
724 and running Ada programs with the GNAT Ada programming environment.
725 @item
726 @ref{The GNAT Compilation Model}, describes the compilation model used
727 by GNAT.
728
729 @item
730 @ref{Compiling Using gcc}, describes how to compile
731 Ada programs with @command{gcc}, the Ada compiler.
732
733 @item
734 @ref{Binding Using gnatbind}, describes how to
735 perform binding of Ada programs with @code{gnatbind}, the GNAT binding
736 utility.
737
738 @item
739 @ref{Linking Using gnatlink},
740 describes @command{gnatlink}, a
741 program that provides for linking using the GNAT run-time library to
742 construct a program. @command{gnatlink} can also incorporate foreign language
743 object units into the executable.
744
745 @item
746 @ref{The GNAT Make Program gnatmake}, describes @command{gnatmake}, a
747 utility that automatically determines the set of sources
748 needed by an Ada compilation unit, and executes the necessary compilations
749 binding and link.
750
751 @item
752 @ref{Improving Performance}, shows various techniques for making your
753 Ada program run faster or take less space.
754 It discusses the effect of the compiler's optimization switch and
755 also describes the @command{gnatelim} tool and unused subprogram/data
756 elimination.
757
758 @item
759 @ref{Renaming Files Using gnatchop}, describes
760 @code{gnatchop}, a utility that allows you to preprocess a file that
761 contains Ada source code, and split it into one or more new files, one
762 for each compilation unit.
763
764 @item
765 @ref{Configuration Pragmas}, describes the configuration pragmas
766 handled by GNAT.
767
768 @item
769 @ref{Handling Arbitrary File Naming Conventions Using gnatname},
770 shows how to override the default GNAT file naming conventions,
771 either for an individual unit or globally.
772
773 @item
774 @ref{GNAT Project Manager}, describes how to use project files
775 to organize large projects.
776
777 @item
778 @ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses
779 @code{gnatxref} and @code{gnatfind}, two tools that provide an easy
780 way to navigate through sources.
781
782 @item
783 @ref{The GNAT Pretty-Printer gnatpp}, shows how to produce a reformatted
784 version of an Ada source file with control over casing, indentation,
785 comment placement, and other elements of program presentation style.
786
787 @item
788 @ref{The GNAT Metric Tool gnatmetric}, shows how to compute various
789 metrics for an Ada source file, such as the number of types and subprograms,
790 and assorted complexity measures.
791
792 @item
793 @ref{File Name Krunching Using gnatkr}, describes the @code{gnatkr}
794 file name krunching utility, used to handle shortened
795 file names on operating systems with a limit on the length of names.
796
797 @item
798 @ref{Preprocessing Using gnatprep}, describes @code{gnatprep}, a
799 preprocessor utility that allows a single source file to be used to
800 generate multiple or parameterized source files by means of macro
801 substitution.
802
803 @ifset vms
804 @item
805 @ref{The GNAT Run-Time Library Builder gnatlbr}, describes @command{gnatlbr},
806 a tool for rebuilding the GNAT run time with user-supplied
807 configuration pragmas.
808 @end ifset
809
810 @item
811 @ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a
812 utility that displays information about compiled units, including dependences
813 on the corresponding sources files, and consistency of compilations.
814
815 @item
816 @ref{Cleaning Up Using gnatclean}, describes @code{gnatclean}, a utility
817 to delete files that are produced by the compiler, binder and linker.
818
819 @ifclear vms
820 @item
821 @ref{GNAT and Libraries}, describes the process of creating and using
822 Libraries with GNAT. It also describes how to recompile the GNAT run-time
823 library.
824
825 @item
826 @ref{Using the GNU make Utility}, describes some techniques for using
827 the GNAT toolset in Makefiles.
828 @end ifclear
829
830 @item
831 @ref{Memory Management Issues}, describes some useful predefined storage pools
832 and in particular the GNAT Debug Pool facility, which helps detect incorrect
833 memory references.
834 @ifclear vms
835 It also describes @command{gnatmem}, a utility that monitors dynamic
836 allocation and deallocation and helps detect ``memory leaks''.
837 @end ifclear
838
839 @item
840 @ref{Stack Related Facilities}, describes some useful tools associated with
841 stack checking and analysis.
842
843 @item
844 @ref{Verifying Properties Using gnatcheck}, discusses @code{gnatcheck},
845 a utility that checks Ada code against a set of rules.
846
847 @item
848 @ref{Creating Sample Bodies Using gnatstub}, discusses @code{gnatstub},
849 a utility that generates empty but compilable bodies for library units.
850
851 @item
852 @ref{Generating Ada Bindings for C and C++ headers}, describes how to
853 generate automatically Ada bindings from C and C++ headers.
854
855 @item
856 @ref{Other Utility Programs}, discusses several other GNAT utilities,
857 including @code{gnathtml}.
858
859 @ifclear vms
860 @item
861 @ref{Code Coverage and Profiling}, describes how to perform a structural
862 coverage and profile the execution of Ada programs.
863 @end ifclear
864
865 @item
866 @ref{Running and Debugging Ada Programs}, describes how to run and debug
867 Ada programs.
868
869 @ifset vms
870 @item
871 @ref{Compatibility with HP Ada}, details the compatibility of GNAT with
872 HP Ada 83 @footnote{``HP Ada'' refers to the legacy product originally
873 developed by Digital Equipment Corporation and currently supported by HP.}
874 for OpenVMS Alpha. This product was formerly known as DEC Ada,
875 @cindex DEC Ada
876 and for
877 historical compatibility reasons, the relevant libraries still use the
878 DEC prefix.
879 @end ifset
880
881 @item
882 @ref{Platform-Specific Information for the Run-Time Libraries},
883 describes the various run-time
884 libraries supported by GNAT on various platforms and explains how to
885 choose a particular library.
886
887 @item
888 @ref{Example of Binder Output File}, shows the source code for the binder
889 output file for a sample program.
890
891 @item
892 @ref{Elaboration Order Handling in GNAT}, describes how GNAT helps
893 you deal with elaboration order issues.
894
895 @item
896 @ref{Conditional Compilation}, describes how to model conditional compilation,
897 both with Ada in general and with GNAT facilities in particular.
898
899 @item
900 @ref{Inline Assembler}, shows how to use the inline assembly facility
901 in an Ada program.
902
903 @item
904 @ref{Compatibility and Porting Guide}, contains sections on compatibility
905 of GNAT with other Ada development environments (including Ada 83 systems),
906 to assist in porting code from those environments.
907
908 @ifset unw
909 @item
910 @ref{Microsoft Windows Topics}, presents information relevant to the
911 Microsoft Windows platform.
912 @end ifset
913 @end itemize
914
915 @c *************************************************
916 @node What You Should Know before Reading This Guide
917 @c *************************************************
918 @unnumberedsec What You Should Know before Reading This Guide
919
920 @cindex Ada 95 Language Reference Manual
921 @cindex Ada 2005 Language Reference Manual
922 @noindent
923 This guide assumes a basic familiarity with the Ada 95 language, as
924 described in the International Standard ANSI/ISO/IEC-8652:1995, January
925 1995.
926 It does not require knowledge of the new features introduced by Ada 2005,
927 (officially known as ISO/IEC 8652:1995 with Technical Corrigendum 1
928 and Amendment 1).
929 Both reference manuals are included in the GNAT documentation
930 package.
931
932 @node Related Information
933 @unnumberedsec Related Information
934
935 @noindent
936 For further information about related tools, refer to the following
937 documents:
938
939 @itemize @bullet
940 @item
941 @xref{Top, GNAT Reference Manual, About This Guide, gnat_rm, GNAT
942 Reference Manual}, which contains all reference material for the GNAT
943 implementation of Ada.
944
945 @ifset unw
946 @item
947 @cite{Using the GNAT Programming Studio}, which describes the GPS
948 Integrated Development Environment.
949
950 @item
951 @cite{GNAT Programming Studio Tutorial}, which introduces the
952 main GPS features through examples.
953 @end ifset
954
955 @item
956 @cite{Ada 95 Reference Manual}, which contains reference
957 material for the Ada 95 programming language.
958
959 @item
960 @cite{Ada 2005 Reference Manual}, which contains reference
961 material for the Ada 2005 programming language.
962
963 @item
964 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
965 @ifset vms
966 in the GNU:[DOCS] directory,
967 @end ifset
968 for all details on the use of the GNU source-level debugger.
969
970 @item
971 @xref{Top,, The extensible self-documenting text editor, emacs,
972 GNU Emacs Manual},
973 @ifset vms
974 located in the GNU:[DOCS] directory if the EMACS kit is installed,
975 @end ifset
976 for full information on the extensible editor and programming
977 environment Emacs.
978
979 @end itemize
980
981 @c **************
982 @node Conventions
983 @unnumberedsec Conventions
984 @cindex Conventions
985 @cindex Typographical conventions
986
987 @noindent
988 Following are examples of the typographical and graphic conventions used
989 in this guide:
990
991 @itemize @bullet
992 @item
993 @code{Functions}, @command{utility program names}, @code{standard names},
994 and @code{classes}.
995
996 @item
997 @option{Option flags}
998
999 @item
1000 @file{File names}, @samp{button names}, and @samp{field names}.
1001
1002 @item
1003 @code{Variables}, @env{environment variables}, and @var{metasyntactic
1004 variables}.
1005
1006 @item
1007 @emph{Emphasis}.
1008
1009 @item
1010 @r{[}optional information or parameters@r{]}
1011
1012 @item
1013 Examples are described by text
1014 @smallexample
1015 and then shown this way.
1016 @end smallexample
1017 @end itemize
1018
1019 @noindent
1020 Commands that are entered by the user are preceded in this manual by the
1021 characters @w{``@code{$ }''} (dollar sign followed by space). If your system
1022 uses this sequence as a prompt, then the commands will appear exactly as
1023 you see them in the manual. If your system uses some other prompt, then
1024 the command will appear with the @code{$} replaced by whatever prompt
1025 character you are using.
1026
1027 @ifset unw
1028 Full file names are shown with the ``@code{/}'' character
1029 as the directory separator; e.g., @file{parent-dir/subdir/myfile.adb}.
1030 If you are using GNAT on a Windows platform, please note that
1031 the ``@code{\}'' character should be used instead.
1032 @end ifset
1033
1034 @c ****************************
1035 @node Getting Started with GNAT
1036 @chapter Getting Started with GNAT
1037
1038 @noindent
1039 This chapter describes some simple ways of using GNAT to build
1040 executable Ada programs.
1041 @ifset unw
1042 @ref{Running GNAT}, through @ref{Using the gnatmake Utility},
1043 show how to use the command line environment.
1044 @ref{Introduction to GPS}, provides a brief
1045 introduction to the GNAT Programming Studio, a visually-oriented
1046 Integrated Development Environment for GNAT.
1047 GPS offers a graphical ``look and feel'', support for development in
1048 other programming languages, comprehensive browsing features, and
1049 many other capabilities.
1050 For information on GPS please refer to
1051 @cite{Using the GNAT Programming Studio}.
1052 @end ifset
1053
1054 @menu
1055 * Running GNAT::
1056 * Running a Simple Ada Program::
1057 * Running a Program with Multiple Units::
1058 * Using the gnatmake Utility::
1059 @ifset vms
1060 * Editing with Emacs::
1061 @end ifset
1062 @ifclear vms
1063 * Introduction to GPS::
1064 @end ifclear
1065 @end menu
1066
1067 @node Running GNAT
1068 @section Running GNAT
1069
1070 @noindent
1071 Three steps are needed to create an executable file from an Ada source
1072 file:
1073
1074 @enumerate
1075 @item
1076 The source file(s) must be compiled.
1077 @item
1078 The file(s) must be bound using the GNAT binder.
1079 @item
1080 All appropriate object files must be linked to produce an executable.
1081 @end enumerate
1082
1083 @noindent
1084 All three steps are most commonly handled by using the @command{gnatmake}
1085 utility program that, given the name of the main program, automatically
1086 performs the necessary compilation, binding and linking steps.
1087
1088 @node Running a Simple Ada Program
1089 @section Running a Simple Ada Program
1090
1091 @noindent
1092 Any text editor may be used to prepare an Ada program.
1093 (If @code{Emacs} is
1094 used, the optional Ada mode may be helpful in laying out the program.)
1095 The
1096 program text is a normal text file. We will assume in our initial
1097 example that you have used your editor to prepare the following
1098 standard format text file:
1099
1100 @smallexample @c ada
1101 @cartouche
1102 with Ada.Text_IO; use Ada.Text_IO;
1103 procedure Hello is
1104 begin
1105    Put_Line ("Hello WORLD!");
1106 end Hello;
1107 @end cartouche
1108 @end smallexample
1109
1110 @noindent
1111 This file should be named @file{hello.adb}.
1112 With the normal default file naming conventions, GNAT requires
1113 that each file
1114 contain a single compilation unit whose file name is the
1115 unit name,
1116 with periods replaced by hyphens; the
1117 extension is @file{ads} for a
1118 spec and @file{adb} for a body.
1119 You can override this default file naming convention by use of the
1120 special pragma @code{Source_File_Name} (@pxref{Using Other File Names}).
1121 Alternatively, if you want to rename your files according to this default
1122 convention, which is probably more convenient if you will be using GNAT
1123 for all your compilations, then the @code{gnatchop} utility
1124 can be used to generate correctly-named source files
1125 (@pxref{Renaming Files Using gnatchop}).
1126
1127 You can compile the program using the following command (@code{$} is used
1128 as the command prompt in the examples in this document):
1129
1130 @smallexample
1131 $ gcc -c hello.adb
1132 @end smallexample
1133
1134 @noindent
1135 @command{gcc} is the command used to run the compiler. This compiler is
1136 capable of compiling programs in several languages, including Ada and
1137 C. It assumes that you have given it an Ada program if the file extension is
1138 either @file{.ads} or @file{.adb}, and it will then call
1139 the GNAT compiler to compile the specified file.
1140
1141 @ifclear vms
1142 The @option{-c} switch is required. It tells @command{gcc} to only do a
1143 compilation. (For C programs, @command{gcc} can also do linking, but this
1144 capability is not used directly for Ada programs, so the @option{-c}
1145 switch must always be present.)
1146 @end ifclear
1147
1148 This compile command generates a file
1149 @file{hello.o}, which is the object
1150 file corresponding to your Ada program. It also generates
1151 an ``Ada Library Information'' file @file{hello.ali},
1152 which contains additional information used to check
1153 that an Ada program is consistent.
1154 To build an executable file,
1155 use @code{gnatbind} to bind the program
1156 and @command{gnatlink} to link it. The
1157 argument to both @code{gnatbind} and @command{gnatlink} is the name of the
1158 @file{ALI} file, but the default extension of @file{.ali} can
1159 be omitted. This means that in the most common case, the argument
1160 is simply the name of the main program:
1161
1162 @smallexample
1163 $ gnatbind hello
1164 $ gnatlink hello
1165 @end smallexample
1166
1167 @noindent
1168 A simpler method of carrying out these steps is to use
1169 @command{gnatmake},
1170 a master program that invokes all the required
1171 compilation, binding and linking tools in the correct order. In particular,
1172 @command{gnatmake} automatically recompiles any sources that have been
1173 modified since they were last compiled, or sources that depend
1174 on such modified sources, so that ``version skew'' is avoided.
1175 @cindex Version skew (avoided by @command{gnatmake})
1176
1177 @smallexample
1178 $ gnatmake hello.adb
1179 @end smallexample
1180
1181 @noindent
1182 The result is an executable program called @file{hello}, which can be
1183 run by entering:
1184
1185 @smallexample
1186 $ ^hello^RUN HELLO^
1187 @end smallexample
1188
1189 @noindent
1190 assuming that the current directory is on the search path
1191 for executable programs.
1192
1193 @noindent
1194 and, if all has gone well, you will see
1195
1196 @smallexample
1197 Hello WORLD!
1198 @end smallexample
1199
1200 @noindent
1201 appear in response to this command.
1202
1203 @c ****************************************
1204 @node Running a Program with Multiple Units
1205 @section Running a Program with Multiple Units
1206
1207 @noindent
1208 Consider a slightly more complicated example that has three files: a
1209 main program, and the spec and body of a package:
1210
1211 @smallexample @c ada
1212 @cartouche
1213 @group
1214 package Greetings is
1215    procedure Hello;
1216    procedure Goodbye;
1217 end Greetings;
1218
1219 with Ada.Text_IO; use Ada.Text_IO;
1220 package body Greetings is
1221    procedure Hello is
1222    begin
1223       Put_Line ("Hello WORLD!");
1224    end Hello;
1225
1226    procedure Goodbye is
1227    begin
1228       Put_Line ("Goodbye WORLD!");
1229    end Goodbye;
1230 end Greetings;
1231 @end group
1232
1233 @group
1234 with Greetings;
1235 procedure Gmain is
1236 begin
1237    Greetings.Hello;
1238    Greetings.Goodbye;
1239 end Gmain;
1240 @end group
1241 @end cartouche
1242 @end smallexample
1243
1244 @noindent
1245 Following the one-unit-per-file rule, place this program in the
1246 following three separate files:
1247
1248 @table @file
1249 @item greetings.ads
1250 spec of package @code{Greetings}
1251
1252 @item greetings.adb
1253 body of package @code{Greetings}
1254
1255 @item gmain.adb
1256 body of main program
1257 @end table
1258
1259 @noindent
1260 To build an executable version of
1261 this program, we could use four separate steps to compile, bind, and link
1262 the program, as follows:
1263
1264 @smallexample
1265 $ gcc -c gmain.adb
1266 $ gcc -c greetings.adb
1267 $ gnatbind gmain
1268 $ gnatlink gmain
1269 @end smallexample
1270
1271 @noindent
1272 Note that there is no required order of compilation when using GNAT.
1273 In particular it is perfectly fine to compile the main program first.
1274 Also, it is not necessary to compile package specs in the case where
1275 there is an accompanying body; you only need to compile the body. If you want
1276 to submit these files to the compiler for semantic checking and not code
1277 generation, then use the
1278 @option{-gnatc} switch:
1279
1280 @smallexample
1281 $ gcc -c greetings.ads -gnatc
1282 @end smallexample
1283
1284 @noindent
1285 Although the compilation can be done in separate steps as in the
1286 above example, in practice it is almost always more convenient
1287 to use the @command{gnatmake} tool. All you need to know in this case
1288 is the name of the main program's source file. The effect of the above four
1289 commands can be achieved with a single one:
1290
1291 @smallexample
1292 $ gnatmake gmain.adb
1293 @end smallexample
1294
1295 @noindent
1296 In the next section we discuss the advantages of using @command{gnatmake} in
1297 more detail.
1298
1299 @c *****************************
1300 @node Using the gnatmake Utility
1301 @section Using the @command{gnatmake} Utility
1302
1303 @noindent
1304 If you work on a program by compiling single components at a time using
1305 @command{gcc}, you typically keep track of the units you modify. In order to
1306 build a consistent system, you compile not only these units, but also any
1307 units that depend on the units you have modified.
1308 For example, in the preceding case,
1309 if you edit @file{gmain.adb}, you only need to recompile that file. But if
1310 you edit @file{greetings.ads}, you must recompile both
1311 @file{greetings.adb} and @file{gmain.adb}, because both files contain
1312 units that depend on @file{greetings.ads}.
1313
1314 @code{gnatbind} will warn you if you forget one of these compilation
1315 steps, so that it is impossible to generate an inconsistent program as a
1316 result of forgetting to do a compilation. Nevertheless it is tedious and
1317 error-prone to keep track of dependencies among units.
1318 One approach to handle the dependency-bookkeeping is to use a
1319 makefile. However, makefiles present maintenance problems of their own:
1320 if the dependencies change as you change the program, you must make
1321 sure that the makefile is kept up-to-date manually, which is also an
1322 error-prone process.
1323
1324 The @command{gnatmake} utility takes care of these details automatically.
1325 Invoke it using either one of the following forms:
1326
1327 @smallexample
1328 $ gnatmake gmain.adb
1329 $ gnatmake ^gmain^GMAIN^
1330 @end smallexample
1331
1332 @noindent
1333 The argument is the name of the file containing the main program;
1334 you may omit the extension. @command{gnatmake}
1335 examines the environment, automatically recompiles any files that need
1336 recompiling, and binds and links the resulting set of object files,
1337 generating the executable file, @file{^gmain^GMAIN.EXE^}.
1338 In a large program, it
1339 can be extremely helpful to use @command{gnatmake}, because working out by hand
1340 what needs to be recompiled can be difficult.
1341
1342 Note that @command{gnatmake}
1343 takes into account all the Ada rules that
1344 establish dependencies among units. These include dependencies that result
1345 from inlining subprogram bodies, and from
1346 generic instantiation. Unlike some other
1347 Ada make tools, @command{gnatmake} does not rely on the dependencies that were
1348 found by the compiler on a previous compilation, which may possibly
1349 be wrong when sources change. @command{gnatmake} determines the exact set of
1350 dependencies from scratch each time it is run.
1351
1352 @ifset vms
1353 @node Editing with Emacs
1354 @section Editing with Emacs
1355 @cindex Emacs
1356
1357 @noindent
1358 Emacs is an extensible self-documenting text editor that is available in a
1359 separate VMSINSTAL kit.
1360
1361 Invoke Emacs by typing @kbd{Emacs} at the command prompt. To get started,
1362 click on the Emacs Help menu and run the Emacs Tutorial.
1363 In a character cell terminal, Emacs help is invoked with @kbd{Ctrl-h} (also
1364 written as @kbd{C-h}), and the tutorial by @kbd{C-h t}.
1365
1366 Documentation on Emacs and other tools is available in Emacs under the
1367 pull-down menu button: @code{Help - Info}. After selecting @code{Info},
1368 use the middle mouse button to select a topic (e.g.@: Emacs).
1369
1370 In a character cell terminal, do @kbd{C-h i} to invoke info, and then @kbd{m}
1371 (stands for menu) followed by the menu item desired, as in @kbd{m Emacs}, to
1372 get to the Emacs manual.
1373 Help on Emacs is also available by typing @kbd{HELP EMACS} at the DCL command
1374 prompt.
1375
1376 The tutorial is highly recommended in order to learn the intricacies of Emacs,
1377 which is sufficiently extensible to provide for a complete programming
1378 environment and shell for the sophisticated user.
1379 @end ifset
1380
1381 @ifclear vms
1382 @node Introduction to GPS
1383 @section Introduction to GPS
1384 @cindex GPS (GNAT Programming Studio)
1385 @cindex GNAT Programming Studio (GPS)
1386 @noindent
1387 Although the command line interface (@command{gnatmake}, etc.) alone
1388 is sufficient, a graphical Interactive Development
1389 Environment can make it easier for you to compose, navigate, and debug
1390 programs.  This section describes the main features of GPS
1391 (``GNAT Programming Studio''), the GNAT graphical IDE.
1392 You will see how to use GPS to build and debug an executable, and
1393 you will also learn some of the basics of the GNAT ``project'' facility.
1394
1395 GPS enables you to do much more than is presented here;
1396 e.g., you can produce a call graph, interface to a third-party
1397 Version Control System, and inspect the generated assembly language
1398 for a program.
1399 Indeed, GPS also supports languages other than Ada.
1400 Such additional information, and an explanation of all of the GPS menu
1401 items. may be found in the on-line help, which includes
1402 a user's guide and a tutorial (these are also accessible from the GNAT
1403 startup menu).
1404
1405 @menu
1406 * Building a New Program with GPS::
1407 * Simple Debugging with GPS::
1408 @end menu
1409
1410 @node Building a New Program with GPS
1411 @subsection Building a New Program with GPS
1412 @noindent
1413 GPS invokes the GNAT compilation tools using information
1414 contained in a @emph{project} (also known as a @emph{project file}):
1415 a collection of properties such
1416 as source directories, identities of main subprograms, tool switches, etc.,
1417 and their associated values.
1418 See @ref{GNAT Project Manager} for details.
1419 In order to run GPS, you will need to either create a new project
1420 or else open an existing one.
1421
1422 This section will explain how you can use GPS to create a project,
1423 to associate Ada source files with a project, and to build and run
1424 programs.
1425
1426 @enumerate
1427 @item @emph{Creating a project}
1428
1429 Invoke GPS, either from the command line or the platform's IDE.
1430 After it starts, GPS will display a ``Welcome'' screen with three
1431 radio buttons:
1432
1433 @itemize @bullet
1434 @item
1435 @code{Start with default project in directory}
1436
1437 @item
1438 @code{Create new project with wizard}
1439
1440 @item
1441 @code{Open existing project}
1442 @end itemize
1443
1444 @noindent
1445 Select @code{Create new project with wizard} and press @code{OK}.
1446 A new window will appear.  In the text box labeled with
1447 @code{Enter the name of the project to create}, type @file{sample}
1448 as the project name.
1449 In the next box, browse to choose the directory in which you
1450 would like to create the project file.
1451 After selecting an appropriate directory, press @code{Forward}.
1452
1453 A window will appear with the title
1454 @code{Version Control System Configuration}.
1455 Simply press @code{Forward}.
1456
1457 A window will appear with the title
1458 @code{Please select the source directories for this project}.
1459 The directory that you specified for the project file will be selected
1460 by default as the one to use for sources; simply press @code{Forward}.
1461
1462 A window will appear with the title
1463 @code{Please select the build directory for this project}.
1464 The directory that you specified for the project file will be selected
1465 by default for object files and executables;
1466 simply press @code{Forward}.
1467
1468 A window will appear with the title
1469 @code{Please select the main units for this project}.
1470 You will supply this information later, after creating the source file.
1471 Simply press @code{Forward} for now.
1472
1473 A window will appear with the title
1474 @code{Please select the switches to build the project}.
1475 Press @code{Apply}.  This will create a project file named
1476 @file{sample.prj} in the directory that you had specified.
1477
1478 @item @emph{Creating and saving the source file}
1479
1480 After you create the new project, a GPS window will appear, which is
1481 partitioned into two main sections:
1482
1483 @itemize @bullet
1484 @item
1485 A @emph{Workspace area}, initially greyed out, which you will use for
1486 creating and editing source files
1487
1488 @item
1489 Directly below, a @emph{Messages area}, which initially displays a
1490 ``Welcome'' message.
1491 (If the Messages area is not visible, drag its border upward to expand it.)
1492 @end itemize
1493
1494 @noindent
1495 Select @code{File} on the menu bar, and then the @code{New} command.
1496 The Workspace area will become white, and you can now
1497 enter the source program explicitly.
1498 Type the following text
1499
1500 @smallexample @c ada
1501 @group
1502 with Ada.Text_IO; use Ada.Text_IO;
1503 procedure Hello is
1504 begin
1505   Put_Line("Hello from GPS!");
1506 end Hello;
1507 @end group
1508 @end smallexample
1509
1510 @noindent
1511 Select @code{File}, then @code{Save As}, and enter the source file name
1512 @file{hello.adb}.
1513 The file will be saved in the same directory you specified as the
1514 location of the default project file.
1515
1516 @item @emph{Updating the project file}
1517
1518 You need to add the new source file to the project.
1519 To do this, select
1520 the @code{Project} menu and then @code{Edit project properties}.
1521 Click the @code{Main files} tab on the left, and then the
1522 @code{Add} button.
1523 Choose @file{hello.adb} from the list, and press @code{Open}.
1524 The project settings window will reflect this action.
1525 Click @code{OK}.
1526
1527 @item @emph{Building and running the program}
1528
1529 In the main GPS window, now choose the @code{Build} menu, then @code{Make},
1530 and select @file{hello.adb}.
1531 The Messages window will display the resulting invocations of @command{gcc},
1532 @command{gnatbind}, and @command{gnatlink}
1533 (reflecting the default switch settings from the
1534 project file that you created) and then a ``successful compilation/build''
1535 message.
1536
1537 To run the program, choose the @code{Build} menu, then @code{Run}, and
1538 select @command{hello}.
1539 An @emph{Arguments Selection} window will appear.
1540 There are no command line arguments, so just click @code{OK}.
1541
1542 The Messages window will now display the program's output (the string
1543 @code{Hello from GPS}), and at the bottom of the GPS window a status
1544 update is displayed (@code{Run: hello}).
1545 Close the GPS window (or select @code{File}, then @code{Exit}) to
1546 terminate this GPS session.
1547 @end enumerate
1548
1549 @node Simple Debugging with GPS
1550 @subsection Simple Debugging with GPS
1551 @noindent
1552 This section illustrates basic debugging techniques (setting breakpoints,
1553 examining/modifying variables, single stepping).
1554
1555 @enumerate
1556 @item @emph{Opening a project}
1557
1558 Start GPS and select @code{Open existing project}; browse to
1559 specify the project file @file{sample.prj} that you had created in the
1560 earlier example.
1561
1562 @item @emph{Creating a source file}
1563
1564 Select @code{File}, then @code{New}, and type in the following program:
1565
1566 @smallexample @c ada
1567 @group
1568 with Ada.Text_IO; use Ada.Text_IO;
1569 procedure Example is
1570    Line : String (1..80);
1571    N    : Natural;
1572 begin
1573    Put_Line("Type a line of text at each prompt; an empty line to exit");
1574    loop
1575       Put(": ");
1576       Get_Line (Line, N);
1577       Put_Line (Line (1..N) );
1578       exit when N=0;
1579    end loop;
1580 end Example;
1581 @end group
1582 @end smallexample
1583
1584 @noindent
1585 Select @code{File}, then @code{Save as}, and enter the file name
1586 @file{example.adb}.
1587
1588 @item @emph{Updating the project file}
1589
1590 Add @code{Example} as a new main unit for the project:
1591 @enumerate a
1592 @item
1593 Select @code{Project}, then @code{Edit Project Properties}.
1594
1595 @item
1596 Select the @code{Main files} tab, click @code{Add}, then
1597 select the file @file{example.adb} from the list, and
1598 click @code{Open}.
1599 You will see the file name appear in the list of main units
1600
1601 @item
1602 Click @code{OK}
1603 @end enumerate
1604
1605 @item @emph{Building/running the executable}
1606
1607 To build the executable
1608 select @code{Build}, then @code{Make}, and then choose @file{example.adb}.
1609
1610 Run the program to see its effect (in the Messages area).
1611 Each line that you enter is displayed; an empty line will
1612 cause the loop to exit and the program to terminate.
1613
1614 @item @emph{Debugging the program}
1615
1616 Note that the @option{-g} switches to @command{gcc} and @command{gnatlink},
1617 which are required for debugging, are on by default when you create
1618 a new project.
1619 Thus unless you intentionally remove these settings, you will be able
1620 to debug any program that you develop using GPS.
1621
1622 @enumerate a
1623 @item @emph{Initializing}
1624
1625 Select @code{Debug}, then @code{Initialize}, then @file{example}
1626
1627 @item @emph{Setting a breakpoint}
1628
1629 After performing the initialization step, you will observe a small
1630 icon to the right of each line number.
1631 This serves as a toggle for breakpoints; clicking the icon will
1632 set a breakpoint at the corresponding line (the icon will change to
1633 a red circle with an ``x''), and clicking it again
1634 will remove the breakpoint / reset the icon.
1635
1636 For purposes of this example, set a breakpoint at line 10 (the
1637 statement @code{Put_Line@ (Line@ (1..N));}
1638
1639 @item @emph{Starting program execution}
1640
1641 Select @code{Debug}, then @code{Run}.  When the
1642 @code{Program Arguments} window appears, click @code{OK}.
1643 A console window will appear; enter some line of text,
1644 e.g.@: @code{abcde}, at the prompt.
1645 The program will pause execution when it gets to the
1646 breakpoint, and the corresponding line is highlighted.
1647
1648 @item @emph{Examining a variable}
1649
1650 Move the mouse over one of the occurrences of the variable @code{N}.
1651 You will see the value (5) displayed, in ``tool tip'' fashion.
1652 Right click on @code{N}, select @code{Debug}, then select @code{Display N}.
1653 You will see information about @code{N} appear in the @code{Debugger Data}
1654 pane, showing the value as 5.
1655
1656 @item @emph{Assigning a new value to a variable}
1657
1658 Right click on the @code{N} in the @code{Debugger Data} pane, and
1659 select @code{Set value of N}.
1660 When the input window appears, enter the value @code{4} and click
1661 @code{OK}.
1662 This value does not automatically appear in the @code{Debugger Data}
1663 pane; to see it, right click again on the @code{N} in the
1664 @code{Debugger Data} pane and select @code{Update value}.
1665 The new value, 4, will appear in red.
1666
1667 @item @emph{Single stepping}
1668
1669 Select @code{Debug}, then @code{Next}.
1670 This will cause the next statement to be executed, in this case the
1671 call of @code{Put_Line} with the string slice.
1672 Notice in the console window that the displayed string is simply
1673 @code{abcd} and not @code{abcde} which you had entered.
1674 This is because the upper bound of the slice is now 4 rather than 5.
1675
1676 @item @emph{Removing a breakpoint}
1677
1678 Toggle the breakpoint icon at line 10.
1679
1680 @item @emph{Resuming execution from a breakpoint}
1681
1682 Select @code{Debug}, then @code{Continue}.
1683 The program will reach the next iteration of the loop, and
1684 wait for input after displaying the prompt.
1685 This time, just hit the @kbd{Enter} key.
1686 The value of @code{N} will be 0, and the program will terminate.
1687 The console window will disappear.
1688 @end enumerate
1689 @end enumerate
1690 @end ifclear
1691
1692 @node The GNAT Compilation Model
1693 @chapter The GNAT Compilation Model
1694 @cindex GNAT compilation model
1695 @cindex Compilation model
1696
1697 @menu
1698 * Source Representation::
1699 * Foreign Language Representation::
1700 * File Naming Rules::
1701 * Using Other File Names::
1702 * Alternative File Naming Schemes::
1703 * Generating Object Files::
1704 * Source Dependencies::
1705 * The Ada Library Information Files::
1706 * Binding an Ada Program::
1707 * Mixed Language Programming::
1708 @ifclear vms
1709 * Building Mixed Ada & C++ Programs::
1710 * Comparison between GNAT and C/C++ Compilation Models::
1711 @end ifclear
1712 * Comparison between GNAT and Conventional Ada Library Models::
1713 @ifset vms
1714 * Placement of temporary files::
1715 @end ifset
1716 @end menu
1717
1718 @noindent
1719 This chapter describes the compilation model used by GNAT. Although
1720 similar to that used by other languages, such as C and C++, this model
1721 is substantially different from the traditional Ada compilation models,
1722 which are based on a library. The model is initially described without
1723 reference to the library-based model. If you have not previously used an
1724 Ada compiler, you need only read the first part of this chapter. The
1725 last section describes and discusses the differences between the GNAT
1726 model and the traditional Ada compiler models. If you have used other
1727 Ada compilers, this section will help you to understand those
1728 differences, and the advantages of the GNAT model.
1729
1730 @node Source Representation
1731 @section Source Representation
1732 @cindex Latin-1
1733
1734 @noindent
1735 Ada source programs are represented in standard text files, using
1736 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1737 7-bit ASCII set, plus additional characters used for
1738 representing foreign languages (@pxref{Foreign Language Representation}
1739 for support of non-USA character sets). The format effector characters
1740 are represented using their standard ASCII encodings, as follows:
1741
1742 @table @code
1743 @item VT
1744 @findex VT
1745 Vertical tab, @code{16#0B#}
1746
1747 @item HT
1748 @findex HT
1749 Horizontal tab, @code{16#09#}
1750
1751 @item CR
1752 @findex CR
1753 Carriage return, @code{16#0D#}
1754
1755 @item LF
1756 @findex LF
1757 Line feed, @code{16#0A#}
1758
1759 @item FF
1760 @findex FF
1761 Form feed, @code{16#0C#}
1762 @end table
1763
1764 @noindent
1765 Source files are in standard text file format. In addition, GNAT will
1766 recognize a wide variety of stream formats, in which the end of
1767 physical lines is marked by any of the following sequences:
1768 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1769 in accommodating files that are imported from other operating systems.
1770
1771 @cindex End of source file
1772 @cindex Source file, end
1773 @findex SUB
1774 The end of a source file is normally represented by the physical end of
1775 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1776 recognized as signalling the end of the source file. Again, this is
1777 provided for compatibility with other operating systems where this
1778 code is used to represent the end of file.
1779
1780 Each file contains a single Ada compilation unit, including any pragmas
1781 associated with the unit. For example, this means you must place a
1782 package declaration (a package @dfn{spec}) and the corresponding body in
1783 separate files. An Ada @dfn{compilation} (which is a sequence of
1784 compilation units) is represented using a sequence of files. Similarly,
1785 you will place each subunit or child unit in a separate file.
1786
1787 @node Foreign Language Representation
1788 @section Foreign Language Representation
1789
1790 @noindent
1791 GNAT supports the standard character sets defined in Ada as well as
1792 several other non-standard character sets for use in localized versions
1793 of the compiler (@pxref{Character Set Control}).
1794 @menu
1795 * Latin-1::
1796 * Other 8-Bit Codes::
1797 * Wide Character Encodings::
1798 @end menu
1799
1800 @node Latin-1
1801 @subsection Latin-1
1802 @cindex Latin-1
1803
1804 @noindent
1805 The basic character set is Latin-1. This character set is defined by ISO
1806 standard 8859, part 1. The lower half (character codes @code{16#00#}
1807 @dots{} @code{16#7F#)} is identical to standard ASCII coding, but the upper half
1808 is used to represent additional characters. These include extended letters
1809 used by European languages, such as French accents, the vowels with umlauts
1810 used in German, and the extra letter A-ring used in Swedish.
1811
1812 @findex Ada.Characters.Latin_1
1813 For a complete list of Latin-1 codes and their encodings, see the source
1814 file of library unit @code{Ada.Characters.Latin_1} in file
1815 @file{a-chlat1.ads}.
1816 You may use any of these extended characters freely in character or
1817 string literals. In addition, the extended characters that represent
1818 letters can be used in identifiers.
1819
1820 @node Other 8-Bit Codes
1821 @subsection Other 8-Bit Codes
1822
1823 @noindent
1824 GNAT also supports several other 8-bit coding schemes:
1825
1826 @table @asis
1827 @item ISO 8859-2 (Latin-2)
1828 @cindex Latin-2
1829 @cindex ISO 8859-2
1830 Latin-2 letters allowed in identifiers, with uppercase and lowercase
1831 equivalence.
1832
1833 @item ISO 8859-3 (Latin-3)
1834 @cindex Latin-3
1835 @cindex ISO 8859-3
1836 Latin-3 letters allowed in identifiers, with uppercase and lowercase
1837 equivalence.
1838
1839 @item ISO 8859-4 (Latin-4)
1840 @cindex Latin-4
1841 @cindex ISO 8859-4
1842 Latin-4 letters allowed in identifiers, with uppercase and lowercase
1843 equivalence.
1844
1845 @item ISO 8859-5 (Cyrillic)
1846 @cindex ISO 8859-5
1847 @cindex Cyrillic
1848 ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
1849 lowercase equivalence.
1850
1851 @item ISO 8859-15 (Latin-9)
1852 @cindex ISO 8859-15
1853 @cindex Latin-9
1854 ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
1855 lowercase equivalence
1856
1857 @item IBM PC (code page 437)
1858 @cindex code page 437
1859 This code page is the normal default for PCs in the U.S. It corresponds
1860 to the original IBM PC character set. This set has some, but not all, of
1861 the extended Latin-1 letters, but these letters do not have the same
1862 encoding as Latin-1. In this mode, these letters are allowed in
1863 identifiers with uppercase and lowercase equivalence.
1864
1865 @item IBM PC (code page 850)
1866 @cindex code page 850
1867 This code page is a modification of 437 extended to include all the
1868 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
1869 mode, all these letters are allowed in identifiers with uppercase and
1870 lowercase equivalence.
1871
1872 @item Full Upper 8-bit
1873 Any character in the range 80-FF allowed in identifiers, and all are
1874 considered distinct. In other words, there are no uppercase and lowercase
1875 equivalences in this range. This is useful in conjunction with
1876 certain encoding schemes used for some foreign character sets (e.g.,
1877 the typical method of representing Chinese characters on the PC).
1878
1879 @item No Upper-Half
1880 No upper-half characters in the range 80-FF are allowed in identifiers.
1881 This gives Ada 83 compatibility for identifier names.
1882 @end table
1883
1884 @noindent
1885 For precise data on the encodings permitted, and the uppercase and lowercase
1886 equivalences that are recognized, see the file @file{csets.adb} in
1887 the GNAT compiler sources. You will need to obtain a full source release
1888 of GNAT to obtain this file.
1889
1890 @node Wide Character Encodings
1891 @subsection Wide Character Encodings
1892
1893 @noindent
1894 GNAT allows wide character codes to appear in character and string
1895 literals, and also optionally in identifiers, by means of the following
1896 possible encoding schemes:
1897
1898 @table @asis
1899
1900 @item Hex Coding
1901 In this encoding, a wide character is represented by the following five
1902 character sequence:
1903
1904 @smallexample
1905 ESC a b c d
1906 @end smallexample
1907
1908 @noindent
1909 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1910 characters (using uppercase letters) of the wide character code. For
1911 example, ESC A345 is used to represent the wide character with code
1912 @code{16#A345#}.
1913 This scheme is compatible with use of the full Wide_Character set.
1914
1915 @item Upper-Half Coding
1916 @cindex Upper-Half Coding
1917 The wide character with encoding @code{16#abcd#} where the upper bit is on
1918 (in other words, ``a'' is in the range 8-F) is represented as two bytes,
1919 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
1920 character, but is not required to be in the upper half. This method can
1921 be also used for shift-JIS or EUC, where the internal coding matches the
1922 external coding.
1923
1924 @item Shift JIS Coding
1925 @cindex Shift JIS Coding
1926 A wide character is represented by a two-character sequence,
1927 @code{16#ab#} and
1928 @code{16#cd#}, with the restrictions described for upper-half encoding as
1929 described above. The internal character code is the corresponding JIS
1930 character according to the standard algorithm for Shift-JIS
1931 conversion. Only characters defined in the JIS code set table can be
1932 used with this encoding method.
1933
1934 @item EUC Coding
1935 @cindex EUC Coding
1936 A wide character is represented by a two-character sequence
1937 @code{16#ab#} and
1938 @code{16#cd#}, with both characters being in the upper half. The internal
1939 character code is the corresponding JIS character according to the EUC
1940 encoding algorithm. Only characters defined in the JIS code set table
1941 can be used with this encoding method.
1942
1943 @item UTF-8 Coding
1944 A wide character is represented using
1945 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1946 10646-1/Am.2. Depending on the character value, the representation
1947 is a one, two, or three byte sequence:
1948 @smallexample
1949 @iftex
1950 @leftskip=.7cm
1951 @end iftex
1952 16#0000#-16#007f#: 2#0@var{xxxxxxx}#
1953 16#0080#-16#07ff#: 2#110@var{xxxxx}# 2#10@var{xxxxxx}#
1954 16#0800#-16#ffff#: 2#1110@var{xxxx}# 2#10@var{xxxxxx}# 2#10@var{xxxxxx}#
1955
1956 @end smallexample
1957
1958 @noindent
1959 where the @var{xxx} bits correspond to the left-padded bits of the
1960 16-bit character value. Note that all lower half ASCII characters
1961 are represented as ASCII bytes and all upper half characters and
1962 other wide characters are represented as sequences of upper-half
1963 (The full UTF-8 scheme allows for encoding 31-bit characters as
1964 6-byte sequences, but in this implementation, all UTF-8 sequences
1965 of four or more bytes length will be treated as illegal).
1966 @item Brackets Coding
1967 In this encoding, a wide character is represented by the following eight
1968 character sequence:
1969
1970 @smallexample
1971 [ " a b c d " ]
1972 @end smallexample
1973
1974 @noindent
1975 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1976 characters (using uppercase letters) of the wide character code. For
1977 example, [``A345''] is used to represent the wide character with code
1978 @code{16#A345#}. It is also possible (though not required) to use the
1979 Brackets coding for upper half characters. For example, the code
1980 @code{16#A3#} can be represented as @code{[``A3'']}.
1981
1982 This scheme is compatible with use of the full Wide_Character set,
1983 and is also the method used for wide character encoding in the standard
1984 ACVC (Ada Compiler Validation Capability) test suite distributions.
1985
1986 @end table
1987
1988 @noindent
1989 Note: Some of these coding schemes do not permit the full use of the
1990 Ada character set. For example, neither Shift JIS, nor EUC allow the
1991 use of the upper half of the Latin-1 set.
1992
1993 @node File Naming Rules
1994 @section File Naming Rules
1995
1996 @noindent
1997 The default file name is determined by the name of the unit that the
1998 file contains. The name is formed by taking the full expanded name of
1999 the unit and replacing the separating dots with hyphens and using
2000 ^lowercase^uppercase^ for all letters.
2001
2002 An exception arises if the file name generated by the above rules starts
2003 with one of the characters
2004 @ifset vms
2005 @samp{A}, @samp{G}, @samp{I}, or @samp{S},
2006 @end ifset
2007 @ifclear vms
2008 @samp{a}, @samp{g}, @samp{i}, or @samp{s},
2009 @end ifclear
2010 and the second character is a
2011 minus. In this case, the character ^tilde^dollar sign^ is used in place
2012 of the minus. The reason for this special rule is to avoid clashes with
2013 the standard names for child units of the packages System, Ada,
2014 Interfaces, and GNAT, which use the prefixes
2015 @ifset vms
2016 @samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},
2017 @end ifset
2018 @ifclear vms
2019 @samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},
2020 @end ifclear
2021 respectively.
2022
2023 The file extension is @file{.ads} for a spec and
2024 @file{.adb} for a body. The following list shows some
2025 examples of these rules.
2026
2027 @table @file
2028 @item main.ads
2029 Main (spec)
2030 @item main.adb
2031 Main (body)
2032 @item arith_functions.ads
2033 Arith_Functions (package spec)
2034 @item arith_functions.adb
2035 Arith_Functions (package body)
2036 @item func-spec.ads
2037 Func.Spec (child package spec)
2038 @item func-spec.adb
2039 Func.Spec (child package body)
2040 @item main-sub.adb
2041 Sub (subunit of Main)
2042 @item ^a~bad.adb^A$BAD.ADB^
2043 A.Bad (child package body)
2044 @end table
2045
2046 @noindent
2047 Following these rules can result in excessively long
2048 file names if corresponding
2049 unit names are long (for example, if child units or subunits are
2050 heavily nested). An option is available to shorten such long file names
2051 (called file name ``krunching''). This may be particularly useful when
2052 programs being developed with GNAT are to be used on operating systems
2053 with limited file name lengths. @xref{Using gnatkr}.
2054
2055 Of course, no file shortening algorithm can guarantee uniqueness over
2056 all possible unit names; if file name krunching is used, it is your
2057 responsibility to ensure no name clashes occur. Alternatively you
2058 can specify the exact file names that you want used, as described
2059 in the next section. Finally, if your Ada programs are migrating from a
2060 compiler with a different naming convention, you can use the gnatchop
2061 utility to produce source files that follow the GNAT naming conventions.
2062 (For details @pxref{Renaming Files Using gnatchop}.)
2063
2064 Note: in the case of @code{Windows NT/XP} or @code{OpenVMS} operating
2065 systems, case is not significant. So for example on @code{Windows XP}
2066 if the canonical name is @code{main-sub.adb}, you can use the file name
2067 @code{Main-Sub.adb} instead. However, case is significant for other
2068 operating systems, so for example, if you want to use other than
2069 canonically cased file names on a Unix system, you need to follow
2070 the procedures described in the next section.
2071
2072 @node Using Other File Names
2073 @section Using Other File Names
2074 @cindex File names
2075
2076 @noindent
2077 In the previous section, we have described the default rules used by
2078 GNAT to determine the file name in which a given unit resides. It is
2079 often convenient to follow these default rules, and if you follow them,
2080 the compiler knows without being explicitly told where to find all
2081 the files it needs.
2082
2083 However, in some cases, particularly when a program is imported from
2084 another Ada compiler environment, it may be more convenient for the
2085 programmer to specify which file names contain which units. GNAT allows
2086 arbitrary file names to be used by means of the Source_File_Name pragma.
2087 The form of this pragma is as shown in the following examples:
2088 @cindex Source_File_Name pragma
2089
2090 @smallexample @c ada
2091 @cartouche
2092 pragma Source_File_Name (My_Utilities.Stacks,
2093   Spec_File_Name => "myutilst_a.ada");
2094 pragma Source_File_name (My_Utilities.Stacks,
2095   Body_File_Name => "myutilst.ada");
2096 @end cartouche
2097 @end smallexample
2098
2099 @noindent
2100 As shown in this example, the first argument for the pragma is the unit
2101 name (in this example a child unit). The second argument has the form
2102 of a named association. The identifier
2103 indicates whether the file name is for a spec or a body;
2104 the file name itself is given by a string literal.
2105
2106 The source file name pragma is a configuration pragma, which means that
2107 normally it will be placed in the @file{gnat.adc}
2108 file used to hold configuration
2109 pragmas that apply to a complete compilation environment.
2110 For more details on how the @file{gnat.adc} file is created and used
2111 see @ref{Handling of Configuration Pragmas}.
2112 @cindex @file{gnat.adc}
2113
2114 @ifclear vms
2115 GNAT allows completely arbitrary file names to be specified using the
2116 source file name pragma. However, if the file name specified has an
2117 extension other than @file{.ads} or @file{.adb} it is necessary to use
2118 a special syntax when compiling the file. The name in this case must be
2119 preceded by the special sequence @option{-x} followed by a space and the name
2120 of the language, here @code{ada}, as in:
2121
2122 @smallexample
2123 $ gcc -c -x ada peculiar_file_name.sim
2124 @end smallexample
2125 @end ifclear
2126
2127 @noindent
2128 @command{gnatmake} handles non-standard file names in the usual manner (the
2129 non-standard file name for the main program is simply used as the
2130 argument to gnatmake). Note that if the extension is also non-standard,
2131 then it must be included in the @command{gnatmake} command, it may not
2132 be omitted.
2133
2134 @node Alternative File Naming Schemes
2135 @section Alternative File Naming Schemes
2136 @cindex File naming schemes, alternative
2137 @cindex File names
2138
2139 In the previous section, we described the use of the @code{Source_File_Name}
2140 pragma to allow arbitrary names to be assigned to individual source files.
2141 However, this approach requires one pragma for each file, and especially in
2142 large systems can result in very long @file{gnat.adc} files, and also create
2143 a maintenance problem.
2144
2145 GNAT also provides a facility for specifying systematic file naming schemes
2146 other than the standard default naming scheme previously described. An
2147 alternative scheme for naming is specified by the use of
2148 @code{Source_File_Name} pragmas having the following format:
2149 @cindex Source_File_Name pragma
2150
2151 @smallexample @c ada
2152 pragma Source_File_Name (
2153    Spec_File_Name  => FILE_NAME_PATTERN
2154  @r{[},Casing          => CASING_SPEC@r{]}
2155  @r{[},Dot_Replacement => STRING_LITERAL@r{]});
2156
2157 pragma Source_File_Name (
2158    Body_File_Name  => FILE_NAME_PATTERN
2159  @r{[},Casing          => CASING_SPEC@r{]}
2160  @r{[},Dot_Replacement => STRING_LITERAL@r{]});
2161
2162 pragma Source_File_Name (
2163    Subunit_File_Name  => FILE_NAME_PATTERN
2164  @r{[},Casing             => CASING_SPEC@r{]}
2165  @r{[},Dot_Replacement    => STRING_LITERAL@r{]});
2166
2167 FILE_NAME_PATTERN ::= STRING_LITERAL
2168 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
2169 @end smallexample
2170
2171 @noindent
2172 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
2173 It contains a single asterisk character, and the unit name is substituted
2174 systematically for this asterisk. The optional parameter
2175 @code{Casing} indicates
2176 whether the unit name is to be all upper-case letters, all lower-case letters,
2177 or mixed-case. If no
2178 @code{Casing} parameter is used, then the default is all
2179 ^lower-case^upper-case^.
2180
2181 The optional @code{Dot_Replacement} string is used to replace any periods
2182 that occur in subunit or child unit names. If no @code{Dot_Replacement}
2183 argument is used then separating dots appear unchanged in the resulting
2184 file name.
2185 Although the above syntax indicates that the
2186 @code{Casing} argument must appear
2187 before the @code{Dot_Replacement} argument, but it
2188 is also permissible to write these arguments in the opposite order.
2189
2190 As indicated, it is possible to specify different naming schemes for
2191 bodies, specs, and subunits. Quite often the rule for subunits is the
2192 same as the rule for bodies, in which case, there is no need to give
2193 a separate @code{Subunit_File_Name} rule, and in this case the
2194 @code{Body_File_name} rule is used for subunits as well.
2195
2196 The separate rule for subunits can also be used to implement the rather
2197 unusual case of a compilation environment (e.g.@: a single directory) which
2198 contains a subunit and a child unit with the same unit name. Although
2199 both units cannot appear in the same partition, the Ada Reference Manual
2200 allows (but does not require) the possibility of the two units coexisting
2201 in the same environment.
2202
2203 The file name translation works in the following steps:
2204
2205 @itemize @bullet
2206
2207 @item
2208 If there is a specific @code{Source_File_Name} pragma for the given unit,
2209 then this is always used, and any general pattern rules are ignored.
2210
2211 @item
2212 If there is a pattern type @code{Source_File_Name} pragma that applies to
2213 the unit, then the resulting file name will be used if the file exists. If
2214 more than one pattern matches, the latest one will be tried first, and the
2215 first attempt resulting in a reference to a file that exists will be used.
2216
2217 @item
2218 If no pattern type @code{Source_File_Name} pragma that applies to the unit
2219 for which the corresponding file exists, then the standard GNAT default
2220 naming rules are used.
2221
2222 @end itemize
2223
2224 @noindent
2225 As an example of the use of this mechanism, consider a commonly used scheme
2226 in which file names are all lower case, with separating periods copied
2227 unchanged to the resulting file name, and specs end with @file{.1.ada}, and
2228 bodies end with @file{.2.ada}. GNAT will follow this scheme if the following
2229 two pragmas appear:
2230
2231 @smallexample @c ada
2232 pragma Source_File_Name
2233   (Spec_File_Name => "*.1.ada");
2234 pragma Source_File_Name
2235   (Body_File_Name => "*.2.ada");
2236 @end smallexample
2237
2238 @noindent
2239 The default GNAT scheme is actually implemented by providing the following
2240 default pragmas internally:
2241
2242 @smallexample @c ada
2243 pragma Source_File_Name
2244   (Spec_File_Name => "*.ads", Dot_Replacement => "-");
2245 pragma Source_File_Name
2246   (Body_File_Name => "*.adb", Dot_Replacement => "-");
2247 @end smallexample
2248
2249 @noindent
2250 Our final example implements a scheme typically used with one of the
2251 Ada 83 compilers, where the separator character for subunits was ``__''
2252 (two underscores), specs were identified by adding @file{_.ADA}, bodies
2253 by adding @file{.ADA}, and subunits by
2254 adding @file{.SEP}. All file names were
2255 upper case. Child units were not present of course since this was an
2256 Ada 83 compiler, but it seems reasonable to extend this scheme to use
2257 the same double underscore separator for child units.
2258
2259 @smallexample @c ada
2260 pragma Source_File_Name
2261   (Spec_File_Name => "*_.ADA",
2262    Dot_Replacement => "__",
2263    Casing = Uppercase);
2264 pragma Source_File_Name
2265   (Body_File_Name => "*.ADA",
2266    Dot_Replacement => "__",
2267    Casing = Uppercase);
2268 pragma Source_File_Name
2269   (Subunit_File_Name => "*.SEP",
2270    Dot_Replacement => "__",
2271    Casing = Uppercase);
2272 @end smallexample
2273
2274 @node Generating Object Files
2275 @section Generating Object Files
2276
2277 @noindent
2278 An Ada program consists of a set of source files, and the first step in
2279 compiling the program is to generate the corresponding object files.
2280 These are generated by compiling a subset of these source files.
2281 The files you need to compile are the following:
2282
2283 @itemize @bullet
2284 @item
2285 If a package spec has no body, compile the package spec to produce the
2286 object file for the package.
2287
2288 @item
2289 If a package has both a spec and a body, compile the body to produce the
2290 object file for the package. The source file for the package spec need
2291 not be compiled in this case because there is only one object file, which
2292 contains the code for both the spec and body of the package.
2293
2294 @item
2295 For a subprogram, compile the subprogram body to produce the object file
2296 for the subprogram. The spec, if one is present, is as usual in a
2297 separate file, and need not be compiled.
2298
2299 @item
2300 @cindex Subunits
2301 In the case of subunits, only compile the parent unit. A single object
2302 file is generated for the entire subunit tree, which includes all the
2303 subunits.
2304
2305 @item
2306 Compile child units independently of their parent units
2307 (though, of course, the spec of all the ancestor unit must be present in order
2308 to compile a child unit).
2309
2310 @item
2311 @cindex Generics
2312 Compile generic units in the same manner as any other units. The object
2313 files in this case are small dummy files that contain at most the
2314 flag used for elaboration checking. This is because GNAT always handles generic
2315 instantiation by means of macro expansion. However, it is still necessary to
2316 compile generic units, for dependency checking and elaboration purposes.
2317 @end itemize
2318
2319 @noindent
2320 The preceding rules describe the set of files that must be compiled to
2321 generate the object files for a program. Each object file has the same
2322 name as the corresponding source file, except that the extension is
2323 @file{.o} as usual.
2324
2325 You may wish to compile other files for the purpose of checking their
2326 syntactic and semantic correctness. For example, in the case where a
2327 package has a separate spec and body, you would not normally compile the
2328 spec. However, it is convenient in practice to compile the spec to make
2329 sure it is error-free before compiling clients of this spec, because such
2330 compilations will fail if there is an error in the spec.
2331
2332 GNAT provides an option for compiling such files purely for the
2333 purposes of checking correctness; such compilations are not required as
2334 part of the process of building a program. To compile a file in this
2335 checking mode, use the @option{-gnatc} switch.
2336
2337 @node Source Dependencies
2338 @section Source Dependencies
2339
2340 @noindent
2341 A given object file clearly depends on the source file which is compiled
2342 to produce it. Here we are using @dfn{depends} in the sense of a typical
2343 @code{make} utility; in other words, an object file depends on a source
2344 file if changes to the source file require the object file to be
2345 recompiled.
2346 In addition to this basic dependency, a given object may depend on
2347 additional source files as follows:
2348
2349 @itemize @bullet
2350 @item
2351 If a file being compiled @code{with}'s a unit @var{X}, the object file
2352 depends on the file containing the spec of unit @var{X}. This includes
2353 files that are @code{with}'ed implicitly either because they are parents
2354 of @code{with}'ed child units or they are run-time units required by the
2355 language constructs used in a particular unit.
2356
2357 @item
2358 If a file being compiled instantiates a library level generic unit, the
2359 object file depends on both the spec and body files for this generic
2360 unit.
2361
2362 @item
2363 If a file being compiled instantiates a generic unit defined within a
2364 package, the object file depends on the body file for the package as
2365 well as the spec file.
2366
2367 @item
2368 @findex Inline
2369 @cindex @option{-gnatn} switch
2370 If a file being compiled contains a call to a subprogram for which
2371 pragma @code{Inline} applies and inlining is activated with the
2372 @option{-gnatn} switch, the object file depends on the file containing the
2373 body of this subprogram as well as on the file containing the spec. Note
2374 that for inlining to actually occur as a result of the use of this switch,
2375 it is necessary to compile in optimizing mode.
2376
2377 @cindex @option{-gnatN} switch
2378 The use of @option{-gnatN} activates  inlining optimization
2379 that is performed by the front end of the compiler. This inlining does
2380 not require that the code generation be optimized. Like @option{-gnatn},
2381 the use of this switch generates additional dependencies.
2382
2383 When using a gcc-based back end (in practice this means using any version
2384 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
2385 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
2386 Historically front end inlining was more extensive than the gcc back end
2387 inlining, but that is no longer the case.
2388
2389 @item
2390 If an object file @file{O} depends on the proper body of a subunit through
2391 inlining or instantiation, it depends on the parent unit of the subunit.
2392 This means that any modification of the parent unit or one of its subunits
2393 affects the compilation of @file{O}.
2394
2395 @item
2396 The object file for a parent unit depends on all its subunit body files.
2397
2398 @item
2399 The previous two rules meant that for purposes of computing dependencies and
2400 recompilation, a body and all its subunits are treated as an indivisible whole.
2401
2402 @noindent
2403 These rules are applied transitively: if unit @code{A} @code{with}'s
2404 unit @code{B}, whose elaboration calls an inlined procedure in package
2405 @code{C}, the object file for unit @code{A} will depend on the body of
2406 @code{C}, in file @file{c.adb}.
2407
2408 The set of dependent files described by these rules includes all the
2409 files on which the unit is semantically dependent, as dictated by the
2410 Ada language standard. However, it is a superset of what the
2411 standard describes, because it includes generic, inline, and subunit
2412 dependencies.
2413
2414 An object file must be recreated by recompiling the corresponding source
2415 file if any of the source files on which it depends are modified. For
2416 example, if the @code{make} utility is used to control compilation,
2417 the rule for an Ada object file must mention all the source files on
2418 which the object file depends, according to the above definition.
2419 The determination of the necessary
2420 recompilations is done automatically when one uses @command{gnatmake}.
2421 @end itemize
2422
2423 @node The Ada Library Information Files
2424 @section The Ada Library Information Files
2425 @cindex Ada Library Information files
2426 @cindex @file{ALI} files
2427
2428 @noindent
2429 Each compilation actually generates two output files. The first of these
2430 is the normal object file that has a @file{.o} extension. The second is a
2431 text file containing full dependency information. It has the same
2432 name as the source file, but an @file{.ali} extension.
2433 This file is known as the Ada Library Information (@file{ALI}) file.
2434 The following information is contained in the @file{ALI} file.
2435
2436 @itemize @bullet
2437 @item
2438 Version information (indicates which version of GNAT was used to compile
2439 the unit(s) in question)
2440
2441 @item
2442 Main program information (including priority and time slice settings,
2443 as well as the wide character encoding used during compilation).
2444
2445 @item
2446 List of arguments used in the @command{gcc} command for the compilation
2447
2448 @item
2449 Attributes of the unit, including configuration pragmas used, an indication
2450 of whether the compilation was successful, exception model used etc.
2451
2452 @item
2453 A list of relevant restrictions applying to the unit (used for consistency)
2454 checking.
2455
2456 @item
2457 Categorization information (e.g.@: use of pragma @code{Pure}).
2458
2459 @item
2460 Information on all @code{with}'ed units, including presence of
2461 @code{Elaborate} or @code{Elaborate_All} pragmas.
2462
2463 @item
2464 Information from any @code{Linker_Options} pragmas used in the unit
2465
2466 @item
2467 Information on the use of @code{Body_Version} or @code{Version}
2468 attributes in the unit.
2469
2470 @item
2471 Dependency information. This is a list of files, together with
2472 time stamp and checksum information. These are files on which
2473 the unit depends in the sense that recompilation is required
2474 if any of these units are modified.
2475
2476 @item
2477 Cross-reference data. Contains information on all entities referenced
2478 in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
2479 provide cross-reference information.
2480
2481 @end itemize
2482
2483 @noindent
2484 For a full detailed description of the format of the @file{ALI} file,
2485 see the source of the body of unit @code{Lib.Writ}, contained in file
2486 @file{lib-writ.adb} in the GNAT compiler sources.
2487
2488 @node Binding an Ada Program
2489 @section Binding an Ada Program
2490
2491 @noindent
2492 When using languages such as C and C++, once the source files have been
2493 compiled the only remaining step in building an executable program
2494 is linking the object modules together. This means that it is possible to
2495 link an inconsistent version of a program, in which two units have
2496 included different versions of the same header.
2497
2498 The rules of Ada do not permit such an inconsistent program to be built.
2499 For example, if two clients have different versions of the same package,
2500 it is illegal to build a program containing these two clients.
2501 These rules are enforced by the GNAT binder, which also determines an
2502 elaboration order consistent with the Ada rules.
2503
2504 The GNAT binder is run after all the object files for a program have
2505 been created. It is given the name of the main program unit, and from
2506 this it determines the set of units required by the program, by reading the
2507 corresponding ALI files. It generates error messages if the program is
2508 inconsistent or if no valid order of elaboration exists.
2509
2510 If no errors are detected, the binder produces a main program, in Ada by
2511 default, that contains calls to the elaboration procedures of those
2512 compilation unit that require them, followed by
2513 a call to the main program. This Ada program is compiled to generate the
2514 object file for the main program. The name of
2515 the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec
2516 @file{b~@var{xxx}.ads}) where @var{xxx} is the name of the
2517 main program unit.
2518
2519 Finally, the linker is used to build the resulting executable program,
2520 using the object from the main program from the bind step as well as the
2521 object files for the Ada units of the program.
2522
2523 @node Mixed Language Programming
2524 @section Mixed Language Programming
2525 @cindex Mixed Language Programming
2526
2527 @noindent
2528 This section describes how to develop a mixed-language program,
2529 specifically one that comprises units in both Ada and C.
2530
2531 @menu
2532 * Interfacing to C::
2533 * Calling Conventions::
2534 @end menu
2535
2536 @node Interfacing to C
2537 @subsection Interfacing to C
2538 @noindent
2539 Interfacing Ada with a foreign language such as C involves using
2540 compiler directives to import and/or export entity definitions in each
2541 language---using @code{extern} statements in C, for instance, and the
2542 @code{Import}, @code{Export}, and @code{Convention} pragmas in Ada.
2543 A full treatment of these topics is provided in Appendix B, section 1
2544 of the Ada Reference Manual.
2545
2546 There are two ways to build a program using GNAT that contains some Ada
2547 sources and some foreign language sources, depending on whether or not
2548 the main subprogram is written in Ada.  Here is a source example with
2549 the main subprogram in Ada:
2550
2551 @smallexample
2552 /* file1.c */
2553 #include <stdio.h>
2554
2555 void print_num (int num)
2556 @{
2557   printf ("num is %d.\n", num);
2558   return;
2559 @}
2560
2561 /* file2.c */
2562
2563 /* num_from_Ada is declared in my_main.adb */
2564 extern int num_from_Ada;
2565
2566 int get_num (void)
2567 @{
2568   return num_from_Ada;
2569 @}
2570 @end smallexample
2571
2572 @smallexample @c ada
2573 --  my_main.adb
2574 procedure My_Main is
2575
2576    --  Declare then export an Integer entity called num_from_Ada
2577    My_Num : Integer := 10;
2578    pragma Export (C, My_Num, "num_from_Ada");
2579
2580    --  Declare an Ada function spec for Get_Num, then use
2581    --  C function get_num for the implementation.
2582    function Get_Num return Integer;
2583    pragma Import (C, Get_Num, "get_num");
2584
2585    --  Declare an Ada procedure spec for Print_Num, then use
2586    --  C function print_num for the implementation.
2587    procedure Print_Num (Num : Integer);
2588    pragma Import (C, Print_Num, "print_num");
2589
2590 begin
2591    Print_Num (Get_Num);
2592 end My_Main;
2593 @end smallexample
2594
2595 @enumerate
2596 @item
2597 To build this example, first compile the foreign language files to
2598 generate object files:
2599 @smallexample
2600 ^gcc -c file1.c^gcc -c FILE1.C^
2601 ^gcc -c file2.c^gcc -c FILE2.C^
2602 @end smallexample
2603
2604 @item
2605 Then, compile the Ada units to produce a set of object files and ALI
2606 files:
2607 @smallexample
2608 gnatmake ^-c^/ACTIONS=COMPILE^ my_main.adb
2609 @end smallexample
2610
2611 @item
2612 Run the Ada binder on the Ada main program:
2613 @smallexample
2614 gnatbind my_main.ali
2615 @end smallexample
2616
2617 @item
2618 Link the Ada main program, the Ada objects and the other language
2619 objects:
2620 @smallexample
2621 gnatlink my_main.ali file1.o file2.o
2622 @end smallexample
2623 @end enumerate
2624
2625 The last three steps can be grouped in a single command:
2626 @smallexample
2627 gnatmake my_main.adb -largs file1.o file2.o
2628 @end smallexample
2629
2630 @cindex Binder output file
2631 @noindent
2632 If the main program is in a language other than Ada, then you may have
2633 more than one entry point into the Ada subsystem. You must use a special
2634 binder option to generate callable routines that initialize and
2635 finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}).
2636 Calls to the initialization and finalization routines must be inserted
2637 in the main program, or some other appropriate point in the code. The
2638 call to initialize the Ada units must occur before the first Ada
2639 subprogram is called, and the call to finalize the Ada units must occur
2640 after the last Ada subprogram returns. The binder will place the
2641 initialization and finalization subprograms into the
2642 @file{b~@var{xxx}.adb} file where they can be accessed by your C
2643 sources.  To illustrate, we have the following example:
2644
2645 @smallexample
2646 /* main.c */
2647 extern void adainit (void);
2648 extern void adafinal (void);
2649 extern int add (int, int);
2650 extern int sub (int, int);
2651
2652 int main (int argc, char *argv[])
2653 @{
2654   int a = 21, b = 7;
2655
2656   adainit();
2657
2658   /* Should print "21 + 7 = 28" */
2659   printf ("%d + %d = %d\n", a, b, add (a, b));
2660   /* Should print "21 - 7 = 14" */
2661   printf ("%d - %d = %d\n", a, b, sub (a, b));
2662
2663   adafinal();
2664 @}
2665 @end smallexample
2666
2667 @smallexample @c ada
2668 --  unit1.ads
2669 package Unit1 is
2670    function Add (A, B : Integer) return Integer;
2671    pragma Export (C, Add, "add");
2672 end Unit1;
2673
2674 --  unit1.adb
2675 package body Unit1 is
2676    function Add (A, B : Integer) return Integer is
2677    begin
2678       return A + B;
2679    end Add;
2680 end Unit1;
2681
2682 --  unit2.ads
2683 package Unit2 is
2684    function Sub (A, B : Integer) return Integer;
2685    pragma Export (C, Sub, "sub");
2686 end Unit2;
2687
2688 --  unit2.adb
2689 package body Unit2 is
2690    function Sub (A, B : Integer) return Integer is
2691    begin
2692       return A - B;
2693    end Sub;
2694 end Unit2;
2695 @end smallexample
2696
2697 @enumerate
2698 @item
2699 The build procedure for this application is similar to the last
2700 example's.  First, compile the foreign language files to generate object
2701 files:
2702 @smallexample
2703 ^gcc -c main.c^gcc -c main.c^
2704 @end smallexample
2705
2706 @item
2707 Next, compile the Ada units to produce a set of object files and ALI
2708 files:
2709 @smallexample
2710 gnatmake ^-c^/ACTIONS=COMPILE^ unit1.adb
2711 gnatmake ^-c^/ACTIONS=COMPILE^ unit2.adb
2712 @end smallexample
2713
2714 @item
2715 Run the Ada binder on every generated ALI file.  Make sure to use the
2716 @option{-n} option to specify a foreign main program:
2717 @smallexample
2718 gnatbind ^-n^/NOMAIN^ unit1.ali unit2.ali
2719 @end smallexample
2720
2721 @item
2722 Link the Ada main program, the Ada objects and the foreign language
2723 objects. You need only list the last ALI file here:
2724 @smallexample
2725 gnatlink unit2.ali main.o -o exec_file
2726 @end smallexample
2727
2728 This procedure yields a binary executable called @file{exec_file}.
2729 @end enumerate
2730
2731 @noindent
2732 Depending on the circumstances (for example when your non-Ada main object
2733 does not provide symbol @code{main}), you may also need to instruct the
2734 GNAT linker not to include the standard startup objects by passing the
2735 @option{^-nostartfiles^/NOSTART_FILES^} switch to @command{gnatlink}.
2736
2737 @node Calling Conventions
2738 @subsection Calling Conventions
2739 @cindex Foreign Languages
2740 @cindex Calling Conventions
2741 GNAT follows standard calling sequence conventions and will thus interface
2742 to any other language that also follows these conventions. The following
2743 Convention identifiers are recognized by GNAT:
2744
2745 @table @code
2746 @cindex Interfacing to Ada
2747 @cindex Other Ada compilers
2748 @cindex Convention Ada
2749 @item Ada
2750 This indicates that the standard Ada calling sequence will be
2751 used and all Ada data items may be passed without any limitations in the
2752 case where GNAT is used to generate both the caller and callee. It is also
2753 possible to mix GNAT generated code and code generated by another Ada
2754 compiler. In this case, the data types should be restricted to simple
2755 cases, including primitive types. Whether complex data types can be passed
2756 depends on the situation. Probably it is safe to pass simple arrays, such
2757 as arrays of integers or floats. Records may or may not work, depending
2758 on whether both compilers lay them out identically. Complex structures
2759 involving variant records, access parameters, tasks, or protected types,
2760 are unlikely to be able to be passed.
2761
2762 Note that in the case of GNAT running
2763 on a platform that supports HP Ada 83, a higher degree of compatibility
2764 can be guaranteed, and in particular records are layed out in an identical
2765 manner in the two compilers. Note also that if output from two different
2766 compilers is mixed, the program is responsible for dealing with elaboration
2767 issues. Probably the safest approach is to write the main program in the
2768 version of Ada other than GNAT, so that it takes care of its own elaboration
2769 requirements, and then call the GNAT-generated adainit procedure to ensure
2770 elaboration of the GNAT components. Consult the documentation of the other
2771 Ada compiler for further details on elaboration.
2772
2773 However, it is not possible to mix the tasking run time of GNAT and
2774 HP Ada 83, All the tasking operations must either be entirely within
2775 GNAT compiled sections of the program, or entirely within HP Ada 83
2776 compiled sections of the program.
2777
2778 @cindex Interfacing to Assembly
2779 @cindex Convention Assembler
2780 @item Assembler
2781 Specifies assembler as the convention. In practice this has the
2782 same effect as convention Ada (but is not equivalent in the sense of being
2783 considered the same convention).
2784
2785 @cindex Convention Asm
2786 @findex Asm
2787 @item Asm
2788 Equivalent to Assembler.
2789
2790 @cindex Interfacing to COBOL
2791 @cindex Convention COBOL
2792 @findex COBOL
2793 @item COBOL
2794 Data will be passed according to the conventions described
2795 in section B.4 of the Ada Reference Manual.
2796
2797 @findex C
2798 @cindex Interfacing to C
2799 @cindex Convention C
2800 @item C
2801 Data will be passed according to the conventions described
2802 in section B.3 of the Ada Reference Manual.
2803
2804 A note on interfacing to a C ``varargs'' function:
2805 @findex C varargs function
2806 @cindex Interfacing to C varargs function
2807 @cindex varargs function interfaces
2808
2809 @itemize @bullet
2810 @item
2811 In C, @code{varargs} allows a function to take a variable number of
2812 arguments. There is no direct equivalent in this to Ada. One
2813 approach that can be used is to create a C wrapper for each
2814 different profile and then interface to this C wrapper. For
2815 example, to print an @code{int} value using @code{printf},
2816 create a C function @code{printfi} that takes two arguments, a
2817 pointer to a string and an int, and calls @code{printf}.
2818 Then in the Ada program, use pragma @code{Import} to
2819 interface to @code{printfi}.
2820
2821 @item
2822 It may work on some platforms to directly interface to
2823 a @code{varargs} function by providing a specific Ada profile
2824 for a particular call. However, this does not work on
2825 all platforms, since there is no guarantee that the
2826 calling sequence for a two argument normal C function
2827 is the same as for calling a @code{varargs} C function with
2828 the same two arguments.
2829 @end itemize
2830
2831 @cindex Convention Default
2832 @findex Default
2833 @item Default
2834 Equivalent to C.
2835
2836 @cindex Convention External
2837 @findex External
2838 @item External
2839 Equivalent to C.
2840
2841 @ifclear vms
2842 @findex C++
2843 @cindex Interfacing to C++
2844 @cindex Convention C++
2845 @item C_Plus_Plus (or CPP)
2846 This stands for C++. For most purposes this is identical to C.
2847 See the separate description of the specialized GNAT pragmas relating to
2848 C++ interfacing for further details.
2849 @end ifclear
2850
2851 @findex Fortran
2852 @cindex Interfacing to Fortran
2853 @cindex Convention Fortran
2854 @item Fortran
2855 Data will be passed according to the conventions described
2856 in section B.5 of the Ada Reference Manual.
2857
2858 @item Intrinsic
2859 This applies to an intrinsic operation, as defined in the Ada
2860 Reference Manual. If a pragma Import (Intrinsic) applies to a subprogram,
2861 this means that the body of the subprogram is provided by the compiler itself,
2862 usually by means of an efficient code sequence, and that the user does not
2863 supply an explicit body for it. In an application program, the pragma may
2864 be applied to the following sets of names:
2865
2866 @itemize @bullet
2867 @item
2868 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right,
2869 Shift_Right_Arithmetic.  The corresponding subprogram declaration must have
2870 two formal parameters. The
2871 first one must be a signed integer type or a modular type with a binary
2872 modulus, and the second parameter must be of type Natural.
2873 The return type must be the same as the type of the first argument. The size
2874 of this type can only be 8, 16, 32, or 64.
2875
2876 @item
2877 Binary arithmetic operators: ``+'', ``-'', ``*'', ``/''
2878 The corresponding operator declaration must have parameters and result type
2879 that have the same root numeric type (for example, all three are long_float
2880 types). This simplifies the definition of operations that use type checking
2881 to perform dimensional checks:
2882
2883 @smallexample @c ada
2884 type Distance is new Long_Float;
2885 type Time     is new Long_Float;
2886 type Velocity is new Long_Float;
2887 function "/" (D : Distance; T : Time)
2888   return Velocity;
2889 pragma Import (Intrinsic, "/");
2890 @end smallexample
2891
2892 @noindent
2893 This common idiom is often programmed with a generic definition and an
2894 explicit body. The pragma makes it simpler to introduce such declarations.
2895 It incurs no overhead in compilation time or code size, because it is
2896 implemented as a single machine instruction.
2897
2898 @item
2899 General subprogram entities, to bind an Ada subprogram declaration to
2900 a compiler builtin by name with back-ends where such interfaces are
2901 available. A typical example is the set of ``__builtin'' functions
2902 exposed by the GCC back-end, as in the following example:
2903
2904 @smallexample @c ada
2905    function builtin_sqrt (F : Float) return Float;
2906    pragma Import (Intrinsic, builtin_sqrt, "__builtin_sqrtf");
2907 @end smallexample
2908
2909 Most of the GCC builtins are accessible this way, and as for other
2910 import conventions (e.g. C), it is the user's responsibility to ensure
2911 that the Ada subprogram profile matches the underlying builtin
2912 expectations.
2913 @end itemize
2914
2915 @noindent
2916
2917 @ifset unw
2918 @findex Stdcall
2919 @cindex Convention Stdcall
2920 @item Stdcall
2921 This is relevant only to Windows XP/2000/NT implementations of GNAT,
2922 and specifies that the @code{Stdcall} calling sequence will be used,
2923 as defined by the NT API. Nevertheless, to ease building
2924 cross-platform bindings this convention will be handled as a @code{C} calling
2925 convention on non-Windows platforms.
2926
2927 @findex DLL
2928 @cindex Convention DLL
2929 @item DLL
2930 This is equivalent to @code{Stdcall}.
2931
2932 @findex Win32
2933 @cindex Convention Win32
2934 @item Win32
2935 This is equivalent to @code{Stdcall}.
2936 @end ifset
2937
2938 @findex Stubbed
2939 @cindex Convention Stubbed
2940 @item Stubbed
2941 This is a special convention that indicates that the compiler
2942 should provide a stub body that raises @code{Program_Error}.
2943 @end table
2944
2945 @noindent
2946 GNAT additionally provides a useful pragma @code{Convention_Identifier}
2947 that can be used to parametrize conventions and allow additional synonyms
2948 to be specified. For example if you have legacy code in which the convention
2949 identifier Fortran77 was used for Fortran, you can use the configuration
2950 pragma:
2951
2952 @smallexample @c ada
2953 pragma Convention_Identifier (Fortran77, Fortran);
2954 @end smallexample
2955
2956 @noindent
2957 And from now on the identifier Fortran77 may be used as a convention
2958 identifier (for example in an @code{Import} pragma) with the same
2959 meaning as Fortran.
2960
2961 @ifclear vms
2962 @node Building Mixed Ada & C++ Programs
2963 @section Building Mixed Ada and C++ Programs
2964
2965 @noindent
2966 A programmer inexperienced with mixed-language development may find that
2967 building an application containing both Ada and C++ code can be a
2968 challenge.  This section gives a few
2969 hints that should make this task easier. The first section addresses
2970 the differences between interfacing with C and interfacing with C++.
2971 The second section
2972 looks into the delicate problem of linking the complete application from
2973 its Ada and C++ parts. The last section gives some hints on how the GNAT
2974 run-time library can be adapted in order to allow inter-language dispatching
2975 with a new C++ compiler.
2976
2977 @menu
2978 * Interfacing to C++::
2979 * Linking a Mixed C++ & Ada Program::
2980 * A Simple Example::
2981 * Interfacing with C++ constructors::
2982 * Interfacing with C++ at the Class Level::
2983 @end menu
2984
2985 @node Interfacing to C++
2986 @subsection Interfacing to C++
2987
2988 @noindent
2989 GNAT supports interfacing with the G++ compiler (or any C++ compiler
2990 generating code that is compatible with the G++ Application Binary
2991 Interface ---see http://www.codesourcery.com/archives/cxx-abi).
2992
2993 @noindent
2994 Interfacing can be done at 3 levels: simple data, subprograms, and
2995 classes. In the first two cases, GNAT offers a specific @code{Convention
2996 C_Plus_Plus} (or @code{CPP}) that behaves exactly like @code{Convention C}.
2997 Usually, C++ mangles the names of subprograms. To generate proper mangled
2998 names automatically, see @ref{Generating Ada Bindings for C and C++ headers}).
2999 This problem can also be addressed manually in two ways:
3000
3001 @itemize @bullet
3002 @item
3003 by modifying the C++ code in order to force a C convention using
3004 the @code{extern "C"} syntax.
3005
3006 @item
3007 by figuring out the mangled name (using e.g. @command{nm}) and using it as the
3008 Link_Name argument of the pragma import.
3009 @end itemize
3010
3011 @noindent
3012 Interfacing at the class level can be achieved by using the GNAT specific
3013 pragmas such as @code{CPP_Constructor}.  @xref{Interfacing to C++,,,
3014 gnat_rm, GNAT Reference Manual}, for additional information.
3015
3016 @node Linking a Mixed C++ & Ada Program
3017 @subsection Linking a Mixed C++ & Ada Program
3018
3019 @noindent
3020 Usually the linker of the C++ development system must be used to link
3021 mixed applications because most C++ systems will resolve elaboration
3022 issues (such as calling constructors on global class instances)
3023 transparently during the link phase. GNAT has been adapted to ease the
3024 use of a foreign linker for the last phase. Three cases can be
3025 considered:
3026 @enumerate
3027
3028 @item
3029 Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
3030 The C++ linker can simply be called by using the C++ specific driver
3031 called @code{g++}.
3032
3033 Note that if the C++ code uses inline functions, you will need to
3034 compile your C++ code with the @code{-fkeep-inline-functions} switch in
3035 order to provide an existing function implementation that the Ada code can
3036 link with.
3037
3038 @smallexample
3039 $ g++ -c -fkeep-inline-functions file1.C
3040 $ g++ -c -fkeep-inline-functions file2.C
3041 $ gnatmake ada_unit -largs file1.o file2.o --LINK=g++
3042 @end smallexample
3043
3044 @item
3045 Using GNAT and G++ from two different GCC installations: If both
3046 compilers are on the @env{PATH}, the previous method may be used. It is
3047 important to note that environment variables such as
3048 @env{C_INCLUDE_PATH}, @env{GCC_EXEC_PREFIX}, @env{BINUTILS_ROOT}, and
3049 @env{GCC_ROOT} will affect both compilers
3050 at the same time and may make one of the two compilers operate
3051 improperly if set during invocation of the wrong compiler.  It is also
3052 very important that the linker uses the proper @file{libgcc.a} GCC
3053 library -- that is, the one from the C++ compiler installation. The
3054 implicit link command as suggested in the @command{gnatmake} command
3055 from the former example can be replaced by an explicit link command with
3056 the full-verbosity option in order to verify which library is used:
3057 @smallexample
3058 $ gnatbind ada_unit
3059 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
3060 @end smallexample
3061 If there is a problem due to interfering environment variables, it can
3062 be worked around by using an intermediate script. The following example
3063 shows the proper script to use when GNAT has not been installed at its
3064 default location and g++ has been installed at its default location:
3065
3066 @smallexample
3067 $ cat ./my_script
3068 #!/bin/sh
3069 unset BINUTILS_ROOT
3070 unset GCC_ROOT
3071 c++ $*
3072 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
3073 @end smallexample
3074
3075 @item
3076 Using a non-GNU C++ compiler: The commands previously described can be
3077 used to insure that the C++ linker is used. Nonetheless, you need to add
3078 a few more parameters to the link command line, depending on the exception
3079 mechanism used.
3080
3081 If the @code{setjmp/longjmp} exception mechanism is used, only the paths
3082 to the libgcc libraries are required:
3083
3084 @smallexample
3085 $ cat ./my_script
3086 #!/bin/sh
3087 CC $* `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a`
3088 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3089 @end smallexample
3090
3091 Where CC is the name of the non-GNU C++ compiler.
3092
3093 If the @code{zero cost} exception mechanism is used, and the platform
3094 supports automatic registration of exception tables (e.g.@: Solaris or IRIX),
3095 paths to more objects are required:
3096
3097 @smallexample
3098 $ cat ./my_script
3099 #!/bin/sh
3100 CC `gcc -print-file-name=crtbegin.o` $* \
3101 `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a` \
3102 `gcc -print-file-name=crtend.o`
3103 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3104 @end smallexample
3105
3106 If the @code{zero cost} exception mechanism is used, and the platform
3107 doesn't support automatic registration of exception tables (e.g.@: HP-UX,
3108 Tru64 or AIX), the simple approach described above will not work and
3109 a pre-linking phase using GNAT will be necessary.
3110
3111 @end enumerate
3112
3113 Another alternative is to use the @command{gprbuild} multi-language builder
3114 which has a large knowledge base and knows how to link Ada and C++ code
3115 together automatically in most cases.
3116
3117 @node A Simple Example
3118 @subsection  A Simple Example
3119 @noindent
3120 The following example, provided as part of the GNAT examples, shows how
3121 to achieve procedural interfacing between Ada and C++ in both
3122 directions. The C++ class A has two methods. The first method is exported
3123 to Ada by the means of an extern C wrapper function. The second method
3124 calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
3125 a limited record with a layout comparable to the C++ class. The Ada
3126 subprogram, in turn, calls the C++ method. So, starting from the C++
3127 main program, the process passes back and forth between the two
3128 languages.
3129
3130 @noindent
3131 Here are the compilation commands:
3132 @smallexample
3133 $ gnatmake -c simple_cpp_interface
3134 $ g++ -c cpp_main.C
3135 $ g++ -c ex7.C
3136 $ gnatbind -n simple_cpp_interface
3137 $ gnatlink simple_cpp_interface -o cpp_main --LINK=g++
3138       -lstdc++ ex7.o cpp_main.o
3139 @end smallexample
3140
3141 @noindent
3142 Here are the corresponding sources:
3143 @smallexample
3144
3145 //cpp_main.C
3146
3147 #include "ex7.h"
3148
3149 extern "C" @{
3150   void adainit (void);
3151   void adafinal (void);
3152   void method1 (A *t);
3153 @}
3154
3155 void method1 (A *t)
3156 @{
3157   t->method1 ();
3158 @}
3159
3160 int main ()
3161 @{
3162   A obj;
3163   adainit ();
3164   obj.method2 (3030);
3165   adafinal ();
3166 @}
3167
3168 //ex7.h
3169
3170 class Origin @{
3171  public:
3172   int o_value;
3173 @};
3174 class A : public Origin @{
3175  public:
3176   void method1 (void);
3177   void method2 (int v);
3178   A();
3179   int   a_value;
3180 @};
3181
3182 //ex7.C
3183
3184 #include "ex7.h"
3185 #include <stdio.h>
3186
3187 extern "C" @{ void ada_method2 (A *t, int v);@}
3188
3189 void A::method1 (void)
3190 @{
3191   a_value = 2020;
3192   printf ("in A::method1, a_value = %d \n",a_value);
3193
3194 @}
3195
3196 void A::method2 (int v)
3197 @{
3198    ada_method2 (this, v);
3199    printf ("in A::method2, a_value = %d \n",a_value);
3200
3201 @}
3202
3203 A::A(void)
3204 @{
3205    a_value = 1010;
3206   printf ("in A::A, a_value = %d \n",a_value);
3207 @}
3208 @end smallexample
3209
3210 @smallexample @c ada
3211 -- Ada sources
3212 package body Simple_Cpp_Interface is
3213
3214    procedure Ada_Method2 (This : in out A; V : Integer) is
3215    begin
3216       Method1 (This);
3217       This.A_Value := V;
3218    end Ada_Method2;
3219
3220 end Simple_Cpp_Interface;
3221
3222 with System;
3223 package Simple_Cpp_Interface is
3224    type A is limited
3225       record
3226          Vptr    : System.Address;
3227          O_Value : Integer;
3228          A_Value : Integer;
3229       end record;
3230    pragma Convention (C, A);
3231
3232    procedure Method1 (This : in out A);
3233    pragma Import (C, Method1);
3234
3235    procedure Ada_Method2 (This : in out A; V : Integer);
3236    pragma Export (C, Ada_Method2);
3237
3238 end Simple_Cpp_Interface;
3239 @end smallexample
3240
3241 @node Interfacing with C++ constructors
3242 @subsection Interfacing with C++ constructors
3243 @noindent
3244
3245 In order to interface with C++ constructors GNAT provides the
3246 @code{pragma CPP_Constructor} (@xref{Interfacing to C++,,,
3247 gnat_rm, GNAT Reference Manual}, for additional information).
3248 In this section we present some common uses of C++ constructors
3249 in mixed-languages programs in GNAT.
3250
3251 Let us assume that we need to interface with the following
3252 C++ class:
3253
3254 @smallexample
3255 @b{class} Root @{
3256 @b{public}:
3257   int  a_value;
3258   int  b_value;
3259   @b{virtual} int Get_Value ();
3260   Root();              // Default constructor
3261   Root(int v);         // 1st non-default constructor
3262   Root(int v, int w);  // 2nd non-default constructor
3263 @};
3264 @end smallexample
3265
3266 For this purpose we can write the following package spec (further
3267 information on how to build this spec is available in
3268 @ref{Interfacing with C++ at the Class Level} and
3269 @ref{Generating Ada Bindings for C and C++ headers}).
3270
3271 @smallexample @c ada
3272 with Interfaces.C; use Interfaces.C;
3273 package Pkg_Root is
3274   type Root is tagged limited record
3275      A_Value : int;
3276      B_Value : int;
3277   end record;
3278   pragma Import (CPP, Root);
3279
3280   function Get_Value (Obj : Root) return int;
3281   pragma Import (CPP, Get_Value);
3282
3283   function Constructor return Root;
3284   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ev");
3285
3286   function Constructor (v : Integer) return Root;
3287   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ei");
3288
3289   function Constructor (v, w : Integer) return Root;
3290   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Eii");
3291 end Pkg_Root;
3292 @end smallexample
3293
3294 On the Ada side the constructor is represented by a function (whose
3295 name is arbitrary) that returns the classwide type corresponding to
3296 the imported C++ class. Although the constructor is described as a
3297 function, it is typically a procedure with an extra implicit argument
3298 (the object being initialized) at the implementation level. GNAT
3299 issues the appropriate call, whatever it is, to get the object
3300 properly initialized.
3301
3302 Constructors can only appear in the following contexts:
3303
3304 @itemize @bullet
3305 @item
3306 On the right side of an initialization of an object of type @var{T}.
3307 @item
3308 On the right side of an initialization of a record component of type @var{T}.
3309 @item
3310 In an Ada 2005 limited aggregate.
3311 @item
3312 In an Ada 2005 nested limited aggregate.
3313 @item
3314 In an Ada 2005 limited aggregate that initializes an object built in
3315 place by an extended return statement.
3316 @end itemize
3317
3318 @noindent
3319 In a declaration of an object whose type is a class imported from C++,
3320 either the default C++ constructor is implicitly called by GNAT, or
3321 else the required C++ constructor must be explicitly called in the
3322 expression that initializes the object. For example:
3323
3324 @smallexample @c ada
3325   Obj1 : Root;
3326   Obj2 : Root := Constructor;
3327   Obj3 : Root := Constructor (v => 10);
3328   Obj4 : Root := Constructor (30, 40);
3329 @end smallexample
3330
3331 The first two declarations are equivalent: in both cases the default C++
3332 constructor is invoked (in the former case the call to the constructor is
3333 implicit, and in the latter case the call is explicit in the object
3334 declaration). @code{Obj3} is initialized by the C++ non-default constructor
3335 that takes an integer argument, and @code{Obj4} is initialized by the
3336 non-default C++ constructor that takes two integers.
3337
3338 Let us derive the imported C++ class in the Ada side. For example:
3339
3340 @smallexample @c ada
3341   type DT is new Root with record
3342      C_Value : Natural := 2009;
3343   end record;
3344 @end smallexample
3345
3346 In this case the components DT inherited from the C++ side must be
3347 initialized by a C++ constructor, and the additional Ada components
3348 of type DT are initialized by GNAT. The initialization of such an
3349 object is done either by default, or by means of a function returning
3350 an aggregate of type DT, or by means of an extension aggregate.
3351
3352 @smallexample @c ada
3353   Obj5 : DT;
3354   Obj6 : DT := Function_Returning_DT (50);
3355   Obj7 : DT := (Constructor (30,40) with C_Value => 50);
3356 @end smallexample
3357
3358 The declaration of @code{Obj5} invokes the default constructors: the
3359 C++ default constructor of the parent type takes care of the initialization
3360 of the components inherited from Root, and GNAT takes care of the default
3361 initialization of the additional Ada components of type DT (that is,
3362 @code{C_Value} is initialized to value 2009). The order of invocation of
3363 the constructors is consistent with the order of elaboration required by
3364 Ada and C++. That is, the constructor of the parent type is always called
3365 before the constructor of the derived type.
3366
3367 Let us now consider a record that has components whose type is imported
3368 from C++. For example:
3369
3370 @smallexample @c ada
3371   type Rec1 is limited record
3372      Data1 : Root := Constructor (10);
3373      Value : Natural := 1000;
3374   end record;
3375
3376   type Rec2 (D : Integer := 20) is limited record
3377      Rec   : Rec1;
3378      Data2 : Root := Constructor (D, 30);
3379   end record;
3380 @end smallexample
3381
3382 The initialization of an object of type @code{Rec2} will call the
3383 non-default C++ constructors specified for the imported components.
3384 For example:
3385
3386 @smallexample @c ada
3387   Obj8 : Rec2 (40);
3388 @end smallexample
3389
3390 Using Ada 2005 we can use limited aggregates to initialize an object
3391 invoking C++ constructors that differ from those specified in the type
3392 declarations. For example:
3393
3394 @smallexample @c ada
3395   Obj9 : Rec2 := (Rec => (Data1 => Constructor (15, 16),
3396                           others => <>),
3397                   others => <>);
3398 @end smallexample
3399
3400 The above declaration uses an Ada 2005 limited aggregate to
3401 initialize @code{Obj9}, and the C++ constructor that has two integer
3402 arguments is invoked to initialize the @code{Data1} component instead
3403 of the constructor specified in the declaration of type @code{Rec1}. In
3404 Ada 2005 the box in the aggregate indicates that unspecified components
3405 are initialized using the expression (if any) available in the component
3406 declaration. That is, in this case discriminant @code{D} is initialized
3407 to value @code{20}, @code{Value} is initialized to value 1000, and the
3408 non-default C++ constructor that handles two integers takes care of
3409 initializing component @code{Data2} with values @code{20,30}.
3410
3411 In Ada 2005 we can use the extended return statement to build the Ada
3412 equivalent to C++ non-default constructors. For example:
3413
3414 @smallexample @c ada
3415   function Constructor (V : Integer) return Rec2 is
3416   begin
3417      return Obj : Rec2 := (Rec => (Data1  => Constructor (V, 20),
3418                                    others => <>),
3419                            others => <>) do
3420         --  Further actions required for construction of
3421         --  objects of type Rec2
3422         ...
3423      end record;
3424   end Constructor;
3425 @end smallexample
3426
3427 In this example the extended return statement construct is used to
3428 build in place the returned object whose components are initialized
3429 by means of a limited aggregate. Any further action associated with
3430 the constructor can be placed inside the construct.
3431
3432 @node Interfacing with C++ at the Class Level
3433 @subsection Interfacing with C++ at the Class Level
3434 @noindent
3435 In this section we demonstrate the GNAT features for interfacing with
3436 C++ by means of an example making use of Ada 2005 abstract interface
3437 types. This example consists of a classification of animals; classes
3438 have been used to model our main classification of animals, and
3439 interfaces provide support for the management of secondary
3440 classifications. We first demonstrate a case in which the types and
3441 constructors are defined on the C++ side and imported from the Ada
3442 side, and latter the reverse case.
3443
3444 The root of our derivation will be the @code{Animal} class, with a
3445 single private attribute (the @code{Age} of the animal) and two public
3446 primitives to set and get the value of this attribute.
3447
3448 @smallexample
3449 @b{class} Animal @{
3450  @b{public}:
3451    @b{virtual} void Set_Age (int New_Age);
3452    @b{virtual} int Age ();
3453  @b{private}:
3454    int Age_Count;
3455 @};
3456 @end smallexample
3457
3458 Abstract interface types are defined in C++ by means of classes with pure
3459 virtual functions and no data members. In our example we will use two
3460 interfaces that provide support for the common management of @code{Carnivore}
3461 and @code{Domestic} animals:
3462
3463 @smallexample
3464 @b{class} Carnivore @{
3465 @b{public}:
3466    @b{virtual} int Number_Of_Teeth () = 0;
3467 @};
3468
3469 @b{class} Domestic @{
3470 @b{public}:
3471    @b{virtual void} Set_Owner (char* Name) = 0;
3472 @};
3473 @end smallexample
3474
3475 Using these declarations, we can now say that a @code{Dog} is an animal that is
3476 both Carnivore and Domestic, that is:
3477
3478 @smallexample
3479 @b{class} Dog : Animal, Carnivore, Domestic @{
3480  @b{public}:
3481    @b{virtual} int  Number_Of_Teeth ();
3482    @b{virtual} void Set_Owner (char* Name);
3483
3484    Dog(); // Constructor
3485  @b{private}:
3486    int  Tooth_Count;
3487    char *Owner;
3488 @};
3489 @end smallexample
3490
3491 In the following examples we will assume that the previous declarations are
3492 located in a file named @code{animals.h}. The following package demonstrates
3493 how to import these C++ declarations from the Ada side:
3494
3495 @smallexample @c ada
3496 with Interfaces.C.Strings; use Interfaces.C.Strings;
3497 package Animals is
3498   type Carnivore is interface;
3499   pragma Convention (C_Plus_Plus, Carnivore);
3500   function Number_Of_Teeth (X : Carnivore)
3501      return Natural is abstract;
3502
3503   type Domestic is interface;
3504   pragma Convention (C_Plus_Plus, Set_Owner);
3505   procedure Set_Owner
3506     (X    : in out Domestic;
3507      Name : Chars_Ptr) is abstract;
3508
3509   type Animal is tagged record
3510     Age : Natural := 0;
3511   end record;
3512   pragma Import (C_Plus_Plus, Animal);
3513
3514   procedure Set_Age (X : in out Animal; Age : Integer);
3515   pragma Import (C_Plus_Plus, Set_Age);
3516
3517   function Age (X : Animal) return Integer;
3518   pragma Import (C_Plus_Plus, Age);
3519
3520   type Dog is new Animal and Carnivore and Domestic with record
3521     Tooth_Count : Natural;
3522     Owner       : String (1 .. 30);
3523   end record;
3524   pragma Import (C_Plus_Plus, Dog);
3525
3526   function Number_Of_Teeth (A : Dog) return Integer;
3527   pragma Import (C_Plus_Plus, Number_Of_Teeth);
3528
3529   procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3530   pragma Import (C_Plus_Plus, Set_Owner);
3531
3532   function New_Dog return Dog;
3533   pragma CPP_Constructor (New_Dog);
3534   pragma Import (CPP, New_Dog, "_ZN3DogC2Ev");
3535 end Animals;
3536 @end smallexample
3537
3538 Thanks to the compatibility between GNAT run-time structures and the C++ ABI,
3539 interfacing with these C++ classes is easy. The only requirement is that all
3540 the primitives and components must be declared exactly in the same order in
3541 the two languages.
3542
3543 Regarding the abstract interfaces, we must indicate to the GNAT compiler by
3544 means of a @code{pragma Convention (C_Plus_Plus)}, the convention used to pass
3545 the arguments to the called primitives will be the same as for C++. For the
3546 imported classes we use @code{pragma Import} with convention @code{C_Plus_Plus}
3547 to indicate that they have been defined on the C++ side; this is required
3548 because the dispatch table associated with these tagged types will be built
3549 in the C++ side and therefore will not contain the predefined Ada primitives
3550 which Ada would otherwise expect.
3551
3552 As the reader can see there is no need to indicate the C++ mangled names
3553 associated with each subprogram because it is assumed that all the calls to
3554 these primitives will be dispatching calls. The only exception is the
3555 constructor, which must be registered with the compiler by means of
3556 @code{pragma CPP_Constructor} and needs to provide its associated C++
3557 mangled name because the Ada compiler generates direct calls to it.
3558
3559 With the above packages we can now declare objects of type Dog on the Ada side
3560 and dispatch calls to the corresponding subprograms on the C++ side. We can
3561 also extend the tagged type Dog with further fields and primitives, and
3562 override some of its C++ primitives on the Ada side. For example, here we have
3563 a type derivation defined on the Ada side that inherits all the dispatching
3564 primitives of the ancestor from the C++ side.
3565
3566 @smallexample
3567 @b{with} Animals; @b{use} Animals;
3568 @b{package} Vaccinated_Animals @b{is}
3569   @b{type} Vaccinated_Dog @b{is new} Dog @b{with null record};
3570   @b{function} Vaccination_Expired (A : Vaccinated_Dog) @b{return} Boolean;
3571 @b{end} Vaccinated_Animals;
3572 @end smallexample
3573
3574 It is important to note that, because of the ABI compatibility, the programmer
3575 does not need to add any further information to indicate either the object
3576 layout or the dispatch table entry associated with each dispatching operation.
3577
3578 Now let us define all the types and constructors on the Ada side and export
3579 them to C++, using the same hierarchy of our previous example:
3580
3581 @smallexample @c ada
3582 with Interfaces.C.Strings;
3583 use Interfaces.C.Strings;
3584 package Animals is
3585   type Carnivore is interface;
3586   pragma Convention (C_Plus_Plus, Carnivore);
3587   function Number_Of_Teeth (X : Carnivore)
3588      return Natural is abstract;
3589
3590   type Domestic is interface;
3591   pragma Convention (C_Plus_Plus, Set_Owner);
3592   procedure Set_Owner
3593     (X    : in out Domestic;
3594      Name : Chars_Ptr) is abstract;
3595
3596   type Animal is tagged record
3597     Age : Natural := 0;
3598   end record;
3599   pragma Convention (C_Plus_Plus, Animal);
3600
3601   procedure Set_Age (X : in out Animal; Age : Integer);
3602   pragma Export (C_Plus_Plus, Set_Age);
3603
3604   function Age (X : Animal) return Integer;
3605   pragma Export (C_Plus_Plus, Age);
3606
3607   type Dog is new Animal and Carnivore and Domestic with record
3608     Tooth_Count : Natural;
3609     Owner       : String (1 .. 30);
3610   end record;
3611   pragma Convention (C_Plus_Plus, Dog);
3612
3613   function Number_Of_Teeth (A : Dog) return Integer;
3614   pragma Export (C_Plus_Plus, Number_Of_Teeth);
3615
3616   procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3617   pragma Export (C_Plus_Plus, Set_Owner);
3618
3619   function New_Dog return Dog'Class;
3620   pragma Export (C_Plus_Plus, New_Dog);
3621 end Animals;
3622 @end smallexample
3623
3624 Compared with our previous example the only difference is the use of
3625 @code{pragma Export} to indicate to the GNAT compiler that the primitives will
3626 be available to C++. Thanks to the ABI compatibility, on the C++ side there is
3627 nothing else to be done; as explained above, the only requirement is that all
3628 the primitives and components are declared in exactly the same order.
3629
3630 For completeness, let us see a brief C++ main program that uses the
3631 declarations available in @code{animals.h} (presented in our first example) to
3632 import and use the declarations from the Ada side, properly initializing and
3633 finalizing the Ada run-time system along the way:
3634
3635 @smallexample
3636 @b{#include} "animals.h"
3637 @b{#include} <iostream>
3638 @b{using namespace} std;
3639
3640 void Check_Carnivore (Carnivore *obj) @{@dots{}@}
3641 void Check_Domestic (Domestic *obj)   @{@dots{}@}
3642 void Check_Animal (Animal *obj)       @{@dots{}@}
3643 void Check_Dog (Dog *obj)             @{@dots{}@}
3644
3645 @b{extern} "C" @{
3646   void adainit (void);
3647   void adafinal (void);
3648   Dog* new_dog ();
3649 @}
3650
3651 void test ()
3652 @{
3653   Dog *obj = new_dog();  // Ada constructor
3654   Check_Carnivore (obj); // Check secondary DT
3655   Check_Domestic (obj);  // Check secondary DT
3656   Check_Animal (obj);    // Check primary DT
3657   Check_Dog (obj);       // Check primary DT
3658 @}
3659
3660 int main ()
3661 @{
3662   adainit ();  test();  adafinal ();
3663   return 0;
3664 @}
3665 @end smallexample
3666
3667 @node Comparison between GNAT and C/C++ Compilation Models
3668 @section Comparison between GNAT and C/C++ Compilation Models
3669
3670 @noindent
3671 The GNAT model of compilation is close to the C and C++ models. You can
3672 think of Ada specs as corresponding to header files in C. As in C, you
3673 don't need to compile specs; they are compiled when they are used. The
3674 Ada @code{with} is similar in effect to the @code{#include} of a C
3675 header.
3676
3677 One notable difference is that, in Ada, you may compile specs separately
3678 to check them for semantic and syntactic accuracy. This is not always
3679 possible with C headers because they are fragments of programs that have
3680 less specific syntactic or semantic rules.
3681
3682 The other major difference is the requirement for running the binder,
3683 which performs two important functions. First, it checks for
3684 consistency. In C or C++, the only defense against assembling
3685 inconsistent programs lies outside the compiler, in a makefile, for
3686 example. The binder satisfies the Ada requirement that it be impossible
3687 to construct an inconsistent program when the compiler is used in normal
3688 mode.
3689
3690 @cindex Elaboration order control
3691 The other important function of the binder is to deal with elaboration
3692 issues. There are also elaboration issues in C++ that are handled
3693 automatically. This automatic handling has the advantage of being
3694 simpler to use, but the C++ programmer has no control over elaboration.
3695 Where @code{gnatbind} might complain there was no valid order of
3696 elaboration, a C++ compiler would simply construct a program that
3697 malfunctioned at run time.
3698 @end ifclear
3699
3700 @node Comparison between GNAT and Conventional Ada Library Models
3701 @section Comparison between GNAT and Conventional Ada Library Models
3702
3703 @noindent
3704 This section is intended for Ada programmers who have
3705 used an Ada compiler implementing the traditional Ada library
3706 model, as described in the Ada Reference Manual.
3707
3708 @cindex GNAT library
3709 In GNAT, there is no ``library'' in the normal sense. Instead, the set of
3710 source files themselves acts as the library. Compiling Ada programs does
3711 not generate any centralized information, but rather an object file and
3712 a ALI file, which are of interest only to the binder and linker.
3713 In a traditional system, the compiler reads information not only from
3714 the source file being compiled, but also from the centralized library.
3715 This means that the effect of a compilation depends on what has been
3716 previously compiled. In particular:
3717
3718 @itemize @bullet
3719 @item
3720 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3721 to the version of the unit most recently compiled into the library.
3722
3723 @item
3724 Inlining is effective only if the necessary body has already been
3725 compiled into the library.
3726
3727 @item
3728 Compiling a unit may obsolete other units in the library.
3729 @end itemize
3730
3731 @noindent
3732 In GNAT, compiling one unit never affects the compilation of any other
3733 units because the compiler reads only source files. Only changes to source
3734 files can affect the results of a compilation. In particular:
3735
3736 @itemize @bullet
3737 @item
3738 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3739 to the source version of the unit that is currently accessible to the
3740 compiler.
3741
3742 @item
3743 @cindex Inlining
3744 Inlining requires the appropriate source files for the package or
3745 subprogram bodies to be available to the compiler. Inlining is always
3746 effective, independent of the order in which units are complied.
3747
3748 @item
3749 Compiling a unit never affects any other compilations. The editing of
3750 sources may cause previous compilations to be out of date if they
3751 depended on the source file being modified.
3752 @end itemize
3753
3754 @noindent
3755 The most important result of these differences is that order of compilation
3756 is never significant in GNAT. There is no situation in which one is
3757 required to do one compilation before another. What shows up as order of
3758 compilation requirements in the traditional Ada library becomes, in
3759 GNAT, simple source dependencies; in other words, there is only a set
3760 of rules saying what source files must be present when a file is
3761 compiled.
3762
3763 @ifset vms
3764 @node Placement of temporary files
3765 @section Placement of temporary files
3766 @cindex Temporary files (user control over placement)
3767
3768 @noindent
3769 GNAT creates temporary files in the directory designated by the environment
3770 variable @env{TMPDIR}.
3771 (See the HP @emph{C RTL Reference Manual} on the function @code{getenv()}
3772 for detailed information on how environment variables are resolved.
3773 For most users the easiest way to make use of this feature is to simply
3774 define @env{TMPDIR} as a job level logical name).
3775 For example, if you wish to use a Ramdisk (assuming DECRAM is installed)
3776 for compiler temporary files, then you can include something like the
3777 following command in your @file{LOGIN.COM} file:
3778
3779 @smallexample
3780 $ define/job TMPDIR "/disk$scratchram/000000/temp/"
3781 @end smallexample
3782
3783 @noindent
3784 If @env{TMPDIR} is not defined, then GNAT uses the directory designated by
3785 @env{TMP}; if @env{TMP} is not defined, then GNAT uses the directory
3786 designated by @env{TEMP}.
3787 If none of these environment variables are defined then GNAT uses the
3788 directory designated by the logical name @code{SYS$SCRATCH:}
3789 (by default the user's home directory). If all else fails
3790 GNAT uses the current directory for temporary files.
3791 @end ifset
3792
3793 @c *************************
3794 @node Compiling Using gcc
3795 @chapter Compiling Using @command{gcc}
3796
3797 @noindent
3798 This chapter discusses how to compile Ada programs using the @command{gcc}
3799 command. It also describes the set of switches
3800 that can be used to control the behavior of the compiler.
3801 @menu
3802 * Compiling Programs::
3803 * Switches for gcc::
3804 * Search Paths and the Run-Time Library (RTL)::
3805 * Order of Compilation Issues::
3806 * Examples::
3807 @end menu
3808
3809 @node Compiling Programs
3810 @section Compiling Programs
3811
3812 @noindent
3813 The first step in creating an executable program is to compile the units
3814 of the program using the @command{gcc} command. You must compile the
3815 following files:
3816
3817 @itemize @bullet
3818 @item
3819 the body file (@file{.adb}) for a library level subprogram or generic
3820 subprogram
3821
3822 @item
3823 the spec file (@file{.ads}) for a library level package or generic
3824 package that has no body
3825
3826 @item
3827 the body file (@file{.adb}) for a library level package
3828 or generic package that has a body
3829
3830 @end itemize
3831
3832 @noindent
3833 You need @emph{not} compile the following files
3834
3835 @itemize @bullet
3836
3837 @item
3838 the spec of a library unit which has a body
3839
3840 @item
3841 subunits
3842 @end itemize
3843
3844 @noindent
3845 because they are compiled as part of compiling related units. GNAT
3846 package specs
3847 when the corresponding body is compiled, and subunits when the parent is
3848 compiled.
3849
3850 @cindex cannot generate code
3851 If you attempt to compile any of these files, you will get one of the
3852 following error messages (where @var{fff} is the name of the file you compiled):
3853
3854 @smallexample
3855 cannot generate code for file @var{fff} (package spec)
3856 to check package spec, use -gnatc
3857
3858 cannot generate code for file @var{fff} (missing subunits)
3859 to check parent unit, use -gnatc
3860
3861 cannot generate code for file @var{fff} (subprogram spec)
3862 to check subprogram spec, use -gnatc
3863
3864 cannot generate code for file @var{fff} (subunit)
3865 to check subunit, use -gnatc
3866 @end smallexample
3867
3868 @noindent
3869 As indicated by the above error messages, if you want to submit
3870 one of these files to the compiler to check for correct semantics
3871 without generating code, then use the @option{-gnatc} switch.
3872
3873 The basic command for compiling a file containing an Ada unit is
3874
3875 @smallexample
3876 $ gcc -c @ovar{switches} @file{file name}
3877 @end smallexample
3878
3879 @noindent
3880 where @var{file name} is the name of the Ada file (usually
3881 having an extension
3882 @file{.ads} for a spec or @file{.adb} for a body).
3883 @ifclear vms
3884 You specify the
3885 @option{-c} switch to tell @command{gcc} to compile, but not link, the file.
3886 @end ifclear
3887 The result of a successful compilation is an object file, which has the
3888 same name as the source file but an extension of @file{.o} and an Ada
3889 Library Information (ALI) file, which also has the same name as the
3890 source file, but with @file{.ali} as the extension. GNAT creates these
3891 two output files in the current directory, but you may specify a source
3892 file in any directory using an absolute or relative path specification
3893 containing the directory information.
3894
3895 @findex gnat1
3896 @command{gcc} is actually a driver program that looks at the extensions of
3897 the file arguments and loads the appropriate compiler. For example, the
3898 GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}.
3899 These programs are in directories known to the driver program (in some
3900 configurations via environment variables you set), but need not be in
3901 your path. The @command{gcc} driver also calls the assembler and any other
3902 utilities needed to complete the generation of the required object
3903 files.
3904
3905 It is possible to supply several file names on the same @command{gcc}
3906 command. This causes @command{gcc} to call the appropriate compiler for
3907 each file. For example, the following command lists three separate
3908 files to be compiled:
3909
3910 @smallexample
3911 $ gcc -c x.adb y.adb z.c
3912 @end smallexample
3913
3914 @noindent
3915 calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and
3916 @file{y.adb}, and @code{cc1} (the C compiler) once to compile @file{z.c}.
3917 The compiler generates three object files @file{x.o}, @file{y.o} and
3918 @file{z.o} and the two ALI files @file{x.ali} and @file{y.ali} from the
3919 Ada compilations. Any switches apply to all the files ^listed,^listed.^
3920 @ifclear vms
3921 except for
3922 @option{-gnat@var{x}} switches, which apply only to Ada compilations.
3923 @end ifclear
3924
3925 @node Switches for gcc
3926 @section Switches for @command{gcc}
3927
3928 @noindent
3929 The @command{gcc} command accepts switches that control the
3930 compilation process. These switches are fully described in this section.
3931 First we briefly list all the switches, in alphabetical order, then we
3932 describe the switches in more detail in functionally grouped sections.
3933
3934 More switches exist for GCC than those documented here, especially
3935 for specific targets. However, their use is not recommended as
3936 they may change code generation in ways that are incompatible with
3937 the Ada run-time library, or can cause inconsistencies between
3938 compilation units.
3939
3940 @menu
3941 * Output and Error Message Control::
3942 * Warning Message Control::
3943 * Debugging and Assertion Control::
3944 * Validity Checking::
3945 * Style Checking::
3946 * Run-Time Checks::
3947 * Using gcc for Syntax Checking::
3948 * Using gcc for Semantic Checking::
3949 * Compiling Different Versions of Ada::
3950 * Character Set Control::
3951 * File Naming Control::
3952 * Subprogram Inlining Control::
3953 * Auxiliary Output Control::
3954 * Debugging Control::
3955 * Exception Handling Control::
3956 * Units to Sources Mapping Files::
3957 * Integrated Preprocessing::
3958 * Code Generation Control::
3959 @ifset vms
3960 * Return Codes::
3961 @end ifset
3962 @end menu
3963
3964 @table @option
3965 @c !sort!
3966 @ifclear vms
3967 @cindex @option{-b} (@command{gcc})
3968 @item -b @var{target}
3969 Compile your program to run on @var{target}, which is the name of a
3970 system configuration. You must have a GNAT cross-compiler built if
3971 @var{target} is not the same as your host system.
3972
3973 @item -B@var{dir}
3974 @cindex @option{-B} (@command{gcc})
3975 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
3976 from @var{dir} instead of the default location. Only use this switch
3977 when multiple versions of the GNAT compiler are available.
3978 @xref{Directory Options,, Options for Directory Search, gcc, Using the
3979 GNU Compiler Collection (GCC)}, for further details. You would normally
3980 use the @option{-b} or @option{-V} switch instead.
3981
3982 @item -c
3983 @cindex @option{-c} (@command{gcc})
3984 Compile. Always use this switch when compiling Ada programs.
3985
3986 Note: for some other languages when using @command{gcc}, notably in
3987 the case of C and C++, it is possible to use
3988 use @command{gcc} without a @option{-c} switch to
3989 compile and link in one step. In the case of GNAT, you
3990 cannot use this approach, because the binder must be run
3991 and @command{gcc} cannot be used to run the GNAT binder.
3992 @end ifclear
3993
3994 @item -fno-inline
3995 @cindex @option{-fno-inline} (@command{gcc})
3996 Suppresses all back-end inlining, even if other optimization or inlining
3997 switches are set.
3998 This includes suppression of inlining that results
3999 from the use of the pragma @code{Inline_Always}.
4000 Any occurrences of pragma @code{Inline} or @code{Inline_Always}
4001 are ignored, and @option{-gnatn} and @option{-gnatN} have no
4002 effect if this switch is present.
4003
4004 @item -fno-inline-functions
4005 @cindex @option{-fno-inline-functions} (@command{gcc})
4006 Suppresses automatic inlining of simple subprograms, which is enabled
4007 if @option{-O3} is used.
4008
4009 @item -fno-inline-small-functions
4010 @cindex @option{-fno-inline-small-functions} (@command{gcc})
4011 Suppresses automatic inlining of small subprograms, which is enabled
4012 if @option{-O2} is used.
4013
4014 @item -fno-inline-functions-called-once
4015 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
4016 Suppresses inlining of subprograms local to the unit and called once
4017 from within it, which is enabled if @option{-O1} is used.
4018
4019 @item -fno-ivopts
4020 @cindex @option{-fno-ivopts} (@command{gcc})
4021 Suppresses high-level loop induction variable optimizations, which are
4022 enabled if @option{-O1} is used. These optimizations are generally
4023 profitable but, for some specific cases of loops with numerous uses
4024 of the iteration variable that follow a common pattern, they may end
4025 up destroying the regularity that could be exploited at a lower level
4026 and thus producing inferior code.
4027
4028 @item -fno-strict-aliasing
4029 @cindex @option{-fno-strict-aliasing} (@command{gcc})
4030 Causes the compiler to avoid assumptions regarding non-aliasing
4031 of objects of different types. See
4032 @ref{Optimization and Strict Aliasing} for details.
4033
4034 @item -fstack-check
4035 @cindex @option{-fstack-check} (@command{gcc})
4036 Activates stack checking.
4037 See @ref{Stack Overflow Checking} for details.
4038
4039 @item -fstack-usage
4040 @cindex @option{-fstack-usage} (@command{gcc})
4041 Makes the compiler output stack usage information for the program, on a
4042 per-function basis. See @ref{Static Stack Usage Analysis} for details.
4043
4044 @item -fcallgraph-info@r{[}=su@r{]}
4045 @cindex @option{-fcallgraph-info} (@command{gcc})
4046 Makes the compiler output callgraph information for the program, on a
4047 per-file basis.  The information is generated in the VCG format.  It can
4048 be decorated with stack-usage per-node information.
4049
4050 @item ^-g^/DEBUG^
4051 @cindex @option{^-g^/DEBUG^} (@command{gcc})
4052 Generate debugging information. This information is stored in the object
4053 file and copied from there to the final executable file by the linker,
4054 where it can be read by the debugger. You must use the
4055 @option{^-g^/DEBUG^} switch if you plan on using the debugger.
4056
4057 @item -gnat83
4058 @cindex @option{-gnat83} (@command{gcc})
4059 Enforce Ada 83 restrictions.
4060
4061 @item -gnat95
4062 @cindex @option{-gnat95} (@command{gcc})
4063 Enforce Ada 95 restrictions.
4064
4065 @item -gnat05
4066 @cindex @option{-gnat05} (@command{gcc})
4067 Allow full Ada 2005 features.
4068
4069 @item -gnata
4070 @cindex @option{-gnata} (@command{gcc})
4071 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
4072 activated. Note that these pragmas can also be controlled using the
4073 configuration pragmas @code{Assertion_Policy} and @code{Debug_Policy}.
4074 It also activates pragmas @code{Check}, @code{Precondition}, and
4075 @code{Postcondition}. Note that these pragmas can also be controlled
4076 using the configuration pragma @code{Check_Policy}.
4077
4078 @item -gnatA
4079 @cindex @option{-gnatA} (@command{gcc})
4080 Avoid processing @file{gnat.adc}. If a @file{gnat.adc} file is present,
4081 it will be ignored.
4082
4083 @item -gnatb
4084 @cindex @option{-gnatb} (@command{gcc})
4085 Generate brief messages to @file{stderr} even if verbose mode set.
4086
4087 @item -gnatB
4088 @cindex @option{-gnatB} (@command{gcc})
4089 Assume no invalid (bad) values except for 'Valid attribute use
4090 (@pxref{Validity Checking}).
4091
4092 @item -gnatc
4093 @cindex @option{-gnatc} (@command{gcc})
4094 Check syntax and semantics only (no code generation attempted).
4095
4096 @item -gnatC
4097 @cindex @option{-gnatC} (@command{gcc})
4098 Generate CodePeer information (no code generation attempted).
4099 This switch will generate an intermediate representation suitable for
4100 use by CodePeer (@file{.scil} files). This switch is not compatible with
4101 code generation (it will, among other things, disable some switches such
4102 as -gnatn, and enable others such as -gnata).
4103
4104 @item -gnatd
4105 @cindex @option{-gnatd} (@command{gcc})
4106 Specify debug options for the compiler. The string of characters after
4107 the @option{-gnatd} specify the specific debug options. The possible
4108 characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
4109 compiler source file @file{debug.adb} for details of the implemented
4110 debug options. Certain debug options are relevant to applications
4111 programmers, and these are documented at appropriate points in this
4112 users guide.
4113
4114 @ifclear vms
4115 @item -gnatD
4116 @cindex @option{-gnatD[nn]} (@command{gcc})
4117 @end ifclear
4118 @ifset vms
4119 @item /XDEBUG /LXDEBUG=nnn
4120 @end ifset
4121 Create expanded source files for source level debugging. This switch
4122 also suppress generation of cross-reference information
4123 (see @option{-gnatx}).
4124
4125 @item -gnatec=@var{path}
4126 @cindex @option{-gnatec} (@command{gcc})
4127 Specify a configuration pragma file
4128 @ifclear vms
4129 (the equal sign is optional)
4130 @end ifclear
4131 (@pxref{The Configuration Pragmas Files}).
4132
4133 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=@var{value}@r{]}
4134 @cindex @option{-gnateD} (@command{gcc})
4135 Defines a symbol, associated with @var{value}, for preprocessing.
4136 (@pxref{Integrated Preprocessing}).
4137
4138 @item -gnatef
4139 @cindex @option{-gnatef} (@command{gcc})
4140 Display full source path name in brief error messages.
4141
4142 @item -gnateG
4143 @cindex @option{-gnateG} (@command{gcc})
4144 Save result of preprocessing in a text file.
4145
4146 @item -gnatem=@var{path}
4147 @cindex @option{-gnatem} (@command{gcc})
4148 Specify a mapping file
4149 @ifclear vms
4150 (the equal sign is optional)
4151 @end ifclear
4152 (@pxref{Units to Sources Mapping Files}).
4153
4154 @item -gnatep=@var{file}
4155 @cindex @option{-gnatep} (@command{gcc})
4156 Specify a preprocessing data file
4157 @ifclear vms
4158 (the equal sign is optional)
4159 @end ifclear
4160 (@pxref{Integrated Preprocessing}).
4161
4162 @item -gnateS
4163 @cindex @option{-gnateS} (@command{gcc})
4164 Generate SCO (Source Coverage Obligation) information in the ALI
4165 file. This information is used by advanced coverage tools. See
4166 unit @file{SCOs} in the compiler sources for details in files
4167 @file{scos.ads} and @file{scos.adb}.
4168
4169 @item -gnatE
4170 @cindex @option{-gnatE} (@command{gcc})
4171 Full dynamic elaboration checks.
4172
4173 @item -gnatf
4174 @cindex @option{-gnatf} (@command{gcc})
4175 Full errors. Multiple errors per line, all undefined references, do not
4176 attempt to suppress cascaded errors.
4177
4178 @item -gnatF
4179 @cindex @option{-gnatF} (@command{gcc})
4180 Externals names are folded to all uppercase.
4181
4182 @item ^-gnatg^/GNAT_INTERNAL^
4183 @cindex @option{^-gnatg^/GNAT_INTERNAL^} (@command{gcc})
4184 Internal GNAT implementation mode. This should not be used for
4185 applications programs, it is intended only for use by the compiler
4186 and its run-time library. For documentation, see the GNAT sources.
4187 Note that @option{^-gnatg^/GNAT_INTERNAL^} implies
4188 @option{^-gnatwae^/WARNINGS=ALL,ERRORS^} and
4189 @option{^-gnatyg^/STYLE_CHECKS=GNAT^}
4190 so that all standard warnings and all standard style options are turned on.
4191 All warnings and style error messages are treated as errors.
4192
4193 @ifclear vms
4194 @item -gnatG=nn
4195 @cindex @option{-gnatG[nn]} (@command{gcc})
4196 @end ifclear
4197 @ifset vms
4198 @item /EXPAND_SOURCE, /LEXPAND_SOURCE=nnn
4199 @end ifset
4200 List generated expanded code in source form.
4201
4202 @item ^-gnath^/HELP^
4203 @cindex @option{^-gnath^/HELP^} (@command{gcc})
4204 Output usage information. The output is written to @file{stdout}.
4205
4206 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
4207 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
4208 Identifier character set
4209 @ifclear vms
4210 (@var{c}=1/2/3/4/8/9/p/f/n/w).
4211 @end ifclear
4212 For details of the possible selections for @var{c},
4213 see @ref{Character Set Control}.
4214
4215 @item ^-gnatI^/IGNORE_REP_CLAUSES^
4216 @cindex @option{^-gnatI^IGNORE_REP_CLAUSES^} (@command{gcc})
4217 Ignore representation clauses. When this switch is used,
4218 representation clauses are treated as comments. This is useful
4219 when initially porting code where you want to ignore rep clause
4220 problems, and also for compiling foreign code (particularly
4221 for use with ASIS). The representation clauses that are ignored
4222 are: enumeration_representation_clause, record_representation_clause,
4223 and attribute_definition_clause for the following attributes:
4224 Address, Alignment, Bit_Order, Component_Size, Machine_Radix,
4225 Object_Size, Size, Small, Stream_Size, and Value_Size.
4226 Note that this option should be used only for compiling -- the
4227 code is likely to malfunction at run time.
4228
4229 @item -gnatjnn
4230 @cindex @option{-gnatjnn} (@command{gcc})
4231 Reformat error messages to fit on nn character lines
4232
4233 @item -gnatk=@var{n}
4234 @cindex @option{-gnatk} (@command{gcc})
4235 Limit file names to @var{n} (1-999) characters ^(@code{k} = krunch)^^.
4236
4237 @item -gnatl
4238 @cindex @option{-gnatl} (@command{gcc})
4239 Output full source listing with embedded error messages.
4240
4241 @item -gnatL
4242 @cindex @option{-gnatL} (@command{gcc})
4243 Used in conjunction with -gnatG or -gnatD to intersperse original
4244 source lines (as comment lines with line numbers) in the expanded
4245 source output.
4246
4247 @item -gnatm=@var{n}
4248 @cindex @option{-gnatm} (@command{gcc})
4249 Limit number of detected error or warning messages to @var{n}
4250 where @var{n} is in the range 1..999999. The default setting if
4251 no switch is given is 9999. If the number of warnings reaches this
4252 limit, then a message is output and further warnings are suppressed,
4253 but the compilation is continued. If the number of error messages
4254 reaches this limit, then a message is output and the compilation
4255 is abandoned. The equal sign here is optional. A value of zero
4256 means that no limit applies.
4257
4258 @item -gnatn
4259 @cindex @option{-gnatn} (@command{gcc})
4260 Activate inlining for subprograms for which
4261 pragma @code{inline} is specified. This inlining is performed
4262 by the GCC back-end.
4263
4264 @item -gnatN
4265 @cindex @option{-gnatN} (@command{gcc})
4266 Activate front end inlining for subprograms for which
4267 pragma @code{Inline} is specified. This inlining is performed
4268 by the front end and will be visible in the
4269 @option{-gnatG} output.
4270
4271 When using a gcc-based back end (in practice this means using any version
4272 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
4273 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
4274 Historically front end inlining was more extensive than the gcc back end
4275 inlining, but that is no longer the case.
4276
4277 @item -gnato
4278 @cindex @option{-gnato} (@command{gcc})
4279 Enable numeric overflow checking (which is not normally enabled by
4280 default). Note that division by zero is a separate check that is not
4281 controlled by this switch (division by zero checking is on by default).
4282
4283 @item -gnatp
4284 @cindex @option{-gnatp} (@command{gcc})
4285 Suppress all checks. See @ref{Run-Time Checks} for details.
4286
4287 @item -gnatP
4288 @cindex @option{-gnatP} (@command{gcc})
4289 Enable polling. This is required on some systems (notably Windows NT) to
4290 obtain asynchronous abort and asynchronous transfer of control capability.
4291 @xref{Pragma Polling,,, gnat_rm, GNAT Reference Manual}, for full
4292 details.
4293
4294 @item -gnatq
4295 @cindex @option{-gnatq} (@command{gcc})
4296 Don't quit. Try semantics, even if parse errors.
4297
4298 @item -gnatQ
4299 @cindex @option{-gnatQ} (@command{gcc})
4300 Don't quit. Generate @file{ALI} and tree files even if illegalities.
4301
4302 @item -gnatr
4303 @cindex @option{-gnatr} (@command{gcc})
4304 Treat pragma Restrictions as Restriction_Warnings.
4305
4306 @item ^-gnatR@r{[}0@r{/}1@r{/}2@r{/}3@r{[}s@r{]]}^/REPRESENTATION_INFO^
4307 @cindex @option{-gnatR} (@command{gcc})
4308 Output representation information for declared types and objects.
4309
4310 @item -gnats
4311 @cindex @option{-gnats} (@command{gcc})
4312 Syntax check only.
4313
4314 @item -gnatS
4315 @cindex @option{-gnatS} (@command{gcc})
4316 Print package Standard.
4317
4318 @item -gnatt
4319 @cindex @option{-gnatt} (@command{gcc})
4320 Generate tree output file.
4321
4322 @item ^-gnatT^/TABLE_MULTIPLIER=^@var{nnn}
4323 @cindex @option{^-gnatT^/TABLE_MULTIPLIER^} (@command{gcc})
4324 All compiler tables start at @var{nnn} times usual starting size.
4325
4326 @item -gnatu
4327 @cindex @option{-gnatu} (@command{gcc})
4328 List units for this compilation.
4329
4330 @item -gnatU
4331 @cindex @option{-gnatU} (@command{gcc})
4332 Tag all error messages with the unique string ``error:''
4333
4334 @item -gnatv
4335 @cindex @option{-gnatv} (@command{gcc})
4336 Verbose mode. Full error output with source lines to @file{stdout}.
4337
4338 @item -gnatV
4339 @cindex @option{-gnatV} (@command{gcc})
4340 Control level of validity checking (@pxref{Validity Checking}).
4341
4342 @item ^-gnatw@var{xxx}^/WARNINGS=(@var{option}@r{[},@dots{}@r{]})^
4343 @cindex @option{^-gnatw^/WARNINGS^} (@command{gcc})
4344 Warning mode where
4345 ^@var{xxx} is a string of option letters that^the list of options^ denotes
4346 the exact warnings that
4347 are enabled or disabled (@pxref{Warning Message Control}).
4348
4349 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
4350 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
4351 Wide character encoding method
4352 @ifclear vms
4353 (@var{e}=n/h/u/s/e/8).
4354 @end ifclear
4355 @ifset vms
4356 (@var{e}=@code{BRACKETS, NONE, HEX, UPPER, SHIFT_JIS, EUC, UTF8})
4357 @end ifset
4358
4359 @item -gnatx
4360 @cindex @option{-gnatx} (@command{gcc})
4361 Suppress generation of cross-reference information.
4362
4363 @item ^-gnaty^/STYLE_CHECKS=(option,option@dots{})^
4364 @cindex @option{^-gnaty^/STYLE_CHECKS^} (@command{gcc})
4365 Enable built-in style checks (@pxref{Style Checking}).
4366
4367 @item ^-gnatz^/DISTRIBUTION_STUBS=^@var{m}
4368 @cindex @option{^-gnatz^/DISTRIBUTION_STUBS^} (@command{gcc})
4369 Distribution stub generation and compilation
4370 @ifclear vms
4371 (@var{m}=r/c for receiver/caller stubs).
4372 @end ifclear
4373 @ifset vms
4374 (@var{m}=@code{RECEIVER} or @code{CALLER} to specify the type of stubs
4375 to be generated and compiled).
4376 @end ifset
4377
4378 @item ^-I^/SEARCH=^@var{dir}
4379 @cindex @option{^-I^/SEARCH^} (@command{gcc})
4380 @cindex RTL
4381 Direct GNAT to search the @var{dir} directory for source files needed by
4382 the current compilation
4383 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4384
4385 @item ^-I-^/NOCURRENT_DIRECTORY^
4386 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gcc})
4387 @cindex RTL
4388 Except for the source file named in the command line, do not look for source
4389 files in the directory containing the source file named in the command line
4390 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4391
4392 @ifclear vms
4393 @item -mbig-switch
4394 @cindex @option{-mbig-switch} (@command{gcc})
4395 @cindex @code{case} statement (effect of @option{-mbig-switch} option)
4396 This standard gcc switch causes the compiler to use larger offsets in its
4397 jump table representation for @code{case} statements.
4398 This may result in less efficient code, but is sometimes necessary
4399 (for example on HP-UX targets)
4400 @cindex HP-UX and @option{-mbig-switch} option
4401 in order to compile large and/or nested @code{case} statements.
4402
4403 @item -o @var{file}
4404 @cindex @option{-o} (@command{gcc})
4405 This switch is used in @command{gcc} to redirect the generated object file
4406 and its associated ALI file. Beware of this switch with GNAT, because it may
4407 cause the object file and ALI file to have different names which in turn
4408 may confuse the binder and the linker.
4409 @end ifclear
4410
4411 @item -nostdinc
4412 @cindex @option{-nostdinc} (@command{gcc})
4413 Inhibit the search of the default location for the GNAT Run Time
4414 Library (RTL) source files.
4415
4416 @item -nostdlib
4417 @cindex @option{-nostdlib} (@command{gcc})
4418 Inhibit the search of the default location for the GNAT Run Time
4419 Library (RTL) ALI files.
4420
4421 @ifclear vms
4422 @item -O@ovar{n}
4423 @cindex @option{-O} (@command{gcc})
4424 @var{n} controls the optimization level.
4425
4426 @table @asis
4427 @item n = 0
4428 No optimization, the default setting if no @option{-O} appears
4429
4430 @item n = 1
4431 Normal optimization, the default if you specify @option{-O} without
4432 an operand. A good compromise between code quality and compilation
4433 time.
4434
4435 @item n = 2
4436 Extensive optimization, may improve execution time, possibly at the cost of
4437 substantially increased compilation time.
4438
4439 @item n = 3
4440 Same as @option{-O2}, and also includes inline expansion for small subprograms
4441 in the same unit.
4442
4443 @item n = s
4444 Optimize space usage
4445 @end table
4446
4447 @noindent
4448 See also @ref{Optimization Levels}.
4449 @end ifclear
4450
4451 @ifset vms
4452 @item  /NOOPTIMIZE
4453 @cindex @option{/NOOPTIMIZE} (@code{GNAT COMPILE})
4454 Equivalent to @option{/OPTIMIZE=NONE}.
4455 This is the default behavior in the absence of an @option{/OPTIMIZE}
4456 qualifier.
4457
4458 @item /OPTIMIZE@r{[}=(keyword@r{[},@dots{}@r{]})@r{]}
4459 @cindex @option{/OPTIMIZE} (@code{GNAT COMPILE})
4460 Selects the level of optimization for your program. The supported
4461 keywords are as follows:
4462 @table @code
4463 @item   ALL
4464 Perform most optimizations, including those that
4465 are expensive.
4466 This is the default if the @option{/OPTIMIZE} qualifier is supplied
4467 without keyword options.
4468
4469 @item   NONE
4470 Do not do any optimizations. Same as @code{/NOOPTIMIZE}.
4471
4472 @item SOME
4473 Perform some optimizations, but omit ones that are costly.
4474
4475 @item   DEVELOPMENT
4476 Same as @code{SOME}.
4477
4478 @item INLINING
4479 Full optimization as in @option{/OPTIMIZE=ALL}, and also attempts
4480 automatic inlining of small subprograms within a unit
4481
4482 @item   UNROLL_LOOPS
4483 Try to unroll loops. This keyword may be specified together with
4484 any keyword above other than @code{NONE}. Loop unrolling
4485 usually, but not always, improves the performance of programs.
4486
4487 @item SPACE
4488 Optimize space usage
4489 @end table
4490
4491 @noindent
4492 See also @ref{Optimization Levels}.
4493 @end ifset
4494
4495 @ifclear vms
4496 @item -pass-exit-codes
4497 @cindex @option{-pass-exit-codes} (@command{gcc})
4498 Catch exit codes from the compiler and use the most meaningful as
4499 exit status.
4500 @end ifclear
4501
4502 @item --RTS=@var{rts-path}
4503 @cindex @option{--RTS} (@command{gcc})
4504 Specifies the default location of the runtime library. Same meaning as the
4505 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
4506
4507 @item ^-S^/ASM^
4508 @cindex @option{^-S^/ASM^} (@command{gcc})
4509 ^Used in place of @option{-c} to^Used to^
4510 cause the assembler source file to be
4511 generated, using @file{^.s^.S^} as the extension,
4512 instead of the object file.
4513 This may be useful if you need to examine the generated assembly code.
4514
4515 @item ^-fverbose-asm^/VERBOSE_ASM^
4516 @cindex @option{^-fverbose-asm^/VERBOSE_ASM^} (@command{gcc})
4517 ^Used in conjunction with @option{-S}^Used in place of @option{/ASM}^
4518 to cause the generated assembly code file to be annotated with variable
4519 names, making it significantly easier to follow.
4520
4521 @item ^-v^/VERBOSE^
4522 @cindex @option{^-v^/VERBOSE^} (@command{gcc})
4523 Show commands generated by the @command{gcc} driver. Normally used only for
4524 debugging purposes or if you need to be sure what version of the
4525 compiler you are executing.
4526
4527 @ifclear vms
4528 @item -V @var{ver}
4529 @cindex @option{-V} (@command{gcc})
4530 Execute @var{ver} version of the compiler. This is the @command{gcc}
4531 version, not the GNAT version.
4532 @end ifclear
4533
4534 @item ^-w^/NO_BACK_END_WARNINGS^
4535 @cindex @option{-w} (@command{gcc})
4536 Turn off warnings generated by the back end of the compiler. Use of
4537 this switch also causes the default for front end warnings to be set
4538 to suppress (as though @option{-gnatws} had appeared at the start of
4539 the options).
4540
4541 @end table
4542
4543 @ifclear vms
4544 @c Combining qualifiers does not work on VMS
4545 You may combine a sequence of GNAT switches into a single switch. For
4546 example, the combined switch
4547
4548 @cindex Combining GNAT switches
4549 @smallexample
4550 -gnatofi3
4551 @end smallexample
4552
4553 @noindent
4554 is equivalent to specifying the following sequence of switches:
4555
4556 @smallexample
4557 -gnato -gnatf -gnati3
4558 @end smallexample
4559 @end ifclear
4560
4561 @noindent
4562 The following restrictions apply to the combination of switches
4563 in this manner:
4564
4565 @itemize @bullet
4566 @item
4567 The switch @option{-gnatc} if combined with other switches must come
4568 first in the string.
4569
4570 @item
4571 The switch @option{-gnats} if combined with other switches must come
4572 first in the string.
4573
4574 @item
4575 The switches
4576 ^^@option{/DISTRIBUTION_STUBS=},^
4577 @option{-gnatzc} and @option{-gnatzr} may not be combined with any other
4578 switches, and only one of them may appear in the command line.
4579
4580 @ifclear vms
4581 @item
4582 Once a ``y'' appears in the string (that is a use of the @option{-gnaty}
4583 switch), then all further characters in the switch are interpreted
4584 as style modifiers (see description of @option{-gnaty}).
4585
4586 @item
4587 Once a ``d'' appears in the string (that is a use of the @option{-gnatd}
4588 switch), then all further characters in the switch are interpreted
4589 as debug flags (see description of @option{-gnatd}).
4590
4591 @item
4592 Once a ``w'' appears in the string (that is a use of the @option{-gnatw}
4593 switch), then all further characters in the switch are interpreted
4594 as warning mode modifiers (see description of @option{-gnatw}).
4595
4596 @item
4597 Once a ``V'' appears in the string (that is a use of the @option{-gnatV}
4598 switch), then all further characters in the switch are interpreted
4599 as validity checking options (@pxref{Validity Checking}).
4600
4601 @item
4602 Option ``em'', ``ec'', ``ep'', ``l='' and ``R'' must be the last options in
4603 a combined list of options.
4604 @end ifclear
4605 @end itemize
4606
4607 @node Output and Error Message Control
4608 @subsection Output and Error Message Control
4609 @findex stderr
4610
4611 @noindent
4612 The standard default format for error messages is called ``brief format''.
4613 Brief format messages are written to @file{stderr} (the standard error
4614 file) and have the following form:
4615
4616 @smallexample
4617 e.adb:3:04: Incorrect spelling of keyword "function"
4618 e.adb:4:20: ";" should be "is"
4619 @end smallexample
4620
4621 @noindent
4622 The first integer after the file name is the line number in the file,
4623 and the second integer is the column number within the line.
4624 @ifclear vms
4625 @code{GPS} can parse the error messages
4626 and point to the referenced character.
4627 @end ifclear
4628 The following switches provide control over the error message
4629 format:
4630
4631 @table @option
4632 @c !sort!
4633 @item -gnatv
4634 @cindex @option{-gnatv} (@command{gcc})
4635 @findex stdout
4636 @ifclear vms
4637 The v stands for verbose.
4638 @end ifclear
4639 The effect of this setting is to write long-format error
4640 messages to @file{stdout} (the standard output file.
4641 The same program compiled with the
4642 @option{-gnatv} switch would generate:
4643
4644 @smallexample
4645 @cartouche
4646 3. funcion X (Q : Integer)
4647    |
4648 >>> Incorrect spelling of keyword "function"
4649 4. return Integer;
4650                  |
4651 >>> ";" should be "is"
4652 @end cartouche
4653 @end smallexample
4654
4655 @noindent
4656 The vertical bar indicates the location of the error, and the @samp{>>>}
4657 prefix can be used to search for error messages. When this switch is
4658 used the only source lines output are those with errors.
4659
4660 @item -gnatl
4661 @cindex @option{-gnatl} (@command{gcc})
4662 @ifclear vms
4663 The @code{l} stands for list.
4664 @end ifclear
4665 This switch causes a full listing of
4666 the file to be generated. In the case where a body is
4667 compiled, the corresponding spec is also listed, along
4668 with any subunits. Typical output from compiling a package
4669 body @file{p.adb} might look like:
4670
4671 @smallexample @c ada
4672 @cartouche
4673  Compiling: p.adb
4674
4675      1. package body p is
4676      2.    procedure a;
4677      3.    procedure a is separate;
4678      4. begin
4679      5.    null
4680                |
4681         >>> missing ";"
4682
4683      6. end;
4684
4685 Compiling: p.ads
4686
4687      1. package p is
4688      2.    pragma Elaborate_Body
4689                                 |
4690         >>> missing ";"
4691
4692      3. end p;
4693
4694 Compiling: p-a.adb
4695
4696      1. separate p
4697                 |
4698         >>> missing "("
4699
4700      2. procedure a is
4701      3. begin
4702      4.    null
4703                |
4704         >>> missing ";"
4705
4706      5. end;
4707 @end cartouche
4708 @end smallexample
4709
4710 @noindent
4711 @findex stderr
4712 When you specify the @option{-gnatv} or @option{-gnatl} switches and
4713 standard output is redirected, a brief summary is written to
4714 @file{stderr} (standard error) giving the number of error messages and
4715 warning messages generated.
4716
4717 @item -^gnatl^OUTPUT_FILE^=file
4718 @cindex @option{^-gnatl^OUTPUT_FILE^=fname} (@command{gcc})
4719 This has the same effect as @option{-gnatl} except that the output is
4720 written to a file instead of to standard output. If the given name
4721 @file{fname} does not start with a period, then it is the full name
4722 of the file to be written. If @file{fname} is an extension, it is
4723 appended to the name of the file being compiled. For example, if
4724 file @file{xyz.adb} is compiled with @option{^-gnatl^OUTPUT_FILE^=.lst},
4725 then the output is written to file ^xyz.adb.lst^xyz.adb_lst^.
4726
4727 @item -gnatU
4728 @cindex @option{-gnatU} (@command{gcc})
4729 This switch forces all error messages to be preceded by the unique
4730 string ``error:''. This means that error messages take a few more
4731 characters in space, but allows easy searching for and identification
4732 of error messages.
4733
4734 @item -gnatb
4735 @cindex @option{-gnatb} (@command{gcc})
4736 @ifclear vms
4737 The @code{b} stands for brief.
4738 @end ifclear
4739 This switch causes GNAT to generate the
4740 brief format error messages to @file{stderr} (the standard error
4741 file) as well as the verbose
4742 format message or full listing (which as usual is written to
4743 @file{stdout} (the standard output file).
4744
4745 @item -gnatm=@var{n}
4746 @cindex @option{-gnatm} (@command{gcc})
4747 @ifclear vms
4748 The @code{m} stands for maximum.
4749 @end ifclear
4750 @var{n} is a decimal integer in the
4751 range of 1 to 999999 and limits the number of error or warning
4752 messages to be generated. For example, using
4753 @option{-gnatm2} might yield
4754
4755 @smallexample
4756 e.adb:3:04: Incorrect spelling of keyword "function"
4757 e.adb:5:35: missing ".."
4758 fatal error: maximum number of errors detected
4759 compilation abandoned
4760 @end smallexample
4761
4762 @noindent
4763 The default setting if
4764 no switch is given is 9999. If the number of warnings reaches this
4765 limit, then a message is output and further warnings are suppressed,
4766 but the compilation is continued. If the number of error messages
4767 reaches this limit, then a message is output and the compilation
4768 is abandoned. A value of zero means that no limit applies.
4769
4770 @noindent
4771 Note that the equal sign is optional, so the switches
4772 @option{-gnatm2} and @option{-gnatm=2} are equivalent.
4773
4774 @item -gnatf
4775 @cindex @option{-gnatf} (@command{gcc})
4776 @cindex Error messages, suppressing
4777 @ifclear vms
4778 The @code{f} stands for full.
4779 @end ifclear
4780 Normally, the compiler suppresses error messages that are likely to be
4781 redundant. This switch causes all error
4782 messages to be generated. In particular, in the case of
4783 references to undefined variables. If a given variable is referenced
4784 several times, the normal format of messages is
4785 @smallexample
4786 e.adb:7:07: "V" is undefined (more references follow)
4787 @end smallexample
4788
4789 @noindent
4790 where the parenthetical comment warns that there are additional
4791 references to the variable @code{V}. Compiling the same program with the
4792 @option{-gnatf} switch yields
4793
4794 @smallexample
4795 e.adb:7:07: "V" is undefined
4796 e.adb:8:07: "V" is undefined
4797 e.adb:8:12: "V" is undefined
4798 e.adb:8:16: "V" is undefined
4799 e.adb:9:07: "V" is undefined
4800 e.adb:9:12: "V" is undefined
4801 @end smallexample
4802
4803 @noindent
4804 The @option{-gnatf} switch also generates additional information for
4805 some error messages.  Some examples are:
4806
4807 @itemize @bullet
4808 @item
4809 Details on possibly non-portable unchecked conversion
4810 @item
4811 List possible interpretations for ambiguous calls
4812 @item
4813 Additional details on incorrect parameters
4814 @end itemize
4815
4816 @item -gnatjnn
4817 @cindex @option{-gnatjnn} (@command{gcc})
4818 In normal operation mode (or if @option{-gnatj0} is used, then error messages
4819 with continuation lines are treated as though the continuation lines were
4820 separate messages (and so a warning with two continuation lines counts as
4821 three warnings, and is listed as three separate messages).
4822
4823 If the @option{-gnatjnn} switch is used with a positive value for nn, then
4824 messages are output in a different manner. A message and all its continuation
4825 lines are treated as a unit, and count as only one warning or message in the
4826 statistics totals. Furthermore, the message is reformatted so that no line
4827 is longer than nn characters.
4828
4829 @item -gnatq
4830 @cindex @option{-gnatq} (@command{gcc})
4831 @ifclear vms
4832 The @code{q} stands for quit (really ``don't quit'').
4833 @end ifclear
4834 In normal operation mode, the compiler first parses the program and
4835 determines if there are any syntax errors. If there are, appropriate
4836 error messages are generated and compilation is immediately terminated.
4837 This switch tells
4838 GNAT to continue with semantic analysis even if syntax errors have been
4839 found. This may enable the detection of more errors in a single run. On
4840 the other hand, the semantic analyzer is more likely to encounter some
4841 internal fatal error when given a syntactically invalid tree.
4842
4843 @item -gnatQ
4844 @cindex @option{-gnatQ} (@command{gcc})
4845 In normal operation mode, the @file{ALI} file is not generated if any
4846 illegalities are detected in the program. The use of @option{-gnatQ} forces
4847 generation of the @file{ALI} file. This file is marked as being in
4848 error, so it cannot be used for binding purposes, but it does contain
4849 reasonably complete cross-reference information, and thus may be useful
4850 for use by tools (e.g., semantic browsing tools or integrated development
4851 environments) that are driven from the @file{ALI} file. This switch
4852 implies @option{-gnatq}, since the semantic phase must be run to get a
4853 meaningful ALI file.
4854
4855 In addition, if @option{-gnatt} is also specified, then the tree file is
4856 generated even if there are illegalities. It may be useful in this case
4857 to also specify @option{-gnatq} to ensure that full semantic processing
4858 occurs. The resulting tree file can be processed by ASIS, for the purpose
4859 of providing partial information about illegal units, but if the error
4860 causes the tree to be badly malformed, then ASIS may crash during the
4861 analysis.
4862
4863 When @option{-gnatQ} is used and the generated @file{ALI} file is marked as
4864 being in error, @command{gnatmake} will attempt to recompile the source when it
4865 finds such an @file{ALI} file, including with switch @option{-gnatc}.
4866
4867 Note that @option{-gnatQ} has no effect if @option{-gnats} is specified,
4868 since ALI files are never generated if @option{-gnats} is set.
4869
4870 @end table
4871
4872 @node Warning Message Control
4873 @subsection Warning Message Control
4874 @cindex Warning messages
4875 @noindent
4876 In addition to error messages, which correspond to illegalities as defined
4877 in the Ada Reference Manual, the compiler detects two kinds of warning
4878 situations.
4879
4880 First, the compiler considers some constructs suspicious and generates a
4881 warning message to alert you to a possible error. Second, if the
4882 compiler detects a situation that is sure to raise an exception at
4883 run time, it generates a warning message. The following shows an example
4884 of warning messages:
4885 @smallexample
4886 e.adb:4:24: warning: creation of object may raise Storage_Error
4887 e.adb:10:17: warning: static value out of range
4888 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
4889 @end smallexample
4890
4891 @noindent
4892 GNAT considers a large number of situations as appropriate
4893 for the generation of warning messages. As always, warnings are not
4894 definite indications of errors. For example, if you do an out-of-range
4895 assignment with the deliberate intention of raising a
4896 @code{Constraint_Error} exception, then the warning that may be
4897 issued does not indicate an error. Some of the situations for which GNAT
4898 issues warnings (at least some of the time) are given in the following
4899 list. This list is not complete, and new warnings are often added to
4900 subsequent versions of GNAT. The list is intended to give a general idea
4901 of the kinds of warnings that are generated.
4902
4903 @itemize @bullet
4904 @item
4905 Possible infinitely recursive calls
4906
4907 @item
4908 Out-of-range values being assigned
4909
4910 @item
4911 Possible order of elaboration problems
4912
4913 @item
4914 Assertions (pragma Assert) that are sure to fail
4915
4916 @item
4917 Unreachable code
4918
4919 @item
4920 Address clauses with possibly unaligned values, or where an attempt is
4921 made to overlay a smaller variable with a larger one.
4922
4923 @item
4924 Fixed-point type declarations with a null range
4925
4926 @item
4927 Direct_IO or Sequential_IO instantiated with a type that has access values
4928
4929 @item
4930 Variables that are never assigned a value
4931
4932 @item
4933 Variables that are referenced before being initialized
4934
4935 @item
4936 Task entries with no corresponding @code{accept} statement
4937
4938 @item
4939 Duplicate accepts for the same task entry in a @code{select}
4940
4941 @item
4942 Objects that take too much storage
4943
4944 @item
4945 Unchecked conversion between types of differing sizes
4946
4947 @item
4948 Missing @code{return} statement along some execution path in a function
4949
4950 @item
4951 Incorrect (unrecognized) pragmas
4952
4953 @item
4954 Incorrect external names
4955
4956 @item
4957 Allocation from empty storage pool
4958
4959 @item
4960 Potentially blocking operation in protected type
4961
4962 @item
4963 Suspicious parenthesization of expressions
4964
4965 @item
4966 Mismatching bounds in an aggregate
4967
4968 @item
4969 Attempt to return local value by reference
4970
4971 @item
4972 Premature instantiation of a generic body
4973
4974 @item
4975 Attempt to pack aliased components
4976
4977 @item
4978 Out of bounds array subscripts
4979
4980 @item
4981 Wrong length on string assignment
4982
4983 @item
4984 Violations of style rules if style checking is enabled
4985
4986 @item
4987 Unused @code{with} clauses
4988
4989 @item
4990 @code{Bit_Order} usage that does not have any effect
4991
4992 @item
4993 @code{Standard.Duration} used to resolve universal fixed expression
4994
4995 @item
4996 Dereference of possibly null value
4997
4998 @item
4999 Declaration that is likely to cause storage error
5000
5001 @item
5002 Internal GNAT unit @code{with}'ed by application unit
5003
5004 @item
5005 Values known to be out of range at compile time
5006
5007 @item
5008 Unreferenced labels and variables
5009
5010 @item
5011 Address overlays that could clobber memory
5012
5013 @item
5014 Unexpected initialization when address clause present
5015
5016 @item
5017 Bad alignment for address clause
5018
5019 @item
5020 Useless type conversions
5021
5022 @item
5023 Redundant assignment statements and other redundant constructs
5024
5025 @item
5026 Useless exception handlers
5027
5028 @item
5029 Accidental hiding of name by child unit
5030
5031 @item
5032 Access before elaboration detected at compile time
5033
5034 @item
5035 A range in a @code{for} loop that is known to be null or might be null
5036
5037 @end itemize
5038
5039 @noindent
5040 The following section lists compiler switches that are available
5041 to control the handling of warning messages. It is also possible
5042 to exercise much finer control over what warnings are issued and
5043 suppressed using the GNAT pragma Warnings, @xref{Pragma Warnings,,,
5044 gnat_rm, GNAT Reference manual}.
5045
5046 @table @option
5047 @c !sort!
5048 @item -gnatwa
5049 @emph{Activate all optional errors.}
5050 @cindex @option{-gnatwa} (@command{gcc})
5051 This switch activates most optional warning messages, see remaining list
5052 in this section for details on optional warning messages that can be
5053 individually controlled.  The warnings that are not turned on by this
5054 switch are
5055 @option{-gnatwd} (implicit dereferencing),
5056 @option{-gnatwh} (hiding),
5057 @option{-gnatwl} (elaboration warnings),
5058 @option{-gnatw.o} (warn on values set by out parameters ignored)
5059 and @option{-gnatwt} (tracking of deleted conditional code).
5060 All other optional warnings are turned on.
5061
5062 @item -gnatwA
5063 @emph{Suppress all optional errors.}
5064 @cindex @option{-gnatwA} (@command{gcc})
5065 This switch suppresses all optional warning messages, see remaining list
5066 in this section for details on optional warning messages that can be
5067 individually controlled.
5068
5069 @item -gnatw.a
5070 @emph{Activate warnings on failing assertions.}
5071 @cindex @option{-gnatw.a} (@command{gcc})
5072 @cindex Assert failures
5073 This switch activates warnings for assertions where the compiler can tell at
5074 compile time that the assertion will fail. Note that this warning is given
5075 even if assertions are disabled. The default is that such warnings are
5076 generated.
5077
5078 @item -gnatw.A
5079 @emph{Suppress warnings on failing assertions.}
5080 @cindex @option{-gnatw.A} (@command{gcc})
5081 @cindex Assert failures
5082 This switch suppresses warnings for assertions where the compiler can tell at
5083 compile time that the assertion will fail.
5084
5085 @item -gnatwb
5086 @emph{Activate warnings on bad fixed values.}
5087 @cindex @option{-gnatwb} (@command{gcc})
5088 @cindex Bad fixed values
5089 @cindex Fixed-point Small value
5090 @cindex Small value
5091 This switch activates warnings for static fixed-point expressions whose
5092 value is not an exact multiple of Small. Such values are implementation
5093 dependent, since an implementation is free to choose either of the multiples
5094 that surround the value. GNAT always chooses the closer one, but this is not
5095 required behavior, and it is better to specify a value that is an exact
5096 multiple, ensuring predictable execution. The default is that such warnings
5097 are not generated.
5098
5099 @item -gnatwB
5100 @emph{Suppress warnings on bad fixed values.}
5101 @cindex @option{-gnatwB} (@command{gcc})
5102 This switch suppresses warnings for static fixed-point expressions whose
5103 value is not an exact multiple of Small.
5104
5105 @item -gnatw.b
5106 @emph{Activate warnings on biased representation.}
5107 @cindex @option{-gnatw.b} (@command{gcc})
5108 @cindex Biased representation
5109 This switch activates warnings when a size clause, value size clause, component
5110 clause, or component size clause forces the use of biased representation for an
5111 integer type (e.g. representing a range of 10..11 in a single bit by using 0/1
5112 to represent 10/11). The default is that such warnings are generated.
5113
5114 @item -gnatw.B
5115 @emph{Suppress warnings on biased representation.}
5116 @cindex @option{-gnatwB} (@command{gcc})
5117 This switch suppresses warnings for representation clauses that force the use
5118 of biased representation.
5119
5120 @item -gnatwc
5121 @emph{Activate warnings on conditionals.}
5122 @cindex @option{-gnatwc} (@command{gcc})
5123 @cindex Conditionals, constant
5124 This switch activates warnings for conditional expressions used in
5125 tests that are known to be True or False at compile time. The default
5126 is that such warnings are not generated.
5127 Note that this warning does
5128 not get issued for the use of boolean variables or constants whose
5129 values are known at compile time, since this is a standard technique
5130 for conditional compilation in Ada, and this would generate too many
5131 false positive warnings.
5132
5133 This warning option also activates a special test for comparisons using
5134 the operators ``>='' and`` <=''.
5135 If the compiler can tell that only the equality condition is possible,
5136 then it will warn that the ``>'' or ``<'' part of the test
5137 is useless and that the operator could be replaced by ``=''.
5138 An example would be comparing a @code{Natural} variable <= 0.
5139
5140 This warning option also generates warnings if
5141 one or both tests is optimized away in a membership test for integer
5142 values if the result can be determined at compile time. Range tests on
5143 enumeration types are not included, since it is common for such tests
5144 to include an end point.
5145
5146 This warning can also be turned on using @option{-gnatwa}.
5147
5148 @item -gnatwC
5149 @emph{Suppress warnings on conditionals.}
5150 @cindex @option{-gnatwC} (@command{gcc})
5151 This switch suppresses warnings for conditional expressions used in
5152 tests that are known to be True or False at compile time.
5153
5154 @item -gnatw.c
5155 @emph{Activate warnings on missing component clauses.}
5156 @cindex @option{-gnatw.c} (@command{gcc})
5157 @cindex Component clause, missing
5158 This switch activates warnings for record components where a record
5159 representation clause is present and has component clauses for the
5160 majority, but not all, of the components. A warning is given for each
5161 component for which no component clause is present.
5162
5163 This warning can also be turned on using @option{-gnatwa}.
5164
5165 @item -gnatw.C
5166 @emph{Suppress warnings on missing component clauses.}
5167 @cindex @option{-gnatwC} (@command{gcc})
5168 This switch suppresses warnings for record components that are
5169 missing a component clause in the situation described above.
5170
5171 @item -gnatwd
5172 @emph{Activate warnings on implicit dereferencing.}
5173 @cindex @option{-gnatwd} (@command{gcc})
5174 If this switch is set, then the use of a prefix of an access type
5175 in an indexed component, slice, or selected component without an
5176 explicit @code{.all} will generate a warning. With this warning
5177 enabled, access checks occur only at points where an explicit
5178 @code{.all} appears in the source code (assuming no warnings are
5179 generated as a result of this switch). The default is that such
5180 warnings are not generated.
5181 Note that @option{-gnatwa} does not affect the setting of
5182 this warning option.
5183
5184 @item -gnatwD
5185 @emph{Suppress warnings on implicit dereferencing.}
5186 @cindex @option{-gnatwD} (@command{gcc})
5187 @cindex Implicit dereferencing
5188 @cindex Dereferencing, implicit
5189 This switch suppresses warnings for implicit dereferences in
5190 indexed components, slices, and selected components.
5191
5192 @item -gnatwe
5193 @emph{Treat warnings as errors.}
5194 @cindex @option{-gnatwe} (@command{gcc})
5195 @cindex Warnings, treat as error
5196 This switch causes warning messages to be treated as errors.
5197 The warning string still appears, but the warning messages are counted
5198 as errors, and prevent the generation of an object file.
5199
5200 @item -gnatw.e
5201 @emph{Activate every optional warning}
5202 @cindex @option{-gnatw.e} (@command{gcc})
5203 @cindex Warnings, activate every optional warning
5204 This switch activates all optional warnings, including those which
5205 are not activated by @code{-gnatwa}.
5206
5207 @item -gnatwf
5208 @emph{Activate warnings on unreferenced formals.}
5209 @cindex @option{-gnatwf} (@command{gcc})
5210 @cindex Formals, unreferenced
5211 This switch causes a warning to be generated if a formal parameter
5212 is not referenced in the body of the subprogram. This warning can
5213 also be turned on using @option{-gnatwa} or @option{-gnatwu}. The
5214 default is that these warnings are not generated.
5215
5216 @item -gnatwF
5217 @emph{Suppress warnings on unreferenced formals.}
5218 @cindex @option{-gnatwF} (@command{gcc})
5219 This switch suppresses warnings for unreferenced formal
5220 parameters. Note that the
5221 combination @option{-gnatwu} followed by @option{-gnatwF} has the
5222 effect of warning on unreferenced entities other than subprogram
5223 formals.
5224
5225 @item -gnatwg
5226 @emph{Activate warnings on unrecognized pragmas.}
5227 @cindex @option{-gnatwg} (@command{gcc})
5228 @cindex Pragmas, unrecognized
5229 This switch causes a warning to be generated if an unrecognized
5230 pragma is encountered. Apart from issuing this warning, the
5231 pragma is ignored and has no effect. This warning can
5232 also be turned on using @option{-gnatwa}. The default
5233 is that such warnings are issued (satisfying the Ada Reference
5234 Manual requirement that such warnings appear).
5235
5236 @item -gnatwG
5237 @emph{Suppress warnings on unrecognized pragmas.}
5238 @cindex @option{-gnatwG} (@command{gcc})
5239 This switch suppresses warnings for unrecognized pragmas.
5240
5241 @item -gnatwh
5242 @emph{Activate warnings on hiding.}
5243 @cindex @option{-gnatwh} (@command{gcc})
5244 @cindex Hiding of Declarations
5245 This switch activates warnings on hiding declarations.
5246 A declaration is considered hiding
5247 if it is for a non-overloadable entity, and it declares an entity with the
5248 same name as some other entity that is directly or use-visible. The default
5249 is that such warnings are not generated.
5250 Note that @option{-gnatwa} does not affect the setting of this warning option.
5251
5252 @item -gnatwH
5253 @emph{Suppress warnings on hiding.}
5254 @cindex @option{-gnatwH} (@command{gcc})
5255 This switch suppresses warnings on hiding declarations.
5256
5257 @item -gnatwi
5258 @emph{Activate warnings on implementation units.}
5259 @cindex @option{-gnatwi} (@command{gcc})
5260 This switch activates warnings for a @code{with} of an internal GNAT
5261 implementation unit, defined as any unit from the @code{Ada},
5262 @code{Interfaces}, @code{GNAT},
5263 ^^@code{DEC},^ or @code{System}
5264 hierarchies that is not
5265 documented in either the Ada Reference Manual or the GNAT
5266 Programmer's Reference Manual. Such units are intended only
5267 for internal implementation purposes and should not be @code{with}'ed
5268 by user programs. The default is that such warnings are generated
5269 This warning can also be turned on using @option{-gnatwa}.
5270
5271 @item -gnatwI
5272 @emph{Disable warnings on implementation units.}
5273 @cindex @option{-gnatwI} (@command{gcc})
5274 This switch disables warnings for a @code{with} of an internal GNAT
5275 implementation unit.
5276
5277 @item -gnatw.i
5278 @emph{Activate warnings on overlapping actuals.}
5279 @cindex @option{-gnatw.i} (@command{gcc})
5280 This switch enables a warning on statically detectable overlapping actuals in
5281 a subprogram call, when one of the actuals is an in-out parameter, and the
5282 types of the actuals are not by-copy types. The warning is off by default,
5283 and is not included under -gnatwa.
5284
5285 @item -gnatw.I
5286 @emph{Disable warnings on overlapping actuals.}
5287 @cindex @option{-gnatw.I} (@command{gcc})
5288 This switch disables warnings on overlapping actuals in a call..
5289
5290 @item -gnatwj
5291 @emph{Activate warnings on obsolescent features (Annex J).}
5292 @cindex @option{-gnatwj} (@command{gcc})
5293 @cindex Features, obsolescent
5294 @cindex Obsolescent features
5295 If this warning option is activated, then warnings are generated for
5296 calls to subprograms marked with @code{pragma Obsolescent} and
5297 for use of features in Annex J of the Ada Reference Manual. In the
5298 case of Annex J, not all features are flagged. In particular use
5299 of the renamed packages (like @code{Text_IO}) and use of package
5300 @code{ASCII} are not flagged, since these are very common and
5301 would generate many annoying positive warnings. The default is that
5302 such warnings are not generated. This warning is also turned on by
5303 the use of @option{-gnatwa}.
5304
5305 In addition to the above cases, warnings are also generated for
5306 GNAT features that have been provided in past versions but which
5307 have been superseded (typically by features in the new Ada standard).
5308 For example, @code{pragma Ravenscar} will be flagged since its
5309 function is replaced by @code{pragma Profile(Ravenscar)}.
5310
5311 Note that this warning option functions differently from the
5312 restriction @code{No_Obsolescent_Features} in two respects.
5313 First, the restriction applies only to annex J features.
5314 Second, the restriction does flag uses of package @code{ASCII}.
5315
5316 @item -gnatwJ
5317 @emph{Suppress warnings on obsolescent features (Annex J).}
5318 @cindex @option{-gnatwJ} (@command{gcc})
5319 This switch disables warnings on use of obsolescent features.
5320
5321 @item -gnatwk
5322 @emph{Activate warnings on variables that could be constants.}
5323 @cindex @option{-gnatwk} (@command{gcc})
5324 This switch activates warnings for variables that are initialized but
5325 never modified, and then could be declared constants. The default is that
5326 such warnings are not given.
5327 This warning can also be turned on using @option{-gnatwa}.
5328
5329 @item -gnatwK
5330 @emph{Suppress warnings on variables that could be constants.}
5331 @cindex @option{-gnatwK} (@command{gcc})
5332 This switch disables warnings on variables that could be declared constants.
5333
5334 @item -gnatwl
5335 @emph{Activate warnings for elaboration pragmas.}
5336 @cindex @option{-gnatwl} (@command{gcc})
5337 @cindex Elaboration, warnings
5338 This switch activates warnings on missing
5339 @code{Elaborate_All} and @code{Elaborate} pragmas.
5340 See the section in this guide on elaboration checking for details on
5341 when such pragmas should be used. In dynamic elaboration mode, this switch
5342 generations warnings about the need to add elaboration pragmas. Note however,
5343 that if you blindly follow these warnings, and add @code{Elaborate_All}
5344 warnings wherever they are recommended, you basically end up with the
5345 equivalent of the static elaboration model, which may not be what you want for
5346 legacy code for which the static model does not work.
5347
5348 For the static model, the messages generated are labeled "info:" (for
5349 information messages). They are not warnings to add elaboration pragmas,
5350 merely informational messages showing what implicit elaboration pragmas
5351 have been added, for use in analyzing elaboration circularity problems.
5352
5353 Warnings are also generated if you
5354 are using the static mode of elaboration, and a @code{pragma Elaborate}
5355 is encountered. The default is that such warnings
5356 are not generated.
5357 This warning is not automatically turned on by the use of @option{-gnatwa}.
5358
5359 @item -gnatwL
5360 @emph{Suppress warnings for elaboration pragmas.}
5361 @cindex @option{-gnatwL} (@command{gcc})
5362 This switch suppresses warnings on missing Elaborate and Elaborate_All pragmas.
5363 See the section in this guide on elaboration checking for details on
5364 when such pragmas should be used.
5365
5366 @item -gnatwm
5367 @emph{Activate warnings on modified but unreferenced variables.}
5368 @cindex @option{-gnatwm} (@command{gcc})
5369 This switch activates warnings for variables that are assigned (using
5370 an initialization value or with one or more assignment statements) but
5371 whose value is never read. The warning is suppressed for volatile
5372 variables and also for variables that are renamings of other variables
5373 or for which an address clause is given.
5374 This warning can also be turned on using @option{-gnatwa}.
5375 The default is that these warnings are not given.
5376
5377 @item -gnatwM
5378 @emph{Disable warnings on modified but unreferenced variables.}
5379 @cindex @option{-gnatwM} (@command{gcc})
5380 This switch disables warnings for variables that are assigned or
5381 initialized, but never read.
5382
5383 @item -gnatw.m
5384 @emph{Activate warnings on suspicious modulus values.}
5385 @cindex @option{-gnatw.m} (@command{gcc})
5386 This switch activates warnings for modulus values that seem suspicious.
5387 The cases caught are where the size is the same as the modulus (e.g.
5388 a modulus of 7 with a size of 7 bits), and modulus values of 32 or 64
5389 with no size clause. The guess in both cases is that 2**x was intended
5390 rather than x. The default is that these warnings are given.
5391
5392 @item -gnatw.M
5393 @emph{Disable warnings on suspicious modulus values.}
5394 @cindex @option{-gnatw.M} (@command{gcc})
5395 This switch disables warnings for suspicious modulus values.
5396
5397 @item -gnatwn
5398 @emph{Set normal warnings mode.}
5399 @cindex @option{-gnatwn} (@command{gcc})
5400 This switch sets normal warning mode, in which enabled warnings are
5401 issued and treated as warnings rather than errors. This is the default
5402 mode. the switch @option{-gnatwn} can be used to cancel the effect of
5403 an explicit @option{-gnatws} or
5404 @option{-gnatwe}. It also cancels the effect of the
5405 implicit @option{-gnatwe} that is activated by the
5406 use of @option{-gnatg}.
5407
5408 @item -gnatwo
5409 @emph{Activate warnings on address clause overlays.}
5410 @cindex @option{-gnatwo} (@command{gcc})
5411 @cindex Address Clauses, warnings
5412 This switch activates warnings for possibly unintended initialization
5413 effects of defining address clauses that cause one variable to overlap
5414 another. The default is that such warnings are generated.
5415 This warning can also be turned on using @option{-gnatwa}.
5416
5417 @item -gnatwO
5418 @emph{Suppress warnings on address clause overlays.}
5419 @cindex @option{-gnatwO} (@command{gcc})
5420 This switch suppresses warnings on possibly unintended initialization
5421 effects of defining address clauses that cause one variable to overlap
5422 another.
5423
5424 @item -gnatw.o
5425 @emph{Activate warnings on modified but unreferenced out parameters.}
5426 @cindex @option{-gnatw.o} (@command{gcc})
5427 This switch activates warnings for variables that are modified by using
5428 them as actuals for a call to a procedure with an out mode formal, where
5429 the resulting assigned value is never read. It is applicable in the case
5430 where there is more than one out mode formal. If there is only one out
5431 mode formal, the warning is issued by default (controlled by -gnatwu).
5432 The warning is suppressed for volatile
5433 variables and also for variables that are renamings of other variables
5434 or for which an address clause is given.
5435 The default is that these warnings are not given. Note that this warning
5436 is not included in -gnatwa, it must be activated explicitly.
5437
5438 @item -gnatw.O
5439 @emph{Disable warnings on modified but unreferenced out parameters.}
5440 @cindex @option{-gnatw.O} (@command{gcc})
5441 This switch suppresses warnings for variables that are modified by using
5442 them as actuals for a call to a procedure with an out mode formal, where
5443 the resulting assigned value is never read.
5444
5445 @item -gnatwp
5446 @emph{Activate warnings on ineffective pragma Inlines.}
5447 @cindex @option{-gnatwp} (@command{gcc})
5448 @cindex Inlining, warnings
5449 This switch activates warnings for failure of front end inlining
5450 (activated by @option{-gnatN}) to inline a particular call. There are
5451 many reasons for not being able to inline a call, including most
5452 commonly that the call is too complex to inline. The default is
5453 that such warnings are not given.
5454 This warning can also be turned on using @option{-gnatwa}.
5455 Warnings on ineffective inlining by the gcc back-end can be activated
5456 separately, using the gcc switch -Winline.
5457
5458 @item -gnatwP
5459 @emph{Suppress warnings on ineffective pragma Inlines.}
5460 @cindex @option{-gnatwP} (@command{gcc})
5461 This switch suppresses warnings on ineffective pragma Inlines. If the
5462 inlining mechanism cannot inline a call, it will simply ignore the
5463 request silently.
5464
5465 @item -gnatw.p
5466 @emph{Activate warnings on parameter ordering.}
5467 @cindex @option{-gnatw.p} (@command{gcc})
5468 @cindex Parameter order, warnings
5469 This switch activates warnings for cases of suspicious parameter
5470 ordering when the list of arguments are all simple identifiers that
5471 match the names of the formals, but are in a different order. The
5472 warning is suppressed if any use of named parameter notation is used,
5473 so this is the appropriate way to suppress a false positive (and
5474 serves to emphasize that the "misordering" is deliberate). The
5475 default is
5476 that such warnings are not given.
5477 This warning can also be turned on using @option{-gnatwa}.
5478
5479 @item -gnatw.P
5480 @emph{Suppress warnings on parameter ordering.}
5481 @cindex @option{-gnatw.P} (@command{gcc})
5482 This switch suppresses warnings on cases of suspicious parameter
5483 ordering.
5484
5485 @item -gnatwq
5486 @emph{Activate warnings on questionable missing parentheses.}
5487 @cindex @option{-gnatwq} (@command{gcc})
5488 @cindex Parentheses, warnings
5489 This switch activates warnings for cases where parentheses are not used and
5490 the result is potential ambiguity from a readers point of view. For example
5491 (not a > b) when a and b are modular means ((not a) > b) and very likely the
5492 programmer intended (not (a > b)). Similarly (-x mod 5) means (-(x mod 5)) and
5493 quite likely ((-x) mod 5) was intended. In such situations it seems best to
5494 follow the rule of always parenthesizing to make the association clear, and
5495 this warning switch warns if such parentheses are not present. The default
5496 is that these warnings are given.
5497 This warning can also be turned on using @option{-gnatwa}.
5498
5499 @item -gnatwQ
5500 @emph{Suppress warnings on questionable missing parentheses.}
5501 @cindex @option{-gnatwQ} (@command{gcc})
5502 This switch suppresses warnings for cases where the association is not
5503 clear and the use of parentheses is preferred.
5504
5505 @item -gnatwr
5506 @emph{Activate warnings on redundant constructs.}
5507 @cindex @option{-gnatwr} (@command{gcc})
5508 This switch activates warnings for redundant constructs. The following
5509 is the current list of constructs regarded as redundant:
5510
5511 @itemize @bullet
5512 @item
5513 Assignment of an item to itself.
5514 @item
5515 Type conversion that converts an expression to its own type.
5516 @item
5517 Use of the attribute @code{Base} where @code{typ'Base} is the same
5518 as @code{typ}.
5519 @item
5520 Use of pragma @code{Pack} when all components are placed by a record
5521 representation clause.
5522 @item
5523 Exception handler containing only a reraise statement (raise with no
5524 operand) which has no effect.
5525 @item
5526 Use of the operator abs on an operand that is known at compile time
5527 to be non-negative
5528 @item
5529 Comparison of boolean expressions to an explicit True value.
5530 @end itemize
5531
5532 This warning can also be turned on using @option{-gnatwa}.
5533 The default is that warnings for redundant constructs are not given.
5534
5535 @item -gnatwR
5536 @emph{Suppress warnings on redundant constructs.}
5537 @cindex @option{-gnatwR} (@command{gcc})
5538 This switch suppresses warnings for redundant constructs.
5539
5540 @item -gnatw.r
5541 @emph{Activate warnings for object renaming function.}
5542 @cindex @option{-gnatw.r} (@command{gcc})
5543 This switch activates warnings for an object renaming that renames a
5544 function call, which is equivalent to a constant declaration (as
5545 opposed to renaming the function itself).  The default is that these
5546 warnings are given.  This warning can also be turned on using
5547 @option{-gnatwa}.
5548
5549 @item -gnatw.R
5550 @emph{Suppress warnings for object renaming function.}
5551 @cindex @option{-gnatwT} (@command{gcc})
5552 This switch suppresses warnings for object renaming function.
5553
5554 @item -gnatws
5555 @emph{Suppress all warnings.}
5556 @cindex @option{-gnatws} (@command{gcc})
5557 This switch completely suppresses the
5558 output of all warning messages from the GNAT front end.
5559 Note that it does not suppress warnings from the @command{gcc} back end.
5560 To suppress these back end warnings as well, use the switch @option{-w}
5561 in addition to @option{-gnatws}.
5562
5563 @item -gnatwt
5564 @emph{Activate warnings for tracking of deleted conditional code.}
5565 @cindex @option{-gnatwt} (@command{gcc})
5566 @cindex Deactivated code, warnings
5567 @cindex Deleted code, warnings
5568 This switch activates warnings for tracking of code in conditionals (IF and
5569 CASE statements) that is detected to be dead code which cannot be executed, and
5570 which is removed by the front end. This warning is off by default, and is not
5571 turned on by @option{-gnatwa}, it has to be turned on explicitly. This may be
5572 useful for detecting deactivated code in certified applications.
5573
5574 @item -gnatwT
5575 @emph{Suppress warnings for tracking of deleted conditional code.}
5576 @cindex @option{-gnatwT} (@command{gcc})
5577 This switch suppresses warnings for tracking of deleted conditional code.
5578
5579 @item -gnatwu
5580 @emph{Activate warnings on unused entities.}
5581 @cindex @option{-gnatwu} (@command{gcc})
5582 This switch activates warnings to be generated for entities that
5583 are declared but not referenced, and for units that are @code{with}'ed
5584 and not
5585 referenced. In the case of packages, a warning is also generated if
5586 no entities in the package are referenced. This means that if the package
5587 is referenced but the only references are in @code{use}
5588 clauses or @code{renames}
5589 declarations, a warning is still generated. A warning is also generated
5590 for a generic package that is @code{with}'ed but never instantiated.
5591 In the case where a package or subprogram body is compiled, and there
5592 is a @code{with} on the corresponding spec
5593 that is only referenced in the body,
5594 a warning is also generated, noting that the
5595 @code{with} can be moved to the body. The default is that
5596 such warnings are not generated.
5597 This switch also activates warnings on unreferenced formals
5598 (it includes the effect of @option{-gnatwf}).
5599 This warning can also be turned on using @option{-gnatwa}.
5600
5601 @item -gnatwU
5602 @emph{Suppress warnings on unused entities.}
5603 @cindex @option{-gnatwU} (@command{gcc})
5604 This switch suppresses warnings for unused entities and packages.
5605 It also turns off warnings on unreferenced formals (and thus includes
5606 the effect of @option{-gnatwF}).
5607
5608 @item -gnatwv
5609 @emph{Activate warnings on unassigned variables.}
5610 @cindex @option{-gnatwv} (@command{gcc})
5611 @cindex Unassigned variable warnings
5612 This switch activates warnings for access to variables which
5613 may not be properly initialized. The default is that
5614 such warnings are generated.
5615 This warning can also be turned on using @option{-gnatwa}.
5616
5617 @item -gnatwV
5618 @emph{Suppress warnings on unassigned variables.}
5619 @cindex @option{-gnatwV} (@command{gcc})
5620 This switch suppresses warnings for access to variables which
5621 may not be properly initialized.
5622 For variables of a composite type, the warning can also be suppressed in
5623 Ada 2005 by using a default initialization with a box. For example, if
5624 Table is an array of records whose components are only partially uninitialized,
5625 then the following code:
5626
5627 @smallexample @c ada
5628    Tab : Table := (others => <>);
5629 @end smallexample
5630
5631 will suppress warnings on subsequent statements that access components
5632 of variable Tab.
5633
5634 @item -gnatww
5635 @emph{Activate warnings on wrong low bound assumption.}
5636 @cindex @option{-gnatww} (@command{gcc})
5637 @cindex String indexing warnings
5638 This switch activates warnings for indexing an unconstrained string parameter
5639 with a literal or S'Length. This is a case where the code is assuming that the
5640 low bound is one, which is in general not true (for example when a slice is
5641 passed). The default is that such warnings are generated.
5642 This warning can also be turned on using @option{-gnatwa}.
5643
5644 @item -gnatwW
5645 @emph{Suppress warnings on wrong low bound assumption.}
5646 @cindex @option{-gnatwW} (@command{gcc})
5647 This switch suppresses warnings for indexing an unconstrained string parameter
5648 with a literal or S'Length. Note that this warning can also be suppressed
5649 in a particular case by adding an
5650 assertion that the lower bound is 1,
5651 as shown in the following example.
5652
5653 @smallexample @c ada
5654    procedure K (S : String) is
5655       pragma Assert (S'First = 1);
5656       @dots{}
5657 @end smallexample
5658
5659 @item -gnatw.w
5660 @emph{Activate warnings on unnecessary Warnings Off pragmas}
5661 @cindex @option{-gnatw.w} (@command{gcc})
5662 @cindex Warnings Off control
5663 This switch activates warnings for use of @code{pragma Warnings (Off, entity}
5664 where either the pragma is entirely useless (because it suppresses no
5665 warnings), or it could be replaced by @code{pragma Unreferenced} or
5666 @code{pragma Unmodified}.The default is that these warnings are not given.
5667 Note that this warning is not included in -gnatwa, it must be
5668 activated explicitly.
5669
5670 @item -gnatw.W
5671 @emph{Suppress warnings on unnecessary Warnings Off pragmas}
5672 @cindex @option{-gnatw.W} (@command{gcc})
5673 This switch suppresses warnings for use of @code{pragma Warnings (Off, entity}.
5674
5675 @item -gnatwx
5676 @emph{Activate warnings on Export/Import pragmas.}
5677 @cindex @option{-gnatwx} (@command{gcc})
5678 @cindex Export/Import pragma warnings
5679 This switch activates warnings on Export/Import pragmas when
5680 the compiler detects a possible conflict between the Ada and
5681 foreign language calling sequences. For example, the use of
5682 default parameters in a convention C procedure is dubious
5683 because the C compiler cannot supply the proper default, so
5684 a warning is issued. The default is that such warnings are
5685 generated.
5686 This warning can also be turned on using @option{-gnatwa}.
5687
5688 @item -gnatwX
5689 @emph{Suppress warnings on Export/Import pragmas.}
5690 @cindex @option{-gnatwX} (@command{gcc})
5691 This switch suppresses warnings on Export/Import pragmas.
5692 The sense of this is that you are telling the compiler that
5693 you know what you are doing in writing the pragma, and it
5694 should not complain at you.
5695
5696 @item -gnatw.x
5697 @emph{Activate warnings for No_Exception_Propagation mode.}
5698 @cindex @option{-gnatwm} (@command{gcc})
5699 This switch activates warnings for exception usage when pragma Restrictions
5700 (No_Exception_Propagation) is in effect. Warnings are given for implicit or
5701 explicit exception raises which are not covered by a local handler, and for
5702 exception handlers which do not cover a local raise. The default is that these
5703 warnings are not given.
5704
5705 @item -gnatw.X
5706 @emph{Disable warnings for No_Exception_Propagation mode.}
5707 This switch disables warnings for exception usage when pragma Restrictions
5708 (No_Exception_Propagation) is in effect.
5709
5710 @item -gnatwy
5711 @emph{Activate warnings for Ada 2005 compatibility issues.}
5712 @cindex @option{-gnatwy} (@command{gcc})
5713 @cindex Ada 2005 compatibility issues warnings
5714 For the most part Ada 2005 is upwards compatible with Ada 95,
5715 but there are some exceptions (for example the fact that
5716 @code{interface} is now a reserved word in Ada 2005). This
5717 switch activates several warnings to help in identifying
5718 and correcting such incompatibilities. The default is that
5719 these warnings are generated. Note that at one point Ada 2005
5720 was called Ada 0Y, hence the choice of character.
5721 This warning can also be turned on using @option{-gnatwa}.
5722
5723 @item -gnatwY
5724 @emph{Disable warnings for Ada 2005 compatibility issues.}
5725 @cindex @option{-gnatwY} (@command{gcc})
5726 @cindex Ada 2005 compatibility issues warnings
5727 This switch suppresses several warnings intended to help in identifying
5728 incompatibilities between Ada 95 and Ada 2005.
5729
5730 @item -gnatwz
5731 @emph{Activate warnings on unchecked conversions.}
5732 @cindex @option{-gnatwz} (@command{gcc})
5733 @cindex Unchecked_Conversion warnings
5734 This switch activates warnings for unchecked conversions
5735 where the types are known at compile time to have different
5736 sizes. The default
5737 is that such warnings are generated. Warnings are also
5738 generated for subprogram pointers with different conventions,
5739 and, on VMS only, for data pointers with different conventions.
5740 This warning can also be turned on using @option{-gnatwa}.
5741
5742 @item -gnatwZ
5743 @emph{Suppress warnings on unchecked conversions.}
5744 @cindex @option{-gnatwZ} (@command{gcc})
5745 This switch suppresses warnings for unchecked conversions
5746 where the types are known at compile time to have different
5747 sizes or conventions.
5748
5749 @item ^-Wunused^WARNINGS=UNUSED^
5750 @cindex @option{-Wunused}
5751 The warnings controlled by the @option{-gnatw} switch are generated by
5752 the front end of the compiler. The @option{GCC} back end can provide
5753 additional warnings and they are controlled by the @option{-W} switch.
5754 For example, @option{^-Wunused^WARNINGS=UNUSED^} activates back end
5755 warnings for entities that are declared but not referenced.
5756
5757 @item ^-Wuninitialized^WARNINGS=UNINITIALIZED^
5758 @cindex @option{-Wuninitialized}
5759 Similarly, @option{^-Wuninitialized^WARNINGS=UNINITIALIZED^} activates
5760 the back end warning for uninitialized variables. This switch must be
5761 used in conjunction with an optimization level greater than zero.
5762
5763 @item ^-Wall^/ALL_BACK_END_WARNINGS^
5764 @cindex @option{-Wall}
5765 This switch enables all the above warnings from the @option{GCC} back end.
5766 The code generator detects a number of warning situations that are missed
5767 by the @option{GNAT} front end, and this switch can be used to activate them.
5768 The use of this switch also sets the default front end warning mode to
5769 @option{-gnatwa}, that is, most front end warnings activated as well.
5770
5771 @item ^-w^/NO_BACK_END_WARNINGS^
5772 @cindex @option{-w}
5773 Conversely, this switch suppresses warnings from the @option{GCC} back end.
5774 The use of this switch also sets the default front end warning mode to
5775 @option{-gnatws}, that is, front end warnings suppressed as well.
5776
5777 @end table
5778
5779 @noindent
5780 @ifclear vms
5781 A string of warning parameters can be used in the same parameter. For example:
5782
5783 @smallexample
5784 -gnatwaLe
5785 @end smallexample
5786
5787 @noindent
5788 will turn on all optional warnings except for elaboration pragma warnings,
5789 and also specify that warnings should be treated as errors.
5790 @end ifclear
5791 When no switch @option{^-gnatw^/WARNINGS^} is used, this is equivalent to:
5792
5793 @table @option
5794 @c !sort!
5795 @item -gnatwC
5796 @item -gnatwD
5797 @item -gnatwF
5798 @item -gnatwg
5799 @item -gnatwH
5800 @item -gnatwi
5801 @item -gnatwJ
5802 @item -gnatwK
5803 @item -gnatwL
5804 @item -gnatwM
5805 @item -gnatwn
5806 @item -gnatwo
5807 @item -gnatwP
5808 @item -gnatwR
5809 @item -gnatwU
5810 @item -gnatwv
5811 @item -gnatwz
5812 @item -gnatwx
5813
5814 @end table
5815
5816 @node Debugging and Assertion Control
5817 @subsection Debugging and Assertion Control
5818
5819 @table @option
5820 @item -gnata
5821 @cindex @option{-gnata} (@command{gcc})
5822 @findex Assert
5823 @findex Debug
5824 @cindex Assertions
5825
5826 @noindent
5827 The pragmas @code{Assert} and @code{Debug} normally have no effect and
5828 are ignored. This switch, where @samp{a} stands for assert, causes
5829 @code{Assert} and @code{Debug} pragmas to be activated.
5830
5831 The pragmas have the form:
5832
5833 @smallexample
5834 @cartouche
5835    @b{pragma} Assert (@var{Boolean-expression} @r{[},
5836                       @var{static-string-expression}@r{]})
5837    @b{pragma} Debug (@var{procedure call})
5838 @end cartouche
5839 @end smallexample
5840
5841 @noindent
5842 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
5843 If the result is @code{True}, the pragma has no effect (other than
5844 possible side effects from evaluating the expression). If the result is
5845 @code{False}, the exception @code{Assert_Failure} declared in the package
5846 @code{System.Assertions} is
5847 raised (passing @var{static-string-expression}, if present, as the
5848 message associated with the exception). If no string expression is
5849 given the default is a string giving the file name and line number
5850 of the pragma.
5851
5852 The @code{Debug} pragma causes @var{procedure} to be called. Note that
5853 @code{pragma Debug} may appear within a declaration sequence, allowing
5854 debugging procedures to be called between declarations.
5855
5856 @ifset vms
5857 @item /DEBUG@r{[}=debug-level@r{]}
5858 @itemx  /NODEBUG
5859 Specifies how much debugging information is to be included in
5860 the resulting object file where 'debug-level' is one of the following:
5861 @table @code
5862 @item   TRACEBACK
5863 Include both debugger symbol records and traceback
5864 the object file.
5865 This is the default setting.
5866 @item   ALL
5867 Include both debugger symbol records and traceback in
5868 object file.
5869 @item   NONE
5870 Excludes both debugger symbol records and traceback
5871 the object file. Same as /NODEBUG.
5872 @item   SYMBOLS
5873 Includes only debugger symbol records in the object
5874 file. Note that this doesn't include traceback information.
5875 @end table
5876 @end ifset
5877 @end table
5878
5879 @node Validity Checking
5880 @subsection Validity Checking
5881 @findex Validity Checking
5882
5883 @noindent
5884 The Ada Reference Manual defines the concept of invalid values (see
5885 RM 13.9.1). The primary source of invalid values is uninitialized
5886 variables. A scalar variable that is left uninitialized may contain
5887 an invalid value; the concept of invalid does not apply to access or
5888 composite types.
5889
5890 It is an error to read an invalid value, but the RM does not require
5891 run-time checks to detect such errors, except for some minimal
5892 checking to prevent erroneous execution (i.e. unpredictable
5893 behavior). This corresponds to the @option{-gnatVd} switch below,
5894 which is the default. For example, by default, if the expression of a
5895 case statement is invalid, it will raise Constraint_Error rather than
5896 causing a wild jump, and if an array index on the left-hand side of an
5897 assignment is invalid, it will raise Constraint_Error rather than
5898 overwriting an arbitrary memory location.
5899
5900 The @option{-gnatVa} may be used to enable additional validity checks,
5901 which are not required by the RM. These checks are often very
5902 expensive (which is why the RM does not require them). These checks
5903 are useful in tracking down uninitialized variables, but they are
5904 not usually recommended for production builds.
5905
5906 The other @option{-gnatV^@var{x}^^} switches below allow finer-grained
5907 control; you can enable whichever validity checks you desire. However,
5908 for most debugging purposes, @option{-gnatVa} is sufficient, and the
5909 default @option{-gnatVd} (i.e. standard Ada behavior) is usually
5910 sufficient for non-debugging use.
5911
5912 The @option{-gnatB} switch tells the compiler to assume that all
5913 values are valid (that is, within their declared subtype range)
5914 except in the context of a use of the Valid attribute. This means
5915 the compiler can generate more efficient code, since the range
5916 of values is better known at compile time. However, an uninitialized
5917 variable can cause wild jumps and memory corruption in this mode.
5918
5919 The @option{-gnatV^@var{x}^^} switch allows control over the validity
5920 checking mode as described below.
5921 @ifclear vms
5922 The @code{x} argument is a string of letters that
5923 indicate validity checks that are performed or not performed in addition
5924 to the default checks required by Ada as described above.
5925 @end ifclear
5926 @ifset vms
5927 The options allowed for this qualifier
5928 indicate validity checks that are performed or not performed in addition
5929 to the default checks required by Ada as described above.
5930 @end ifset
5931
5932 @table @option
5933 @c !sort!
5934 @item -gnatVa
5935 @emph{All validity checks.}
5936 @cindex @option{-gnatVa} (@command{gcc})
5937 All validity checks are turned on.
5938 @ifclear vms
5939 That is, @option{-gnatVa} is
5940 equivalent to @option{gnatVcdfimorst}.
5941 @end ifclear
5942
5943 @item -gnatVc
5944 @emph{Validity checks for copies.}
5945 @cindex @option{-gnatVc} (@command{gcc})
5946 The right hand side of assignments, and the initializing values of
5947 object declarations are validity checked.
5948
5949 @item -gnatVd
5950 @emph{Default (RM) validity checks.}
5951 @cindex @option{-gnatVd} (@command{gcc})
5952 Some validity checks are done by default following normal Ada semantics
5953 (RM 13.9.1 (9-11)).
5954 A check is done in case statements that the expression is within the range
5955 of the subtype. If it is not, Constraint_Error is raised.
5956 For assignments to array components, a check is done that the expression used
5957 as index is within the range. If it is not, Constraint_Error is raised.
5958 Both these validity checks may be turned off using switch @option{-gnatVD}.
5959 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
5960 switch @option{-gnatVd} will leave the checks turned on.
5961 Switch @option{-gnatVD} should be used only if you are sure that all such
5962 expressions have valid values. If you use this switch and invalid values
5963 are present, then the program is erroneous, and wild jumps or memory
5964 overwriting may occur.
5965
5966 @item -gnatVe
5967 @emph{Validity checks for elementary components.}
5968 @cindex @option{-gnatVe} (@command{gcc})
5969 In the absence of this switch, assignments to record or array components are
5970 not validity checked, even if validity checks for assignments generally
5971 (@option{-gnatVc}) are turned on. In Ada, assignment of composite values do not
5972 require valid data, but assignment of individual components does. So for
5973 example, there is a difference between copying the elements of an array with a
5974 slice assignment, compared to assigning element by element in a loop. This
5975 switch allows you to turn off validity checking for components, even when they
5976 are assigned component by component.
5977
5978 @item -gnatVf
5979 @emph{Validity checks for floating-point values.}
5980 @cindex @option{-gnatVf} (@command{gcc})
5981 In the absence of this switch, validity checking occurs only for discrete
5982 values. If @option{-gnatVf} is specified, then validity checking also applies
5983 for floating-point values, and NaNs and infinities are considered invalid,
5984 as well as out of range values for constrained types. Note that this means
5985 that standard IEEE infinity mode is not allowed. The exact contexts
5986 in which floating-point values are checked depends on the setting of other
5987 options. For example,
5988 @option{^-gnatVif^VALIDITY_CHECKING=(IN_PARAMS,FLOATS)^} or
5989 @option{^-gnatVfi^VALIDITY_CHECKING=(FLOATS,IN_PARAMS)^}
5990 (the order does not matter) specifies that floating-point parameters of mode
5991 @code{in} should be validity checked.
5992
5993 @item -gnatVi
5994 @emph{Validity checks for @code{in} mode parameters}
5995 @cindex @option{-gnatVi} (@command{gcc})
5996 Arguments for parameters of mode @code{in} are validity checked in function
5997 and procedure calls at the point of call.
5998
5999 @item -gnatVm
6000 @emph{Validity checks for @code{in out} mode parameters.}
6001 @cindex @option{-gnatVm} (@command{gcc})
6002 Arguments for parameters of mode @code{in out} are validity checked in
6003 procedure calls at the point of call. The @code{'m'} here stands for
6004 modify, since this concerns parameters that can be modified by the call.
6005 Note that there is no specific option to test @code{out} parameters,
6006 but any reference within the subprogram will be tested in the usual
6007 manner, and if an invalid value is copied back, any reference to it
6008 will be subject to validity checking.
6009
6010 @item -gnatVn
6011 @emph{No validity checks.}
6012 @cindex @option{-gnatVn} (@command{gcc})
6013 This switch turns off all validity checking, including the default checking
6014 for case statements and left hand side subscripts. Note that the use of
6015 the switch @option{-gnatp} suppresses all run-time checks, including
6016 validity checks, and thus implies @option{-gnatVn}. When this switch
6017 is used, it cancels any other @option{-gnatV} previously issued.
6018
6019 @item -gnatVo
6020 @emph{Validity checks for operator and attribute operands.}
6021 @cindex @option{-gnatVo} (@command{gcc})
6022 Arguments for predefined operators and attributes are validity checked.
6023 This includes all operators in package @code{Standard},
6024 the shift operators defined as intrinsic in package @code{Interfaces}
6025 and operands for attributes such as @code{Pos}. Checks are also made
6026 on individual component values for composite comparisons, and on the
6027 expressions in type conversions and qualified expressions. Checks are
6028 also made on explicit ranges using @samp{..} (e.g.@: slices, loops etc).
6029
6030 @item -gnatVp
6031 @emph{Validity checks for parameters.}
6032 @cindex @option{-gnatVp} (@command{gcc})
6033 This controls the treatment of parameters within a subprogram (as opposed
6034 to @option{-gnatVi} and @option{-gnatVm} which control validity testing
6035 of parameters on a call. If either of these call options is used, then
6036 normally an assumption is made within a subprogram that the input arguments
6037 have been validity checking at the point of call, and do not need checking
6038 again within a subprogram). If @option{-gnatVp} is set, then this assumption
6039 is not made, and parameters are not assumed to be valid, so their validity
6040 will be checked (or rechecked) within the subprogram.
6041
6042 @item -gnatVr
6043 @emph{Validity checks for function returns.}
6044 @cindex @option{-gnatVr} (@command{gcc})
6045 The expression in @code{return} statements in functions is validity
6046 checked.
6047
6048 @item -gnatVs
6049 @emph{Validity checks for subscripts.}
6050 @cindex @option{-gnatVs} (@command{gcc})
6051 All subscripts expressions are checked for validity, whether they appear
6052 on the right side or left side (in default mode only left side subscripts
6053 are validity checked).
6054
6055 @item -gnatVt
6056 @emph{Validity checks for tests.}
6057 @cindex @option{-gnatVt} (@command{gcc})
6058 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
6059 statements are checked, as well as guard expressions in entry calls.
6060
6061 @end table
6062
6063 @noindent
6064 The @option{-gnatV} switch may be followed by
6065 ^a string of letters^a list of options^
6066 to turn on a series of validity checking options.
6067 For example,
6068 @option{^-gnatVcr^/VALIDITY_CHECKING=(COPIES, RETURNS)^}
6069 specifies that in addition to the default validity checking, copies and
6070 function return expressions are to be validity checked.
6071 In order to make it easier
6072 to specify the desired combination of effects,
6073 @ifclear vms
6074 the upper case letters @code{CDFIMORST} may
6075 be used to turn off the corresponding lower case option.
6076 @end ifclear
6077 @ifset vms
6078 the prefix @code{NO} on an option turns off the corresponding validity
6079 checking:
6080 @itemize @bullet
6081 @item @code{NOCOPIES}
6082 @item @code{NODEFAULT}
6083 @item @code{NOFLOATS}
6084 @item @code{NOIN_PARAMS}
6085 @item @code{NOMOD_PARAMS}
6086 @item @code{NOOPERANDS}
6087 @item @code{NORETURNS}
6088 @item @code{NOSUBSCRIPTS}
6089 @item @code{NOTESTS}
6090 @end itemize
6091 @end ifset
6092 Thus
6093 @option{^-gnatVaM^/VALIDITY_CHECKING=(ALL, NOMOD_PARAMS)^}
6094 turns on all validity checking options except for
6095 checking of @code{@b{in out}} procedure arguments.
6096
6097 The specification of additional validity checking generates extra code (and
6098 in the case of @option{-gnatVa} the code expansion can be substantial).
6099 However, these additional checks can be very useful in detecting
6100 uninitialized variables, incorrect use of unchecked conversion, and other
6101 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
6102 is useful in conjunction with the extra validity checking, since this
6103 ensures that wherever possible uninitialized variables have invalid values.
6104
6105 See also the pragma @code{Validity_Checks} which allows modification of
6106 the validity checking mode at the program source level, and also allows for
6107 temporary disabling of validity checks.
6108
6109 @node Style Checking
6110 @subsection Style Checking
6111 @findex Style checking
6112
6113 @noindent
6114 The @option{-gnaty^x^(option,option,@dots{})^} switch
6115 @cindex @option{-gnaty} (@command{gcc})
6116 causes the compiler to
6117 enforce specified style rules. A limited set of style rules has been used
6118 in writing the GNAT sources themselves. This switch allows user programs
6119 to activate all or some of these checks. If the source program fails a
6120 specified style check, an appropriate warning message is given, preceded by
6121 the character sequence ``(style)''.
6122 @ifset vms
6123 @code{(option,option,@dots{})} is a sequence of keywords
6124 @end ifset
6125 @ifclear vms
6126 The string @var{x} is a sequence of letters or digits
6127 @end ifclear
6128 indicating the particular style
6129 checks to be performed. The following checks are defined:
6130
6131 @table @option
6132 @c !sort!
6133 @item 0-9
6134 @emph{Specify indentation level.}
6135 If a digit from 1-9 appears
6136 ^in the string after @option{-gnaty}^as an option for /STYLE_CHECKS^
6137 then proper indentation is checked, with the digit indicating the
6138 indentation level required. A value of zero turns off this style check.
6139 The general style of required indentation is as specified by
6140 the examples in the Ada Reference Manual. Full line comments must be
6141 aligned with the @code{--} starting on a column that is a multiple of
6142 the alignment level, or they may be aligned the same way as the following
6143 non-blank line (this is useful when full line comments appear in the middle
6144 of a statement.
6145
6146 @item ^a^ATTRIBUTE^
6147 @emph{Check attribute casing.}
6148 Attribute names, including the case of keywords such as @code{digits}
6149 used as attributes names, must be written in mixed case, that is, the
6150 initial letter and any letter following an underscore must be uppercase.
6151 All other letters must be lowercase.
6152
6153 @item ^A^ARRAY_INDEXES^
6154 @emph{Use of array index numbers in array attributes.}
6155 When using the array attributes First, Last, Range,
6156 or Length, the index number must be omitted for one-dimensional arrays
6157 and is required for multi-dimensional arrays.
6158
6159 @item ^b^BLANKS^
6160 @emph{Blanks not allowed at statement end.}
6161 Trailing blanks are not allowed at the end of statements. The purpose of this
6162 rule, together with h (no horizontal tabs), is to enforce a canonical format
6163 for the use of blanks to separate source tokens.
6164
6165 @item ^B^BOOLEAN_OPERATORS^
6166 @emph{Check Boolean operators.}
6167 The use of AND/OR operators is not permitted except in the cases of modular
6168 operands, array operands, and simple stand-alone boolean variables or
6169 boolean constants. In all other cases AND THEN/OR ELSE are required.
6170
6171 @item ^c^COMMENTS^
6172 @emph{Check comments.}
6173 Comments must meet the following set of rules:
6174
6175 @itemize @bullet
6176
6177 @item
6178 The ``@code{--}'' that starts the column must either start in column one,
6179 or else at least one blank must precede this sequence.
6180
6181 @item
6182 Comments that follow other tokens on a line must have at least one blank
6183 following the ``@code{--}'' at the start of the comment.
6184
6185 @item
6186 Full line comments must have two blanks following the ``@code{--}'' that
6187 starts the comment, with the following exceptions.
6188
6189 @item
6190 A line consisting only of the ``@code{--}'' characters, possibly preceded
6191 by blanks is permitted.
6192
6193 @item
6194 A comment starting with ``@code{--x}'' where @code{x} is a special character
6195 is permitted.
6196 This allows proper processing of the output generated by specialized tools
6197 including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK
6198 annotation
6199 language (where ``@code{--#}'' is used). For the purposes of this rule, a
6200 special character is defined as being in one of the ASCII ranges
6201 @code{16#21#@dots{}16#2F#} or @code{16#3A#@dots{}16#3F#}.
6202 Note that this usage is not permitted
6203 in GNAT implementation units (i.e., when @option{-gnatg} is used).
6204
6205 @item
6206 A line consisting entirely of minus signs, possibly preceded by blanks, is
6207 permitted. This allows the construction of box comments where lines of minus
6208 signs are used to form the top and bottom of the box.
6209
6210 @item
6211 A comment that starts and ends with ``@code{--}'' is permitted as long as at
6212 least one blank follows the initial ``@code{--}''. Together with the preceding
6213 rule, this allows the construction of box comments, as shown in the following
6214 example:
6215 @smallexample
6216 ---------------------------
6217 -- This is a box comment --
6218 -- with two text lines.  --
6219 ---------------------------
6220 @end smallexample
6221 @end itemize
6222
6223 @item ^d^DOS_LINE_ENDINGS^
6224 @emph{Check no DOS line terminators present.}
6225 All lines must be terminated by a single ASCII.LF
6226 character (in particular the DOS line terminator sequence CR/LF is not
6227 allowed).
6228
6229 @item ^e^END^
6230 @emph{Check end/exit labels.}
6231 Optional labels on @code{end} statements ending subprograms and on
6232 @code{exit} statements exiting named loops, are required to be present.
6233
6234 @item ^f^VTABS^
6235 @emph{No form feeds or vertical tabs.}
6236 Neither form feeds nor vertical tab characters are permitted
6237 in the source text.
6238
6239 @item ^g^GNAT^
6240 @emph{GNAT style mode}
6241 The set of style check switches is set to match that used by the GNAT sources.
6242 This may be useful when developing code that is eventually intended to be
6243 incorporated into GNAT. For further details, see GNAT sources.
6244
6245 @item ^h^HTABS^
6246 @emph{No horizontal tabs.}
6247 Horizontal tab characters are not permitted in the source text.
6248 Together with the b (no blanks at end of line) check, this
6249 enforces a canonical form for the use of blanks to separate
6250 source tokens.
6251
6252 @item ^i^IF_THEN^
6253 @emph{Check if-then layout.}
6254 The keyword @code{then} must appear either on the same
6255 line as corresponding @code{if}, or on a line on its own, lined
6256 up under the @code{if} with at least one non-blank line in between
6257 containing all or part of the condition to be tested.
6258
6259 @item ^I^IN_MODE^
6260 @emph{check mode IN keywords}
6261 Mode @code{in} (the default mode) is not
6262 allowed to be given explicitly. @code{in out} is fine,
6263 but not @code{in} on its own.
6264
6265 @item ^k^KEYWORD^
6266 @emph{Check keyword casing.}
6267 All keywords must be in lower case (with the exception of keywords
6268 such as @code{digits} used as attribute names to which this check
6269 does not apply).
6270
6271 @item ^l^LAYOUT^
6272 @emph{Check layout.}
6273 Layout of statement and declaration constructs must follow the
6274 recommendations in the Ada Reference Manual, as indicated by the
6275 form of the syntax rules. For example an @code{else} keyword must
6276 be lined up with the corresponding @code{if} keyword.
6277
6278 There are two respects in which the style rule enforced by this check
6279 option are more liberal than those in the Ada Reference Manual. First
6280 in the case of record declarations, it is permissible to put the
6281 @code{record} keyword on the same line as the @code{type} keyword, and
6282 then the @code{end} in @code{end record} must line up under @code{type}.
6283 This is also permitted when the type declaration is split on two lines.
6284 For example, any of the following three layouts is acceptable:
6285
6286 @smallexample @c ada
6287 @cartouche
6288 type q is record
6289    a : integer;
6290    b : integer;
6291 end record;
6292
6293 type q is
6294    record
6295       a : integer;
6296       b : integer;
6297    end record;
6298
6299 type q is
6300    record
6301       a : integer;
6302       b : integer;
6303 end record;
6304
6305 @end cartouche
6306 @end smallexample
6307
6308 @noindent
6309 Second, in the case of a block statement, a permitted alternative
6310 is to put the block label on the same line as the @code{declare} or
6311 @code{begin} keyword, and then line the @code{end} keyword up under
6312 the block label. For example both the following are permitted:
6313
6314 @smallexample @c ada
6315 @cartouche
6316 Block : declare
6317    A : Integer := 3;
6318 begin
6319    Proc (A, A);
6320 end Block;
6321
6322 Block :
6323    declare
6324       A : Integer := 3;
6325    begin
6326       Proc (A, A);
6327    end Block;
6328 @end cartouche
6329 @end smallexample
6330
6331 @noindent
6332 The same alternative format is allowed for loops. For example, both of
6333 the following are permitted:
6334
6335 @smallexample @c ada
6336 @cartouche
6337 Clear : while J < 10 loop
6338    A (J) := 0;
6339 end loop Clear;
6340
6341 Clear :
6342    while J < 10 loop
6343       A (J) := 0;
6344    end loop Clear;
6345 @end cartouche
6346 @end smallexample
6347
6348 @item ^Lnnn^MAX_NESTING=nnn^
6349 @emph{Set maximum nesting level}
6350 The maximum level of nesting of constructs (including subprograms, loops,
6351 blocks, packages, and conditionals) may not exceed the given value
6352 @option{nnn}. A value of zero disconnects this style check.
6353
6354 @item ^m^LINE_LENGTH^
6355 @emph{Check maximum line length.}
6356 The length of source lines must not exceed 79 characters, including
6357 any trailing blanks. The value of 79 allows convenient display on an
6358 80 character wide device or window, allowing for possible special
6359 treatment of 80 character lines. Note that this count is of
6360 characters in the source text. This means that a tab character counts
6361 as one character in this count but a wide character sequence counts as
6362 a single character (however many bytes are needed in the encoding).
6363
6364 @item ^Mnnn^MAX_LENGTH=nnn^
6365 @emph{Set maximum line length.}
6366 The length of lines must not exceed the
6367 given value @option{nnn}. The maximum value that can be specified is 32767.
6368
6369 @item ^n^STANDARD_CASING^
6370 @emph{Check casing of entities in Standard.}
6371 Any identifier from Standard must be cased
6372 to match the presentation in the Ada Reference Manual (for example,
6373 @code{Integer} and @code{ASCII.NUL}).
6374
6375 @item ^N^NONE^
6376 @emph{Turn off all style checks}
6377 All style check options are turned off.
6378
6379 @item ^o^ORDERED_SUBPROGRAMS^
6380 @emph{Check order of subprogram bodies.}
6381 All subprogram bodies in a given scope
6382 (e.g.@: a package body) must be in alphabetical order. The ordering
6383 rule uses normal Ada rules for comparing strings, ignoring casing
6384 of letters, except that if there is a trailing numeric suffix, then
6385 the value of this suffix is used in the ordering (e.g.@: Junk2 comes
6386 before Junk10).
6387
6388 @item ^O^OVERRIDING_INDICATORS^
6389 @emph{Check that overriding subprograms are explicitly marked as such.}
6390 The declaration of a primitive operation of a type extension that overrides
6391 an inherited operation must carry an overriding indicator.
6392
6393 @item ^p^PRAGMA^
6394 @emph{Check pragma casing.}
6395 Pragma names must be written in mixed case, that is, the
6396 initial letter and any letter following an underscore must be uppercase.
6397 All other letters must be lowercase.
6398
6399 @item ^r^REFERENCES^
6400 @emph{Check references.}
6401 All identifier references must be cased in the same way as the
6402 corresponding declaration. No specific casing style is imposed on
6403 identifiers. The only requirement is for consistency of references
6404 with declarations.
6405
6406 @item ^S^STATEMENTS_AFTER_THEN_ELSE^
6407 @emph{Check no statements after THEN/ELSE.}
6408 No statements are allowed
6409 on the same line as a THEN or ELSE keyword following the
6410 keyword in an IF statement. OR ELSE and AND THEN are not affected,
6411 and a special exception allows a pragma to appear after ELSE.
6412
6413 @item ^s^SPECS^
6414 @emph{Check separate specs.}
6415 Separate declarations (``specs'') are required for subprograms (a
6416 body is not allowed to serve as its own declaration). The only
6417 exception is that parameterless library level procedures are
6418 not required to have a separate declaration. This exception covers
6419 the most frequent form of main program procedures.
6420
6421 @item ^t^TOKEN^
6422 @emph{Check token spacing.}
6423 The following token spacing rules are enforced:
6424
6425 @itemize @bullet
6426
6427 @item
6428 The keywords @code{@b{abs}} and @code{@b{not}} must be followed by a space.
6429
6430 @item
6431 The token @code{=>} must be surrounded by spaces.
6432
6433 @item
6434 The token @code{<>} must be preceded by a space or a left parenthesis.
6435
6436 @item
6437 Binary operators other than @code{**} must be surrounded by spaces.
6438 There is no restriction on the layout of the @code{**} binary operator.
6439
6440 @item
6441 Colon must be surrounded by spaces.
6442
6443 @item
6444 Colon-equal (assignment, initialization) must be surrounded by spaces.
6445
6446 @item
6447 Comma must be the first non-blank character on the line, or be
6448 immediately preceded by a non-blank character, and must be followed
6449 by a space.
6450
6451 @item
6452 If the token preceding a left parenthesis ends with a letter or digit, then
6453 a space must separate the two tokens.
6454
6455 @item
6456 if the token following a right parenthesis starts with a letter or digit, then
6457 a space must separate the two tokens.
6458
6459 @item
6460 A right parenthesis must either be the first non-blank character on
6461 a line, or it must be preceded by a non-blank character.
6462
6463 @item
6464 A semicolon must not be preceded by a space, and must not be followed by
6465 a non-blank character.
6466
6467 @item
6468 A unary plus or minus may not be followed by a space.
6469
6470 @item
6471 A vertical bar must be surrounded by spaces.
6472 @end itemize
6473
6474 @item ^u^UNNECESSARY_BLANK_LINES^
6475 @emph{Check unnecessary blank lines.}
6476 Unnecessary blank lines are not allowed. A blank line is considered
6477 unnecessary if it appears at the end of the file, or if more than
6478 one blank line occurs in sequence.
6479
6480 @item ^x^XTRA_PARENS^
6481 @emph{Check extra parentheses.}
6482 Unnecessary extra level of parentheses (C-style) are not allowed
6483 around conditions in @code{if} statements, @code{while} statements and
6484 @code{exit} statements.
6485
6486 @item ^y^ALL_BUILTIN^
6487 @emph{Set all standard style check options}
6488 This is equivalent to @code{gnaty3aAbcefhiklmnprst}, that is all checking
6489 options enabled with the exception of @option{-gnatyo}, @option{-gnatyI},
6490 @option{-gnatyS}, @option{-gnatyLnnn},
6491 @option{-gnatyd}, @option{-gnatyu}, and @option{-gnatyx}.
6492
6493 @ifclear vms
6494 @item -
6495 @emph{Remove style check options}
6496 This causes any subsequent options in the string to act as canceling the
6497 corresponding style check option. To cancel maximum nesting level control,
6498 use @option{L} parameter witout any integer value after that, because any
6499 digit following @option{-} in the parameter string of the @option{-gnaty}
6500 option will be threated as canceling indentation check. The same is true
6501 for @option{M} parameter. @option{y} and @option{N} parameters are not
6502 allowed after @option{-}.
6503
6504 @item +
6505 This causes any subsequent options in the string to enable the corresponding
6506 style check option. That is, it cancels the effect of a previous ^-^REMOVE^,
6507 if any.
6508 @end ifclear
6509
6510 @ifset vms
6511 @item NOxxx
6512 @emph{Removing style check options}
6513 If the name of a style check is preceded by @option{NO} then the corresponding
6514 style check is turned off. For example @option{NOCOMMENTS} turns off style
6515 checking for comments.
6516 @end ifset
6517 @end table
6518
6519 @noindent
6520 In the above rules, appearing in column one is always permitted, that is,
6521 counts as meeting either a requirement for a required preceding space,
6522 or as meeting a requirement for no preceding space.
6523
6524 Appearing at the end of a line is also always permitted, that is, counts
6525 as meeting either a requirement for a following space, or as meeting
6526 a requirement for no following space.
6527
6528 @noindent
6529 If any of these style rules is violated, a message is generated giving
6530 details on the violation. The initial characters of such messages are
6531 always ``@code{(style)}''. Note that these messages are treated as warning
6532 messages, so they normally do not prevent the generation of an object
6533 file. The @option{-gnatwe} switch can be used to treat warning messages,
6534 including style messages, as fatal errors.
6535
6536 The switch
6537 @ifclear vms
6538 @option{-gnaty} on its own (that is not
6539 followed by any letters or digits), then the effect is equivalent
6540 to the use of @option{-gnatyy}, as described above, that is all
6541 built-in standard style check options are enabled.
6542
6543 @end ifclear
6544 @ifset vms
6545 /STYLE_CHECKS=ALL_BUILTIN enables all checking options with
6546 the exception of ORDERED_SUBPROGRAMS, UNNECESSARY_BLANK_LINES,
6547 XTRA_PARENS, and DOS_LINE_ENDINGS. In addition
6548 @end ifset
6549
6550 The switch
6551 @ifclear vms
6552 @option{-gnatyN}
6553 @end ifclear
6554 @ifset vms
6555 /STYLE_CHECKS=NONE
6556 @end ifset
6557 clears any previously set style checks.
6558
6559 @node Run-Time Checks
6560 @subsection Run-Time Checks
6561 @cindex Division by zero
6562 @cindex Access before elaboration
6563 @cindex Checks, division by zero
6564 @cindex Checks, access before elaboration
6565 @cindex Checks, stack overflow checking
6566
6567 @noindent
6568 By default, the following checks are suppressed: integer overflow
6569 checks, stack overflow checks, and checks for access before
6570 elaboration on subprogram calls. All other checks, including range
6571 checks and array bounds checks, are turned on by default. The
6572 following @command{gcc} switches refine this default behavior.
6573
6574 @table @option
6575 @c !sort!
6576 @item -gnatp
6577 @cindex @option{-gnatp} (@command{gcc})
6578 @cindex Suppressing checks
6579 @cindex Checks, suppressing
6580 @findex Suppress
6581 This switch causes the unit to be compiled
6582 as though @code{pragma Suppress (All_checks)}
6583 had been present in the source. Validity checks are also eliminated (in
6584 other words @option{-gnatp} also implies @option{-gnatVn}.
6585 Use this switch to improve the performance
6586 of the code at the expense of safety in the presence of invalid data or
6587 program bugs.
6588
6589 Note that when checks are suppressed, the compiler is allowed, but not
6590 required, to omit the checking code. If the run-time cost of the
6591 checking code is zero or near-zero, the compiler will generate it even
6592 if checks are suppressed. In particular, if the compiler can prove
6593 that a certain check will necessarily fail, it will generate code to
6594 do an unconditional ``raise'', even if checks are suppressed. The
6595 compiler warns in this case. Another case in which checks may not be
6596 eliminated is when they are embedded in certain run time routines such
6597 as math library routines.
6598
6599 Of course, run-time checks are omitted whenever the compiler can prove
6600 that they will not fail, whether or not checks are suppressed.
6601
6602 Note that if you suppress a check that would have failed, program
6603 execution is erroneous, which means the behavior is totally
6604 unpredictable. The program might crash, or print wrong answers, or
6605 do anything else. It might even do exactly what you wanted it to do
6606 (and then it might start failing mysteriously next week or next
6607 year). The compiler will generate code based on the assumption that
6608 the condition being checked is true, which can result in disaster if
6609 that assumption is wrong.
6610
6611 @item -gnato
6612 @cindex @option{-gnato} (@command{gcc})
6613 @cindex Overflow checks
6614 @cindex Check, overflow
6615 Enables overflow checking for integer operations.
6616 This causes GNAT to generate slower and larger executable
6617 programs by adding code to check for overflow (resulting in raising
6618 @code{Constraint_Error} as required by standard Ada
6619 semantics). These overflow checks correspond to situations in which
6620 the true value of the result of an operation may be outside the base
6621 range of the result type. The following example shows the distinction:
6622
6623 @smallexample @c ada
6624 X1 : Integer := "Integer'Last";
6625 X2 : Integer range 1 .. 5 := "5";
6626 X3 : Integer := "Integer'Last";
6627 X4 : Integer range 1 .. 5 := "5";
6628 F  : Float := "2.0E+20";
6629 @dots{}
6630 X1 := X1 + 1;
6631 X2 := X2 + 1;
6632 X3 := Integer (F);
6633 X4 := Integer (F);
6634 @end smallexample
6635
6636 @noindent
6637 Note that if explicit values are assigned at compile time, the
6638 compiler may be able to detect overflow at compile time, in which case
6639 no actual run-time checking code is required, and Constraint_Error
6640 will be raised unconditionally, with or without
6641 @option{-gnato}. That's why the assigned values in the above fragment
6642 are in quotes, the meaning is "assign a value not known to the
6643 compiler that happens to be equal to ...". The remaining discussion
6644 assumes that the compiler cannot detect the values at compile time.
6645
6646 Here the first addition results in a value that is outside the base range
6647 of Integer, and hence requires an overflow check for detection of the
6648 constraint error. Thus the first assignment to @code{X1} raises a
6649 @code{Constraint_Error} exception only if @option{-gnato} is set.
6650
6651 The second increment operation results in a violation of the explicit
6652 range constraint; such range checks are performed by default, and are
6653 unaffected by @option{-gnato}.
6654
6655 The two conversions of @code{F} both result in values that are outside
6656 the base range of type @code{Integer} and thus will raise
6657 @code{Constraint_Error} exceptions only if @option{-gnato} is used.
6658 The fact that the result of the second conversion is assigned to
6659 variable @code{X4} with a restricted range is irrelevant, since the problem
6660 is in the conversion, not the assignment.
6661
6662 Basically the rule is that in the default mode (@option{-gnato} not
6663 used), the generated code assures that all integer variables stay
6664 within their declared ranges, or within the base range if there is
6665 no declared range. This prevents any serious problems like indexes
6666 out of range for array operations.
6667
6668 What is not checked in default mode is an overflow that results in
6669 an in-range, but incorrect value. In the above example, the assignments
6670 to @code{X1}, @code{X2}, @code{X3} all give results that are within the
6671 range of the target variable, but the result is wrong in the sense that
6672 it is too large to be represented correctly. Typically the assignment
6673 to @code{X1} will result in wrap around to the largest negative number.
6674 The conversions of @code{F} will result in some @code{Integer} value
6675 and if that integer value is out of the @code{X4} range then the
6676 subsequent assignment would generate an exception.
6677
6678 @findex Machine_Overflows
6679 Note that the @option{-gnato} switch does not affect the code generated
6680 for any floating-point operations; it applies only to integer
6681 semantics).
6682 For floating-point, GNAT has the @code{Machine_Overflows}
6683 attribute set to @code{False} and the normal mode of operation is to
6684 generate IEEE NaN and infinite values on overflow or invalid operations
6685 (such as dividing 0.0 by 0.0).
6686
6687 The reason that we distinguish overflow checking from other kinds of
6688 range constraint checking is that a failure of an overflow check, unlike
6689 for example the failure of a range check, can result in an incorrect
6690 value, but cannot cause random memory destruction (like an out of range
6691 subscript), or a wild jump (from an out of range case value). Overflow
6692 checking is also quite expensive in time and space, since in general it
6693 requires the use of double length arithmetic.
6694
6695 Note again that @option{-gnato} is off by default, so overflow checking is
6696 not performed in default mode. This means that out of the box, with the
6697 default settings, GNAT does not do all the checks expected from the
6698 language description in the Ada Reference Manual. If you want all constraint
6699 checks to be performed, as described in this Manual, then you must
6700 explicitly use the -gnato switch either on the @command{gnatmake} or
6701 @command{gcc} command.
6702
6703 @item -gnatE
6704 @cindex @option{-gnatE} (@command{gcc})
6705 @cindex Elaboration checks
6706 @cindex Check, elaboration
6707 Enables dynamic checks for access-before-elaboration
6708 on subprogram calls and generic instantiations.
6709 Note that @option{-gnatE} is not necessary for safety, because in the
6710 default mode, GNAT ensures statically that the checks would not fail.
6711 For full details of the effect and use of this switch,
6712 @xref{Compiling Using gcc}.
6713
6714 @item -fstack-check
6715 @cindex @option{-fstack-check} (@command{gcc})
6716 @cindex Stack Overflow Checking
6717 @cindex Checks, stack overflow checking
6718 Activates stack overflow checking. For full details of the effect and use of
6719 this switch see @ref{Stack Overflow Checking}.
6720 @end table
6721
6722 @findex Unsuppress
6723 @noindent
6724 The setting of these switches only controls the default setting of the
6725 checks. You may modify them using either @code{Suppress} (to remove
6726 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
6727 the program source.
6728
6729 @node Using gcc for Syntax Checking
6730 @subsection Using @command{gcc} for Syntax Checking
6731 @table @option
6732 @item -gnats
6733 @cindex @option{-gnats} (@command{gcc})
6734 @ifclear vms
6735
6736 @noindent
6737 The @code{s} stands for ``syntax''.
6738 @end ifclear
6739
6740 Run GNAT in syntax checking only mode. For
6741 example, the command
6742
6743 @smallexample
6744 $ gcc -c -gnats x.adb
6745 @end smallexample
6746
6747 @noindent
6748 compiles file @file{x.adb} in syntax-check-only mode. You can check a
6749 series of files in a single command
6750 @ifclear vms
6751 , and can use wild cards to specify such a group of files.
6752 Note that you must specify the @option{-c} (compile
6753 only) flag in addition to the @option{-gnats} flag.
6754 @end ifclear
6755 .
6756 You may use other switches in conjunction with @option{-gnats}. In
6757 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
6758 format of any generated error messages.
6759
6760 When the source file is empty or contains only empty lines and/or comments,
6761 the output is a warning:
6762
6763 @smallexample
6764 $ gcc -c -gnats -x ada toto.txt
6765 toto.txt:1:01: warning: empty file, contains no compilation units
6766 $
6767 @end smallexample
6768
6769 Otherwise, the output is simply the error messages, if any. No object file or
6770 ALI file is generated by a syntax-only compilation. Also, no units other
6771 than the one specified are accessed. For example, if a unit @code{X}
6772 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
6773 check only mode does not access the source file containing unit
6774 @code{Y}.
6775
6776 @cindex Multiple units, syntax checking
6777 Normally, GNAT allows only a single unit in a source file. However, this
6778 restriction does not apply in syntax-check-only mode, and it is possible
6779 to check a file containing multiple compilation units concatenated
6780 together. This is primarily used by the @code{gnatchop} utility
6781 (@pxref{Renaming Files Using gnatchop}).
6782 @end table
6783
6784 @node Using gcc for Semantic Checking
6785 @subsection Using @command{gcc} for Semantic Checking
6786 @table @option
6787 @item -gnatc
6788 @cindex @option{-gnatc} (@command{gcc})
6789
6790 @ifclear vms
6791 @noindent
6792 The @code{c} stands for ``check''.
6793 @end ifclear
6794 Causes the compiler to operate in semantic check mode,
6795 with full checking for all illegalities specified in the
6796 Ada Reference Manual, but without generation of any object code
6797 (no object file is generated).
6798
6799 Because dependent files must be accessed, you must follow the GNAT
6800 semantic restrictions on file structuring to operate in this mode:
6801
6802 @itemize @bullet
6803 @item
6804 The needed source files must be accessible
6805 (@pxref{Search Paths and the Run-Time Library (RTL)}).
6806
6807 @item
6808 Each file must contain only one compilation unit.
6809
6810 @item
6811 The file name and unit name must match (@pxref{File Naming Rules}).
6812 @end itemize
6813
6814 The output consists of error messages as appropriate. No object file is
6815 generated. An @file{ALI} file is generated for use in the context of
6816 cross-reference tools, but this file is marked as not being suitable
6817 for binding (since no object file is generated).
6818 The checking corresponds exactly to the notion of
6819 legality in the Ada Reference Manual.
6820
6821 Any unit can be compiled in semantics-checking-only mode, including
6822 units that would not normally be compiled (subunits,
6823 and specifications where a separate body is present).
6824 @end table
6825
6826 @node Compiling Different Versions of Ada
6827 @subsection Compiling Different Versions of Ada
6828
6829 @noindent
6830 The switches described in this section allow you to explicitly specify
6831 the version of the Ada language that your programs are written in.
6832 By default @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION},
6833 but you can also specify @value{NONDEFAULTLANGUAGEVERSION} or
6834 indicate Ada 83 compatibility mode.
6835
6836 @table @option
6837 @cindex Compatibility with Ada 83
6838
6839 @item -gnat83 (Ada 83 Compatibility Mode)
6840 @cindex @option{-gnat83} (@command{gcc})
6841 @cindex ACVC, Ada 83 tests
6842 @cindex Ada 83 mode
6843
6844 @noindent
6845 Although GNAT is primarily an Ada 95 / Ada 2005 compiler, this switch
6846 specifies that the program is to be compiled in Ada 83 mode. With
6847 @option{-gnat83}, GNAT rejects most post-Ada 83 extensions and applies Ada 83
6848 semantics where this can be done easily.
6849 It is not possible to guarantee this switch does a perfect
6850 job; some subtle tests, such as are
6851 found in earlier ACVC tests (and that have been removed from the ACATS suite
6852 for Ada 95), might not compile correctly.
6853 Nevertheless, this switch may be useful in some circumstances, for example
6854 where, due to contractual reasons, existing code needs to be maintained
6855 using only Ada 83 features.
6856
6857 With few exceptions (most notably the need to use @code{<>} on
6858 @cindex Generic formal parameters
6859 unconstrained generic formal parameters, the use of the new Ada 95 / Ada 2005
6860 reserved words, and the use of packages
6861 with optional bodies), it is not necessary to specify the
6862 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
6863 exceptions, Ada 95 and Ada 2005 are upwardly compatible with Ada 83. Thus
6864 a correct Ada 83 program is usually also a correct program
6865 in these later versions of the language standard.
6866 For further information, please refer to @ref{Compatibility and Porting Guide}.
6867
6868 @item -gnat95 (Ada 95 mode)
6869 @cindex @option{-gnat95} (@command{gcc})
6870 @cindex Ada 95 mode
6871
6872 @noindent
6873 This switch directs the compiler to implement the Ada 95 version of the
6874 language.
6875 Since Ada 95 is almost completely upwards
6876 compatible with Ada 83, Ada 83 programs may generally be compiled using
6877 this switch (see the description of the @option{-gnat83} switch for further
6878 information about Ada 83 mode).
6879 If an Ada 2005 program is compiled in Ada 95 mode,
6880 uses of the new Ada 2005 features will cause error
6881 messages or warnings.
6882
6883 This switch also can be used to cancel the effect of a previous
6884 @option{-gnat83} or @option{-gnat05} switch earlier in the command line.
6885
6886 @item -gnat05 (Ada 2005 mode)
6887 @cindex @option{-gnat05} (@command{gcc})
6888 @cindex Ada 2005 mode
6889
6890 @noindent
6891 This switch directs the compiler to implement the Ada 2005 version of the
6892 language.
6893 Since Ada 2005 is almost completely upwards
6894 compatible with Ada 95 (and thus also with Ada 83), Ada 83 and Ada 95 programs
6895 may generally be compiled using this switch (see the description of the
6896 @option{-gnat83} and @option{-gnat95} switches for further
6897 information).
6898
6899 For information about the approved ``Ada Issues'' that have been incorporated
6900 into Ada 2005, see @url{http://www.ada-auth.org/cgi-bin/cvsweb.cgi/AIs}.
6901 Included with GNAT releases is a file @file{features-ada0y} that describes
6902 the set of implemented Ada 2005 features.
6903 @end table
6904
6905
6906 @node Character Set Control
6907 @subsection Character Set Control
6908 @table @option
6909 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
6910 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
6911
6912 @noindent
6913 Normally GNAT recognizes the Latin-1 character set in source program
6914 identifiers, as described in the Ada Reference Manual.
6915 This switch causes
6916 GNAT to recognize alternate character sets in identifiers. @var{c} is a
6917 single character ^^or word^ indicating the character set, as follows:
6918
6919 @table @code
6920 @item 1
6921 ISO 8859-1 (Latin-1) identifiers
6922
6923 @item 2
6924 ISO 8859-2 (Latin-2) letters allowed in identifiers
6925
6926 @item 3
6927 ISO 8859-3 (Latin-3) letters allowed in identifiers
6928
6929 @item 4
6930 ISO 8859-4 (Latin-4) letters allowed in identifiers
6931
6932 @item 5
6933 ISO 8859-5 (Cyrillic) letters allowed in identifiers
6934
6935 @item 9
6936 ISO 8859-15 (Latin-9) letters allowed in identifiers
6937
6938 @item ^p^PC^
6939 IBM PC letters (code page 437) allowed in identifiers
6940
6941 @item ^8^PC850^
6942 IBM PC letters (code page 850) allowed in identifiers
6943
6944 @item ^f^FULL_UPPER^
6945 Full upper-half codes allowed in identifiers
6946
6947 @item ^n^NO_UPPER^
6948 No upper-half codes allowed in identifiers
6949
6950 @item ^w^WIDE^
6951 Wide-character codes (that is, codes greater than 255)
6952 allowed in identifiers
6953 @end table
6954
6955 @xref{Foreign Language Representation}, for full details on the
6956 implementation of these character sets.
6957
6958 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
6959 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
6960 Specify the method of encoding for wide characters.
6961 @var{e} is one of the following:
6962
6963 @table @code
6964
6965 @item ^h^HEX^
6966 Hex encoding (brackets coding also recognized)
6967
6968 @item ^u^UPPER^
6969 Upper half encoding (brackets encoding also recognized)
6970
6971 @item ^s^SHIFT_JIS^
6972 Shift/JIS encoding (brackets encoding also recognized)
6973
6974 @item ^e^EUC^
6975 EUC encoding (brackets encoding also recognized)
6976
6977 @item ^8^UTF8^
6978 UTF-8 encoding (brackets encoding also recognized)
6979
6980 @item ^b^BRACKETS^
6981 Brackets encoding only (default value)
6982 @end table
6983 For full details on these encoding
6984 methods see @ref{Wide Character Encodings}.
6985 Note that brackets coding is always accepted, even if one of the other
6986 options is specified, so for example @option{-gnatW8} specifies that both
6987 brackets and UTF-8 encodings will be recognized. The units that are
6988 with'ed directly or indirectly will be scanned using the specified
6989 representation scheme, and so if one of the non-brackets scheme is
6990 used, it must be used consistently throughout the program. However,
6991 since brackets encoding is always recognized, it may be conveniently
6992 used in standard libraries, allowing these libraries to be used with
6993 any of the available coding schemes.
6994 scheme.
6995
6996 If no @option{-gnatW?} parameter is present, then the default
6997 representation is normally Brackets encoding only. However, if the
6998 first three characters of the file are 16#EF# 16#BB# 16#BF# (the standard
6999 byte order mark or BOM for UTF-8), then these three characters are
7000 skipped and the default representation for the file is set to UTF-8.
7001
7002 Note that the wide character representation that is specified (explicitly
7003 or by default) for the main program also acts as the default encoding used
7004 for Wide_Text_IO files if not specifically overridden by a WCEM form
7005 parameter.
7006
7007 @end table
7008 @node File Naming Control
7009 @subsection File Naming Control
7010
7011 @table @option
7012 @item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n}
7013 @cindex @option{-gnatk} (@command{gcc})
7014 Activates file name ``krunching''. @var{n}, a decimal integer in the range
7015 1-999, indicates the maximum allowable length of a file name (not
7016 including the @file{.ads} or @file{.adb} extension). The default is not
7017 to enable file name krunching.
7018
7019 For the source file naming rules, @xref{File Naming Rules}.
7020 @end table
7021
7022 @node Subprogram Inlining Control
7023 @subsection Subprogram Inlining Control
7024
7025 @table @option
7026 @c !sort!
7027 @item -gnatn
7028 @cindex @option{-gnatn} (@command{gcc})
7029 @ifclear vms
7030 The @code{n} here is intended to suggest the first syllable of the
7031 word ``inline''.
7032 @end ifclear
7033 GNAT recognizes and processes @code{Inline} pragmas. However, for the
7034 inlining to actually occur, optimization must be enabled. To enable
7035 inlining of subprograms specified by pragma @code{Inline},
7036 you must also specify this switch.
7037 In the absence of this switch, GNAT does not attempt
7038 inlining and does not need to access the bodies of
7039 subprograms for which @code{pragma Inline} is specified if they are not
7040 in the current unit.
7041
7042 If you specify this switch the compiler will access these bodies,
7043 creating an extra source dependency for the resulting object file, and
7044 where possible, the call will be inlined.
7045 For further details on when inlining is possible
7046 see @ref{Inlining of Subprograms}.
7047
7048 @item -gnatN
7049 @cindex @option{-gnatN} (@command{gcc})
7050 This switch activates front-end inlining which also
7051 generates additional dependencies.
7052
7053 When using a gcc-based back end (in practice this means using any version
7054 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
7055 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
7056 Historically front end inlining was more extensive than the gcc back end
7057 inlining, but that is no longer the case.
7058 @end table
7059
7060 @node Auxiliary Output Control
7061 @subsection Auxiliary Output Control
7062
7063 @table @option
7064 @item -gnatt
7065 @cindex @option{-gnatt} (@command{gcc})
7066 @cindex Writing internal trees
7067 @cindex Internal trees, writing to file
7068 Causes GNAT to write the internal tree for a unit to a file (with the
7069 extension @file{.adt}.
7070 This not normally required, but is used by separate analysis tools.
7071 Typically
7072 these tools do the necessary compilations automatically, so you should
7073 not have to specify this switch in normal operation.
7074 Note that the combination of switches @option{-gnatct}
7075 generates a tree in the form required by ASIS applications.
7076
7077 @item -gnatu
7078 @cindex @option{-gnatu} (@command{gcc})
7079 Print a list of units required by this compilation on @file{stdout}.
7080 The listing includes all units on which the unit being compiled depends
7081 either directly or indirectly.
7082
7083 @ifclear vms
7084 @item -pass-exit-codes
7085 @cindex @option{-pass-exit-codes} (@command{gcc})
7086 If this switch is not used, the exit code returned by @command{gcc} when
7087 compiling multiple files indicates whether all source files have
7088 been successfully used to generate object files or not.
7089
7090 When @option{-pass-exit-codes} is used, @command{gcc} exits with an extended
7091 exit status and allows an integrated development environment to better
7092 react to a compilation failure. Those exit status are:
7093
7094 @table @asis
7095 @item 5
7096 There was an error in at least one source file.
7097 @item 3
7098 At least one source file did not generate an object file.
7099 @item 2
7100 The compiler died unexpectedly (internal error for example).
7101 @item 0
7102 An object file has been generated for every source file.
7103 @end table
7104 @end ifclear
7105 @end table
7106
7107 @node Debugging Control
7108 @subsection Debugging Control
7109
7110 @table @option
7111 @c !sort!
7112 @cindex Debugging options
7113 @ifclear vms
7114 @item -gnatd@var{x}
7115 @cindex @option{-gnatd} (@command{gcc})
7116 Activate internal debugging switches. @var{x} is a letter or digit, or
7117 string of letters or digits, which specifies the type of debugging
7118 outputs desired. Normally these are used only for internal development
7119 or system debugging purposes. You can find full documentation for these
7120 switches in the body of the @code{Debug} unit in the compiler source
7121 file @file{debug.adb}.
7122 @end ifclear
7123
7124 @item -gnatG[=nn]
7125 @cindex @option{-gnatG} (@command{gcc})
7126 This switch causes the compiler to generate auxiliary output containing
7127 a pseudo-source listing of the generated expanded code. Like most Ada
7128 compilers, GNAT works by first transforming the high level Ada code into
7129 lower level constructs. For example, tasking operations are transformed
7130 into calls to the tasking run-time routines. A unique capability of GNAT
7131 is to list this expanded code in a form very close to normal Ada source.
7132 This is very useful in understanding the implications of various Ada
7133 usage on the efficiency of the generated code. There are many cases in
7134 Ada (e.g.@: the use of controlled types), where simple Ada statements can
7135 generate a lot of run-time code. By using @option{-gnatG} you can identify
7136 these cases, and consider whether it may be desirable to modify the coding
7137 approach to improve efficiency.
7138
7139 The optional parameter @code{nn} if present after -gnatG specifies an
7140 alternative maximum line length that overrides the normal default of 72.
7141 This value is in the range 40-999999, values less than 40 being silently
7142 reset to 40. The equal sign is optional.
7143
7144 The format of the output is very similar to standard Ada source, and is
7145 easily understood by an Ada programmer. The following special syntactic
7146 additions correspond to low level features used in the generated code that
7147 do not have any exact analogies in pure Ada source form. The following
7148 is a partial list of these special constructions. See the spec
7149 of package @code{Sprint} in file @file{sprint.ads} for a full list.
7150
7151 If the switch @option{-gnatL} is used in conjunction with
7152 @cindex @option{-gnatL} (@command{gcc})
7153 @option{-gnatG}, then the original source lines are interspersed
7154 in the expanded source (as comment lines with the original line number).
7155
7156 @table @code
7157 @item new @var{xxx} @r{[}storage_pool = @var{yyy}@r{]}
7158 Shows the storage pool being used for an allocator.
7159
7160 @item at end @var{procedure-name};
7161 Shows the finalization (cleanup) procedure for a scope.
7162
7163 @item (if @var{expr} then @var{expr} else @var{expr})
7164 Conditional expression equivalent to the @code{x?y:z} construction in C.
7165
7166 @item @var{target}^^^(@var{source})
7167 A conversion with floating-point truncation instead of rounding.
7168
7169 @item @var{target}?(@var{source})
7170 A conversion that bypasses normal Ada semantic checking. In particular
7171 enumeration types and fixed-point types are treated simply as integers.
7172
7173 @item @var{target}?^^^(@var{source})
7174 Combines the above two cases.
7175
7176 @item @var{x} #/ @var{y}
7177 @itemx @var{x} #mod @var{y}
7178 @itemx @var{x} #* @var{y}
7179 @itemx @var{x} #rem @var{y}
7180 A division or multiplication of fixed-point values which are treated as
7181 integers without any kind of scaling.
7182
7183 @item free @var{expr} @r{[}storage_pool = @var{xxx}@r{]}
7184 Shows the storage pool associated with a @code{free} statement.
7185
7186 @item [subtype or type declaration]
7187 Used to list an equivalent declaration for an internally generated
7188 type that is referenced elsewhere in the listing.
7189
7190 @item freeze @var{type-name} @ovar{actions}
7191 Shows the point at which @var{type-name} is frozen, with possible
7192 associated actions to be performed at the freeze point.
7193
7194 @item reference @var{itype}
7195 Reference (and hence definition) to internal type @var{itype}.
7196
7197 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
7198 Intrinsic function call.
7199
7200 @item @var{label-name} : label
7201 Declaration of label @var{labelname}.
7202
7203 @item #$ @var{subprogram-name}
7204 An implicit call to a run-time support routine
7205 (to meet the requirement of H.3.1(9) in a
7206 convenient manner).
7207
7208 @item @var{expr} && @var{expr} && @var{expr} @dots{} && @var{expr}
7209 A multiple concatenation (same effect as @var{expr} & @var{expr} &
7210 @var{expr}, but handled more efficiently).
7211
7212 @item [constraint_error]
7213 Raise the @code{Constraint_Error} exception.
7214
7215 @item @var{expression}'reference
7216 A pointer to the result of evaluating @var{expression}.
7217
7218 @item @var{target-type}!(@var{source-expression})
7219 An unchecked conversion of @var{source-expression} to @var{target-type}.
7220
7221 @item [@var{numerator}/@var{denominator}]
7222 Used to represent internal real literals (that) have no exact
7223 representation in base 2-16 (for example, the result of compile time
7224 evaluation of the expression 1.0/27.0).
7225 @end table
7226
7227 @item -gnatD[=nn]
7228 @cindex @option{-gnatD} (@command{gcc})
7229 When used in conjunction with @option{-gnatG}, this switch causes
7230 the expanded source, as described above for
7231 @option{-gnatG} to be written to files with names
7232 @file{^xxx.dg^XXX_DG^}, where @file{xxx} is the normal file name,
7233 instead of to the standard output file. For
7234 example, if the source file name is @file{hello.adb}, then a file
7235 @file{^hello.adb.dg^HELLO.ADB_DG^} will be written.  The debugging
7236 information generated by the @command{gcc} @option{^-g^/DEBUG^} switch
7237 will refer to the generated @file{^xxx.dg^XXX_DG^} file. This allows
7238 you to do source level debugging using the generated code which is
7239 sometimes useful for complex code, for example to find out exactly
7240 which part of a complex construction raised an exception. This switch
7241 also suppress generation of cross-reference information (see
7242 @option{-gnatx}) since otherwise the cross-reference information
7243 would refer to the @file{^.dg^.DG^} file, which would cause
7244 confusion since this is not the original source file.
7245
7246 Note that @option{-gnatD} actually implies @option{-gnatG}
7247 automatically, so it is not necessary to give both options.
7248 In other words @option{-gnatD} is equivalent to @option{-gnatDG}).
7249
7250 If the switch @option{-gnatL} is used in conjunction with
7251 @cindex @option{-gnatL} (@command{gcc})
7252 @option{-gnatDG}, then the original source lines are interspersed
7253 in the expanded source (as comment lines with the original line number).
7254
7255 The optional parameter @code{nn} if present after -gnatD specifies an
7256 alternative maximum line length that overrides the normal default of 72.
7257 This value is in the range 40-999999, values less than 40 being silently
7258 reset to 40. The equal sign is optional.
7259
7260 @item -gnatr
7261 @cindex @option{-gnatr} (@command{gcc})
7262 @cindex pragma Restrictions
7263 This switch causes pragma Restrictions to be treated as Restriction_Warnings
7264 so that violation of restrictions causes warnings rather than illegalities.
7265 This is useful during the development process when new restrictions are added
7266 or investigated. The switch also causes pragma Profile to be treated as
7267 Profile_Warnings, and pragma Restricted_Run_Time and pragma Ravenscar set
7268 restriction warnings rather than restrictions.
7269
7270 @ifclear vms
7271 @item -gnatR@r{[}0@r{|}1@r{|}2@r{|}3@r{[}s@r{]]}
7272 @cindex @option{-gnatR} (@command{gcc})
7273 This switch controls output from the compiler of a listing showing
7274 representation information for declared types and objects. For
7275 @option{-gnatR0}, no information is output (equivalent to omitting
7276 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
7277 so @option{-gnatR} with no parameter has the same effect), size and alignment
7278 information is listed for declared array and record types. For
7279 @option{-gnatR2}, size and alignment information is listed for all
7280 declared types and objects. Finally @option{-gnatR3} includes symbolic
7281 expressions for values that are computed at run time for
7282 variant records. These symbolic expressions have a mostly obvious
7283 format with #n being used to represent the value of the n'th
7284 discriminant. See source files @file{repinfo.ads/adb} in the
7285 @code{GNAT} sources for full details on the format of @option{-gnatR3}
7286 output. If the switch is followed by an s (e.g.@: @option{-gnatR2s}), then
7287 the output is to a file with the name @file{^file.rep^file_REP^} where
7288 file is the name of the corresponding source file.
7289 @end ifclear
7290 @ifset vms
7291 @item /REPRESENTATION_INFO
7292 @cindex @option{/REPRESENTATION_INFO} (@command{gcc})
7293 This qualifier controls output from the compiler of a listing showing
7294 representation information for declared types and objects. For
7295 @option{/REPRESENTATION_INFO=NONE}, no information is output
7296 (equivalent to omitting the @option{/REPRESENTATION_INFO} qualifier).
7297 @option{/REPRESENTATION_INFO} without option is equivalent to
7298 @option{/REPRESENTATION_INFO=ARRAYS}.
7299 For @option{/REPRESENTATION_INFO=ARRAYS}, size and alignment
7300 information is listed for declared array and record types. For
7301 @option{/REPRESENTATION_INFO=OBJECTS}, size and alignment information
7302 is listed for all expression information for values that are computed
7303 at run time for variant records. These symbolic expressions have a mostly
7304 obvious format with #n being used to represent the value of the n'th
7305 discriminant. See source files @file{REPINFO.ADS/ADB} in the
7306 @code{GNAT} sources for full details on the format of
7307 @option{/REPRESENTATION_INFO=SYMBOLIC} output.
7308 If _FILE is added at the end of an option
7309 (e.g.@: @option{/REPRESENTATION_INFO=ARRAYS_FILE}),
7310 then the output is to a file with the name @file{file_REP} where
7311 file is the name of the corresponding source file.
7312 @end ifset
7313 Note that it is possible for record components to have zero size. In
7314 this case, the component clause uses an obvious extension of permitted
7315 Ada syntax, for example @code{at 0 range 0 .. -1}.
7316
7317 Representation information requires that code be generated (since it is the
7318 code generator that lays out complex data structures). If an attempt is made
7319 to output representation information when no code is generated, for example
7320 when a subunit is compiled on its own, then no information can be generated
7321 and the compiler outputs a message to this effect.
7322
7323 @item -gnatS
7324 @cindex @option{-gnatS} (@command{gcc})
7325 The use of the switch @option{-gnatS} for an
7326 Ada compilation will cause the compiler to output a
7327 representation of package Standard in a form very
7328 close to standard Ada. It is not quite possible to
7329 do this entirely in standard Ada (since new
7330 numeric base types cannot be created in standard
7331 Ada), but the output is easily
7332 readable to any Ada programmer, and is useful to
7333 determine the characteristics of target dependent
7334 types in package Standard.
7335
7336 @item -gnatx
7337 @cindex @option{-gnatx} (@command{gcc})
7338 Normally the compiler generates full cross-referencing information in
7339 the @file{ALI} file. This information is used by a number of tools,
7340 including @code{gnatfind} and @code{gnatxref}. The @option{-gnatx} switch
7341 suppresses this information. This saves some space and may slightly
7342 speed up compilation, but means that these tools cannot be used.
7343 @end table
7344
7345 @node Exception Handling Control
7346 @subsection Exception Handling Control
7347
7348 @noindent
7349 GNAT uses two methods for handling exceptions at run-time. The
7350 @code{setjmp/longjmp} method saves the context when entering
7351 a frame with an exception handler. Then when an exception is
7352 raised, the context can be restored immediately, without the
7353 need for tracing stack frames. This method provides very fast
7354 exception propagation, but introduces significant overhead for
7355 the use of exception handlers, even if no exception is raised.
7356
7357 The other approach is called ``zero cost'' exception handling.
7358 With this method, the compiler builds static tables to describe
7359 the exception ranges. No dynamic code is required when entering
7360 a frame containing an exception handler. When an exception is
7361 raised, the tables are used to control a back trace of the
7362 subprogram invocation stack to locate the required exception
7363 handler. This method has considerably poorer performance for
7364 the propagation of exceptions, but there is no overhead for
7365 exception handlers if no exception is raised. Note that in this
7366 mode and in the context of mixed Ada and C/C++ programming,
7367 to propagate an exception through a C/C++ code, the C/C++ code
7368 must be compiled with the @option{-funwind-tables} GCC's
7369 option.
7370
7371 The following switches may be used to control which of the
7372 two exception handling methods is used.
7373
7374 @table @option
7375 @c !sort!
7376
7377 @item --RTS=sjlj
7378 @cindex @option{--RTS=sjlj} (@command{gnatmake})
7379 This switch causes the setjmp/longjmp run-time (when available) to be used
7380 for exception handling. If the default
7381 mechanism for the target is zero cost exceptions, then
7382 this switch can be used to modify this default, and must be
7383 used for all units in the partition.
7384 This option is rarely used. One case in which it may be
7385 advantageous is if you have an application where exception
7386 raising is common and the overall performance of the
7387 application is improved by favoring exception propagation.
7388
7389 @item --RTS=zcx
7390 @cindex @option{--RTS=zcx} (@command{gnatmake})
7391 @cindex Zero Cost Exceptions
7392 This switch causes the zero cost approach to be used
7393 for exception handling. If this is the default mechanism for the
7394 target (see below), then this switch is unneeded. If the default
7395 mechanism for the target is setjmp/longjmp exceptions, then
7396 this switch can be used to modify this default, and must be
7397 used for all units in the partition.
7398 This option can only be used if the zero cost approach
7399 is available for the target in use, otherwise it will generate an error.
7400 @end table
7401
7402 @noindent
7403 The same option @option{--RTS} must be used both for @command{gcc}
7404 and @command{gnatbind}. Passing this option to @command{gnatmake}
7405 (@pxref{Switches for gnatmake}) will ensure the required consistency
7406 through the compilation and binding steps.
7407
7408 @node Units to Sources Mapping Files
7409 @subsection Units to Sources Mapping Files
7410
7411 @table @option
7412
7413 @item -gnatem=@var{path}
7414 @cindex @option{-gnatem} (@command{gcc})
7415 A mapping file is a way to communicate to the compiler two mappings:
7416 from unit names to file names (without any directory information) and from
7417 file names to path names (with full directory information). These mappings
7418 are used by the compiler to short-circuit the path search.
7419
7420 The use of mapping files is not required for correct operation of the
7421 compiler, but mapping files can improve efficiency, particularly when
7422 sources are read over a slow network connection. In normal operation,
7423 you need not be concerned with the format or use of mapping files,
7424 and the @option{-gnatem} switch is not a switch that you would use
7425 explicitly. It is intended primarily for use by automatic tools such as
7426 @command{gnatmake} running under the project file facility. The
7427 description here of the format of mapping files is provided
7428 for completeness and for possible use by other tools.
7429
7430 A mapping file is a sequence of sets of three lines. In each set, the
7431 first line is the unit name, in lower case, with @code{%s} appended
7432 for specs and @code{%b} appended for bodies; the second line is the
7433 file name; and the third line is the path name.
7434
7435 Example:
7436 @smallexample
7437    main%b
7438    main.2.ada
7439    /gnat/project1/sources/main.2.ada
7440 @end smallexample
7441
7442 When the switch @option{-gnatem} is specified, the compiler will
7443 create in memory the two mappings from the specified file. If there is
7444 any problem (nonexistent file, truncated file or duplicate entries),
7445 no mapping will be created.
7446
7447 Several @option{-gnatem} switches may be specified; however, only the
7448 last one on the command line will be taken into account.
7449
7450 When using a project file, @command{gnatmake} creates a temporary
7451 mapping file and communicates it to the compiler using this switch.
7452
7453 @end table
7454
7455 @node Integrated Preprocessing
7456 @subsection Integrated Preprocessing
7457
7458 @noindent
7459 GNAT sources may be preprocessed immediately before compilation.
7460 In this case, the actual
7461 text of the source is not the text of the source file, but is derived from it
7462 through a process called preprocessing. Integrated preprocessing is specified
7463 through switches @option{-gnatep} and/or @option{-gnateD}. @option{-gnatep}
7464 indicates, through a text file, the preprocessing data to be used.
7465 @option{-gnateD} specifies or modifies the values of preprocessing symbol.
7466
7467 @noindent
7468 Note that when integrated preprocessing is used, the output from the
7469 preprocessor is not written to any external file. Instead it is passed
7470 internally to the compiler. If you need to preserve the result of
7471 preprocessing in a file, then you should use @command{gnatprep}
7472 to perform the desired preprocessing in stand-alone mode.
7473
7474 @noindent
7475 It is recommended that @command{gnatmake} switch ^-s^/SWITCH_CHECK^ should be
7476 used when Integrated Preprocessing is used. The reason is that preprocessing
7477 with another Preprocessing Data file without changing the sources will
7478 not trigger recompilation without this switch.
7479
7480 @noindent
7481 Note that @command{gnatmake} switch ^-m^/MINIMAL_RECOMPILATION^ will almost
7482 always trigger recompilation for sources that are preprocessed,
7483 because @command{gnatmake} cannot compute the checksum of the source after
7484 preprocessing.
7485
7486 @noindent
7487 The actual preprocessing function is described in details in section
7488 @ref{Preprocessing Using gnatprep}. This section only describes how integrated
7489 preprocessing is triggered and parameterized.
7490
7491 @table @code
7492
7493 @item -gnatep=@var{file}
7494 @cindex @option{-gnatep} (@command{gcc})
7495 This switch indicates to the compiler the file name (without directory
7496 information) of the preprocessor data file to use. The preprocessor data file
7497 should be found in the source directories.
7498
7499 @noindent
7500 A preprocessing data file is a text file with significant lines indicating
7501 how should be preprocessed either a specific source or all sources not
7502 mentioned in other lines. A significant line is a nonempty, non-comment line.
7503 Comments are similar to Ada comments.
7504
7505 @noindent
7506 Each significant line starts with either a literal string or the character '*'.
7507 A literal string is the file name (without directory information) of the source
7508 to preprocess. A character '*' indicates the preprocessing for all the sources
7509 that are not specified explicitly on other lines (order of the lines is not
7510 significant). It is an error to have two lines with the same file name or two
7511 lines starting with the character '*'.
7512
7513 @noindent
7514 After the file name or the character '*', another optional literal string
7515 indicating the file name of the definition file to be used for preprocessing
7516 (@pxref{Form of Definitions File}). The definition files are found by the
7517 compiler in one of the source directories. In some cases, when compiling
7518 a source in a directory other than the current directory, if the definition
7519 file is in the current directory, it may be necessary to add the current
7520 directory as a source directory through switch ^-I.^/SEARCH=[]^, otherwise
7521 the compiler would not find the definition file.
7522
7523 @noindent
7524 Then, optionally, ^switches^switches^ similar to those of @code{gnatprep} may
7525 be found. Those ^switches^switches^ are:
7526
7527 @table @code
7528
7529 @item -b
7530 Causes both preprocessor lines and the lines deleted by
7531 preprocessing to be replaced by blank lines, preserving the line number.
7532 This ^switch^switch^ is always implied; however, if specified after @option{-c}
7533 it cancels the effect of @option{-c}.
7534
7535 @item -c
7536 Causes both preprocessor lines and the lines deleted
7537 by preprocessing to be retained as comments marked
7538 with the special string ``@code{--! }''.
7539
7540 @item -Dsymbol=value
7541 Define or redefine a symbol, associated with value. A symbol is an Ada
7542 identifier, or an Ada reserved word, with the exception of @code{if},
7543 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7544 @code{value} is either a literal string, an Ada identifier or any Ada reserved
7545 word. A symbol declared with this ^switch^switch^ replaces a symbol with the
7546 same name defined in a definition file.
7547
7548 @item -s
7549 Causes a sorted list of symbol names and values to be
7550 listed on the standard output file.
7551
7552 @item -u
7553 Causes undefined symbols to be treated as having the value @code{FALSE}
7554 in the context
7555 of a preprocessor test. In the absence of this option, an undefined symbol in
7556 a @code{#if} or @code{#elsif} test will be treated as an error.
7557
7558 @end table
7559
7560 @noindent
7561 Examples of valid lines in a preprocessor data file:
7562
7563 @smallexample
7564   "toto.adb"  "prep.def" -u
7565   --  preprocess "toto.adb", using definition file "prep.def",
7566   --  undefined symbol are False.
7567
7568   * -c -DVERSION=V101
7569   --  preprocess all other sources without a definition file;
7570   --  suppressed lined are commented; symbol VERSION has the value V101.
7571
7572   "titi.adb" "prep2.def" -s
7573   --  preprocess "titi.adb", using definition file "prep2.def";
7574   --  list all symbols with their values.
7575 @end smallexample
7576
7577 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=value@r{]}
7578 @cindex @option{-gnateD} (@command{gcc})
7579 Define or redefine a preprocessing symbol, associated with value. If no value
7580 is given on the command line, then the value of the symbol is @code{True}.
7581 A symbol is an identifier, following normal Ada (case-insensitive)
7582 rules for its syntax, and value is any sequence (including an empty sequence)
7583 of characters from the set (letters, digits, period, underline).
7584 Ada reserved words may be used as symbols, with the exceptions of @code{if},
7585 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7586
7587 @noindent
7588 A symbol declared with this ^switch^switch^ on the command line replaces a
7589 symbol with the same name either in a definition file or specified with a
7590 ^switch^switch^ -D in the preprocessor data file.
7591
7592 @noindent
7593 This switch is similar to switch @option{^-D^/ASSOCIATE^} of @code{gnatprep}.
7594
7595 @item -gnateG
7596 When integrated preprocessing is performed and the preprocessor modifies
7597 the source text, write the result of this preprocessing into a file
7598 <source>^.prep^_prep^.
7599
7600 @end table
7601
7602 @node Code Generation Control
7603 @subsection Code Generation Control
7604
7605 @noindent
7606
7607 The GCC technology provides a wide range of target dependent
7608 @option{-m} switches for controlling
7609 details of code generation with respect to different versions of
7610 architectures. This includes variations in instruction sets (e.g.@:
7611 different members of the power pc family), and different requirements
7612 for optimal arrangement of instructions (e.g.@: different members of
7613 the x86 family). The list of available @option{-m} switches may be
7614 found in the GCC documentation.
7615
7616 Use of these @option{-m} switches may in some cases result in improved
7617 code performance.
7618
7619 The GNAT Pro technology is tested and qualified without any
7620 @option{-m} switches,
7621 so generally the most reliable approach is to avoid the use of these
7622 switches. However, we generally expect most of these switches to work
7623 successfully with GNAT Pro, and many customers have reported successful
7624 use of these options.
7625
7626 Our general advice is to avoid the use of @option{-m} switches unless
7627 special needs lead to requirements in this area. In particular,
7628 there is no point in using @option{-m} switches to improve performance
7629 unless you actually see a performance improvement.
7630
7631 @ifset vms
7632 @node Return Codes
7633 @subsection Return Codes
7634 @cindex Return Codes
7635 @cindex @option{/RETURN_CODES=VMS}
7636
7637 @noindent
7638 On VMS, GNAT compiled programs return POSIX-style codes by default,
7639 e.g.@: @option{/RETURN_CODES=POSIX}.
7640
7641 To enable VMS style return codes, use GNAT BIND and LINK with the option
7642 @option{/RETURN_CODES=VMS}. For example:
7643
7644 @smallexample
7645 GNAT BIND MYMAIN.ALI /RETURN_CODES=VMS
7646 GNAT LINK MYMAIN.ALI /RETURN_CODES=VMS
7647 @end smallexample
7648
7649 @noindent
7650 Programs built with /RETURN_CODES=VMS are suitable to be called in
7651 VMS DCL scripts. Programs compiled with the default /RETURN_CODES=POSIX
7652 are suitable for spawning with appropriate GNAT RTL routines.
7653
7654 @end ifset
7655
7656 @node Search Paths and the Run-Time Library (RTL)
7657 @section Search Paths and the Run-Time Library (RTL)
7658
7659 @noindent
7660 With the GNAT source-based library system, the compiler must be able to
7661 find source files for units that are needed by the unit being compiled.
7662 Search paths are used to guide this process.
7663
7664 The compiler compiles one source file whose name must be given
7665 explicitly on the command line. In other words, no searching is done
7666 for this file. To find all other source files that are needed (the most
7667 common being the specs of units), the compiler examines the following
7668 directories, in the following order:
7669
7670 @enumerate
7671 @item
7672 The directory containing the source file of the main unit being compiled
7673 (the file name on the command line).
7674
7675 @item
7676 Each directory named by an @option{^-I^/SOURCE_SEARCH^} switch given on the
7677 @command{gcc} command line, in the order given.
7678
7679 @item
7680 @findex ADA_PRJ_INCLUDE_FILE
7681 Each of the directories listed in the text file whose name is given
7682 by the @env{ADA_PRJ_INCLUDE_FILE} ^environment variable^logical name^.
7683
7684 @noindent
7685 @env{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
7686 driver when project files are used. It should not normally be set
7687 by other means.
7688
7689 @item
7690 @findex ADA_INCLUDE_PATH
7691 Each of the directories listed in the value of the
7692 @env{ADA_INCLUDE_PATH} ^environment variable^logical name^.
7693 @ifclear vms
7694 Construct this value
7695 exactly as the @env{PATH} environment variable: a list of directory
7696 names separated by colons (semicolons when working with the NT version).
7697 @end ifclear
7698 @ifset vms
7699 Normally, define this value as a logical name containing a comma separated
7700 list of directory names.
7701
7702 This variable can also be defined by means of an environment string
7703 (an argument to the HP C exec* set of functions).
7704
7705 Logical Name:
7706 @smallexample
7707 DEFINE ANOTHER_PATH FOO:[BAG]
7708 DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
7709 @end smallexample
7710
7711 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
7712 first, followed by the standard Ada
7713 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADAINCLUDE].
7714 If this is not redefined, the user will obtain the HP Ada 83 IO packages
7715 (Text_IO, Sequential_IO, etc)
7716 instead of the standard Ada packages. Thus, in order to get the standard Ada
7717 packages by default, ADA_INCLUDE_PATH must be redefined.
7718 @end ifset
7719
7720 @item
7721 The content of the @file{ada_source_path} file which is part of the GNAT
7722 installation tree and is used to store standard libraries such as the
7723 GNAT Run Time Library (RTL) source files.
7724 @ifclear vms
7725 @ref{Installing a library}
7726 @end ifclear
7727 @end enumerate
7728
7729 @noindent
7730 Specifying the switch @option{^-I-^/NOCURRENT_DIRECTORY^}
7731 inhibits the use of the directory
7732 containing the source file named in the command line. You can still
7733 have this directory on your search path, but in this case it must be
7734 explicitly requested with a @option{^-I^/SOURCE_SEARCH^} switch.
7735
7736 Specifying the switch @option{-nostdinc}
7737 inhibits the search of the default location for the GNAT Run Time
7738 Library (RTL) source files.
7739
7740 The compiler outputs its object files and ALI files in the current
7741 working directory.
7742 @ifclear vms
7743 Caution: The object file can be redirected with the @option{-o} switch;
7744 however, @command{gcc} and @code{gnat1} have not been coordinated on this
7745 so the @file{ALI} file will not go to the right place. Therefore, you should
7746 avoid using the @option{-o} switch.
7747 @end ifclear
7748
7749 @findex System.IO
7750 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
7751 children make up the GNAT RTL, together with the simple @code{System.IO}
7752 package used in the @code{"Hello World"} example. The sources for these units
7753 are needed by the compiler and are kept together in one directory. Not
7754 all of the bodies are needed, but all of the sources are kept together
7755 anyway. In a normal installation, you need not specify these directory
7756 names when compiling or binding. Either the environment variables or
7757 the built-in defaults cause these files to be found.
7758
7759 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
7760 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
7761 consisting of child units of @code{GNAT}. This is a collection of generally
7762 useful types, subprograms, etc. @xref{Top, GNAT Reference Manual, About
7763 This Guid, gnat_rm, GNAT Reference Manual}, for further details.
7764
7765 Besides simplifying access to the RTL, a major use of search paths is
7766 in compiling sources from multiple directories. This can make
7767 development environments much more flexible.
7768
7769 @node Order of Compilation Issues
7770 @section Order of Compilation Issues
7771
7772 @noindent
7773 If, in our earlier example, there was a spec for the @code{hello}
7774 procedure, it would be contained in the file @file{hello.ads}; yet this
7775 file would not have to be explicitly compiled. This is the result of the
7776 model we chose to implement library management. Some of the consequences
7777 of this model are as follows:
7778
7779 @itemize @bullet
7780 @item
7781 There is no point in compiling specs (except for package
7782 specs with no bodies) because these are compiled as needed by clients. If
7783 you attempt a useless compilation, you will receive an error message.
7784 It is also useless to compile subunits because they are compiled as needed
7785 by the parent.
7786
7787 @item
7788 There are no order of compilation requirements: performing a
7789 compilation never obsoletes anything. The only way you can obsolete
7790 something and require recompilations is to modify one of the
7791 source files on which it depends.
7792
7793 @item
7794 There is no library as such, apart from the ALI files
7795 (@pxref{The Ada Library Information Files}, for information on the format
7796 of these files). For now we find it convenient to create separate ALI files,
7797 but eventually the information therein may be incorporated into the object
7798 file directly.
7799
7800 @item
7801 When you compile a unit, the source files for the specs of all units
7802 that it @code{with}'s, all its subunits, and the bodies of any generics it
7803 instantiates must be available (reachable by the search-paths mechanism
7804 described above), or you will receive a fatal error message.
7805 @end itemize
7806
7807 @node Examples
7808 @section Examples
7809
7810 @noindent
7811 The following are some typical Ada compilation command line examples:
7812
7813 @table @code
7814 @item $ gcc -c xyz.adb
7815 Compile body in file @file{xyz.adb} with all default options.
7816
7817 @ifclear vms
7818 @item $ gcc -c -O2 -gnata xyz-def.adb
7819 @end ifclear
7820 @ifset vms
7821 @item $ GNAT COMPILE /OPTIMIZE=ALL -gnata xyz-def.adb
7822 @end ifset
7823
7824 Compile the child unit package in file @file{xyz-def.adb} with extensive
7825 optimizations, and pragma @code{Assert}/@code{Debug} statements
7826 enabled.
7827
7828 @item $ gcc -c -gnatc abc-def.adb
7829 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
7830 mode.
7831 @end table
7832
7833 @node Binding Using gnatbind
7834 @chapter Binding Using @code{gnatbind}
7835 @findex gnatbind
7836
7837 @menu
7838 * Running gnatbind::
7839 * Switches for gnatbind::
7840 * Command-Line Access::
7841 * Search Paths for gnatbind::
7842 * Examples of gnatbind Usage::
7843 @end menu
7844
7845 @noindent
7846 This chapter describes the GNAT binder, @code{gnatbind}, which is used
7847 to bind compiled GNAT objects.
7848
7849 Note: to invoke @code{gnatbind} with a project file, use the @code{gnat}
7850 driver (see @ref{The GNAT Driver and Project Files}).
7851
7852 The @code{gnatbind} program performs four separate functions:
7853
7854 @enumerate
7855 @item
7856 Checks that a program is consistent, in accordance with the rules in
7857 Chapter 10 of the Ada Reference Manual. In particular, error
7858 messages are generated if a program uses inconsistent versions of a
7859 given unit.
7860
7861 @item
7862 Checks that an acceptable order of elaboration exists for the program
7863 and issues an error message if it cannot find an order of elaboration
7864 that satisfies the rules in Chapter 10 of the Ada Language Manual.
7865
7866 @item
7867 Generates a main program incorporating the given elaboration order.
7868 This program is a small Ada package (body and spec) that
7869 must be subsequently compiled
7870 using the GNAT compiler. The necessary compilation step is usually
7871 performed automatically by @command{gnatlink}. The two most important
7872 functions of this program
7873 are to call the elaboration routines of units in an appropriate order
7874 and to call the main program.
7875
7876 @item
7877 Determines the set of object files required by the given main program.
7878 This information is output in the forms of comments in the generated program,
7879 to be read by the @command{gnatlink} utility used to link the Ada application.
7880 @end enumerate
7881
7882 @node Running gnatbind
7883 @section Running @code{gnatbind}
7884
7885 @noindent
7886 The form of the @code{gnatbind} command is
7887
7888 @smallexample
7889 $ gnatbind @ovar{switches} @var{mainprog}@r{[}.ali@r{]} @ovar{switches}
7890 @end smallexample
7891
7892 @noindent
7893 where @file{@var{mainprog}.adb} is the Ada file containing the main program
7894 unit body. If no switches are specified, @code{gnatbind} constructs an Ada
7895 package in two files whose names are
7896 @file{b~@var{mainprog}.ads}, and @file{b~@var{mainprog}.adb}.
7897 For example, if given the
7898 parameter @file{hello.ali}, for a main program contained in file
7899 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
7900 and @file{b~hello.adb}.
7901
7902 When doing consistency checking, the binder takes into consideration
7903 any source files it can locate. For example, if the binder determines
7904 that the given main program requires the package @code{Pack}, whose
7905 @file{.ALI}
7906 file is @file{pack.ali} and whose corresponding source spec file is
7907 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
7908 (using the same search path conventions as previously described for the
7909 @command{gcc} command). If it can locate this source file, it checks that
7910 the time stamps
7911 or source checksums of the source and its references to in @file{ALI} files
7912 match. In other words, any @file{ALI} files that mentions this spec must have
7913 resulted from compiling this version of the source file (or in the case
7914 where the source checksums match, a version close enough that the
7915 difference does not matter).
7916
7917 @cindex Source files, use by binder
7918 The effect of this consistency checking, which includes source files, is
7919 that the binder ensures that the program is consistent with the latest
7920 version of the source files that can be located at bind time. Editing a
7921 source file without compiling files that depend on the source file cause
7922 error messages to be generated by the binder.
7923
7924 For example, suppose you have a main program @file{hello.adb} and a
7925 package @code{P}, from file @file{p.ads} and you perform the following
7926 steps:
7927
7928 @enumerate
7929 @item
7930 Enter @code{gcc -c hello.adb} to compile the main program.
7931
7932 @item
7933 Enter @code{gcc -c p.ads} to compile package @code{P}.
7934
7935 @item
7936 Edit file @file{p.ads}.
7937
7938 @item
7939 Enter @code{gnatbind hello}.
7940 @end enumerate
7941
7942 @noindent
7943 At this point, the file @file{p.ali} contains an out-of-date time stamp
7944 because the file @file{p.ads} has been edited. The attempt at binding
7945 fails, and the binder generates the following error messages:
7946
7947 @smallexample
7948 error: "hello.adb" must be recompiled ("p.ads" has been modified)
7949 error: "p.ads" has been modified and must be recompiled
7950 @end smallexample
7951
7952 @noindent
7953 Now both files must be recompiled as indicated, and then the bind can
7954 succeed, generating a main program. You need not normally be concerned
7955 with the contents of this file, but for reference purposes a sample
7956 binder output file is given in @ref{Example of Binder Output File}.
7957
7958 In most normal usage, the default mode of @command{gnatbind} which is to
7959 generate the main package in Ada, as described in the previous section.
7960 In particular, this means that any Ada programmer can read and understand
7961 the generated main program. It can also be debugged just like any other
7962 Ada code provided the @option{^-g^/DEBUG^} switch is used for
7963 @command{gnatbind} and @command{gnatlink}.
7964
7965 However for some purposes it may be convenient to generate the main
7966 program in C rather than Ada. This may for example be helpful when you
7967 are generating a mixed language program with the main program in C. The
7968 GNAT compiler itself is an example.
7969 The use of the @option{^-C^/BIND_FILE=C^} switch
7970 for both @code{gnatbind} and @command{gnatlink} will cause the program to
7971 be generated in C (and compiled using the gnu C compiler).
7972
7973 @node Switches for gnatbind
7974 @section Switches for @command{gnatbind}
7975
7976 @noindent
7977 The following switches are available with @code{gnatbind}; details will
7978 be presented in subsequent sections.
7979
7980 @menu
7981 * Consistency-Checking Modes::
7982 * Binder Error Message Control::
7983 * Elaboration Control::
7984 * Output Control::
7985 * Binding with Non-Ada Main Programs::
7986 * Binding Programs with No Main Subprogram::
7987 @end menu
7988
7989 @table @option
7990 @c !sort!
7991
7992 @item --version
7993 @cindex @option{--version} @command{gnatbind}
7994 Display Copyright and version, then exit disregarding all other options.
7995
7996 @item --help
7997 @cindex @option{--help} @command{gnatbind}
7998 If @option{--version} was not used, display usage, then exit disregarding
7999 all other options.
8000
8001 @item -a
8002 @cindex @option{-a} @command{gnatbind}
8003 Indicates that, if supported by the platform, the adainit procedure should
8004 be treated as an initialisation routine by the linker (a constructor). This
8005 is intended to be used by the Project Manager to automatically initialize
8006 shared Stand-Alone Libraries.
8007
8008 @item ^-aO^/OBJECT_SEARCH^
8009 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatbind})
8010 Specify directory to be searched for ALI files.
8011
8012 @item ^-aI^/SOURCE_SEARCH^
8013 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
8014 Specify directory to be searched for source file.
8015
8016 @item ^-A^/BIND_FILE=ADA^
8017 @cindex @option{^-A^/BIND_FILE=ADA^} (@command{gnatbind})
8018 Generate binder program in Ada (default)
8019
8020 @item ^-b^/REPORT_ERRORS=BRIEF^
8021 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@command{gnatbind})
8022 Generate brief messages to @file{stderr} even if verbose mode set.
8023
8024 @item ^-c^/NOOUTPUT^
8025 @cindex @option{^-c^/NOOUTPUT^} (@command{gnatbind})
8026 Check only, no generation of binder output file.
8027
8028 @item ^-C^/BIND_FILE=C^
8029 @cindex @option{^-C^/BIND_FILE=C^} (@command{gnatbind})
8030 Generate binder program in C
8031
8032 @item ^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
8033 @cindex @option{^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}} (@command{gnatbind})
8034 This switch can be used to change the default task stack size value
8035 to a specified size @var{nn}, which is expressed in bytes by default, or
8036 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8037 with @var{m}.
8038 In the absence of a @samp{@r{[}k@r{|}m@r{]}} suffix, this switch is equivalent,
8039 in effect, to completing all task specs with
8040 @smallexample @c ada
8041    pragma Storage_Size (nn);
8042 @end smallexample
8043 When they do not already have such a pragma.
8044
8045 @item ^-D^/DEFAULT_SECONDARY_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
8046 @cindex @option{^-D^/DEFAULT_SECONDARY_STACK_SIZE=nnnnn^} (@command{gnatbind})
8047 This switch can be used to change the default secondary stack size value
8048 to a specified size @var{nn}, which is expressed in bytes by default, or
8049 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8050 with @var{m}.
8051
8052 The secondary stack is used to deal with functions that return a variable
8053 sized result, for example a function returning an unconstrained
8054 String. There are two ways in which this secondary stack is allocated.
8055
8056 For most targets, the secondary stack is growing on demand and is allocated
8057 as a chain of blocks in the heap. The -D option is not very
8058 relevant. It only give some control over the size of the allocated
8059 blocks (whose size is the minimum of the default secondary stack size value,
8060 and the actual size needed for the current allocation request).
8061
8062 For certain targets, notably VxWorks 653,
8063 the secondary stack is allocated by carving off a fixed ratio chunk of the
8064 primary task stack. The -D option is used to define the
8065 size of the environment task's secondary stack.
8066
8067 @item ^-e^/ELABORATION_DEPENDENCIES^
8068 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@command{gnatbind})
8069 Output complete list of elaboration-order dependencies.
8070
8071 @item ^-E^/STORE_TRACEBACKS^
8072 @cindex @option{^-E^/STORE_TRACEBACKS^} (@command{gnatbind})
8073 Store tracebacks in exception occurrences when the target supports it.
8074 This is the default with the zero cost exception mechanism.
8075 @ignore
8076 @c The following may get moved to an appendix
8077 This option is currently supported on the following targets:
8078 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
8079 @end ignore
8080 See also the packages @code{GNAT.Traceback} and
8081 @code{GNAT.Traceback.Symbolic} for more information.
8082 @ifclear vms
8083 Note that on x86 ports, you must not use @option{-fomit-frame-pointer}
8084 @command{gcc} option.
8085 @end ifclear
8086
8087 @item ^-F^/FORCE_ELABS_FLAGS^
8088 @cindex @option{^-F^/FORCE_ELABS_FLAGS^} (@command{gnatbind})
8089 Force the checks of elaboration flags. @command{gnatbind} does not normally
8090 generate checks of elaboration flags for the main executable, except when
8091 a Stand-Alone Library is used. However, there are cases when this cannot be
8092 detected by gnatbind. An example is importing an interface of a Stand-Alone
8093 Library through a pragma Import and only specifying through a linker switch
8094 this Stand-Alone Library. This switch is used to guarantee that elaboration
8095 flag checks are generated.
8096
8097 @item ^-h^/HELP^
8098 @cindex @option{^-h^/HELP^} (@command{gnatbind})
8099 Output usage (help) information
8100
8101 @item ^-I^/SEARCH^
8102 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8103 Specify directory to be searched for source and ALI files.
8104
8105 @item ^-I-^/NOCURRENT_DIRECTORY^
8106 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatbind})
8107 Do not look for sources in the current directory where @code{gnatbind} was
8108 invoked, and do not look for ALI files in the directory containing the
8109 ALI file named in the @code{gnatbind} command line.
8110
8111 @item ^-l^/ORDER_OF_ELABORATION^
8112 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@command{gnatbind})
8113 Output chosen elaboration order.
8114
8115 @item ^-L@var{xxx}^/BUILD_LIBRARY=@var{xxx}^
8116 @cindex @option{^-L^/BUILD_LIBRARY^} (@command{gnatbind})
8117 Bind the units for library building. In this case the adainit and
8118 adafinal procedures (@pxref{Binding with Non-Ada Main Programs})
8119 are renamed to ^@var{xxx}init^@var{XXX}INIT^ and
8120 ^@var{xxx}final^@var{XXX}FINAL^.
8121 Implies ^-n^/NOCOMPILE^.
8122 @ifclear vms
8123 (@xref{GNAT and Libraries}, for more details.)
8124 @end ifclear
8125 @ifset vms
8126 On OpenVMS, these init and final procedures are exported in uppercase
8127 letters. For example if /BUILD_LIBRARY=toto is used, the exported name of
8128 the init procedure will be "TOTOINIT" and the exported name of the final
8129 procedure will be "TOTOFINAL".
8130 @end ifset
8131
8132 @item ^-Mxyz^/RENAME_MAIN=xyz^
8133 @cindex @option{^-M^/RENAME_MAIN^} (@command{gnatbind})
8134 Rename generated main program from main to xyz. This option is
8135 supported on cross environments only.
8136
8137 @item ^-m^/ERROR_LIMIT=^@var{n}
8138 @cindex @option{^-m^/ERROR_LIMIT^} (@command{gnatbind})
8139 Limit number of detected errors or warnings to @var{n}, where @var{n} is
8140 in the range 1..999999. The default value if no switch is
8141 given is 9999. If the number of warnings reaches this limit, then a
8142 message is output and further warnings are suppressed, the bind
8143 continues in this case. If the number of errors reaches this
8144 limit, then a message is output and the bind is abandoned.
8145 A value of zero means that no limit is enforced. The equal
8146 sign is optional.
8147
8148 @ifset unw
8149 Furthermore, under Windows, the sources pointed to by the libraries path
8150 set in the registry are not searched for.
8151 @end ifset
8152
8153 @item ^-n^/NOMAIN^
8154 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8155 No main program.
8156
8157 @item -nostdinc
8158 @cindex @option{-nostdinc} (@command{gnatbind})
8159 Do not look for sources in the system default directory.
8160
8161 @item -nostdlib
8162 @cindex @option{-nostdlib} (@command{gnatbind})
8163 Do not look for library files in the system default directory.
8164
8165 @item --RTS=@var{rts-path}
8166 @cindex @option{--RTS} (@code{gnatbind})
8167 Specifies the default location of the runtime library. Same meaning as the
8168 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
8169
8170 @item ^-o ^/OUTPUT=^@var{file}
8171 @cindex @option{^-o ^/OUTPUT^} (@command{gnatbind})
8172 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
8173 Note that if this option is used, then linking must be done manually,
8174 gnatlink cannot be used.
8175
8176 @item ^-O^/OBJECT_LIST^
8177 @cindex @option{^-O^/OBJECT_LIST^} (@command{gnatbind})
8178 Output object list.
8179
8180 @item ^-p^/PESSIMISTIC_ELABORATION^
8181 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@command{gnatbind})
8182 Pessimistic (worst-case) elaboration order
8183
8184 @item ^-R^-R^
8185 @cindex @option{^-R^-R^} (@command{gnatbind})
8186 Output closure source list.
8187
8188 @item ^-s^/READ_SOURCES=ALL^
8189 @cindex @option{^-s^/READ_SOURCES=ALL^} (@command{gnatbind})
8190 Require all source files to be present.
8191
8192 @item ^-S@var{xxx}^/INITIALIZE_SCALARS=@var{xxx}^
8193 @cindex @option{^-S^/INITIALIZE_SCALARS^} (@command{gnatbind})
8194 Specifies the value to be used when detecting uninitialized scalar
8195 objects with pragma Initialize_Scalars.
8196 The @var{xxx} ^string specified with the switch^option^ may be either
8197 @itemize @bullet
8198 @item ``@option{^in^INVALID^}'' requesting an invalid value where possible
8199 @item ``@option{^lo^LOW^}'' for the lowest possible value
8200 @item ``@option{^hi^HIGH^}'' for the highest possible value
8201 @item ``@option{@var{xx}}'' for a value consisting of repeated bytes with the
8202 value @code{16#@var{xx}#} (i.e., @var{xx} is a string of two hexadecimal digits).
8203 @end itemize
8204
8205 In addition, you can specify @option{-Sev} to indicate that the value is
8206 to be set at run time. In this case, the program will look for an environment
8207 @cindex GNAT_INIT_SCALARS
8208 variable of the form @env{GNAT_INIT_SCALARS=@var{xx}}, where @var{xx} is one
8209 of @option{in/lo/hi/@var{xx}} with the same meanings as above.
8210 If no environment variable is found, or if it does not have a valid value,
8211 then the default is @option{in} (invalid values).
8212
8213 @ifclear vms
8214 @item -static
8215 @cindex @option{-static} (@code{gnatbind})
8216 Link against a static GNAT run time.
8217
8218 @item -shared
8219 @cindex @option{-shared} (@code{gnatbind})
8220 Link against a shared GNAT run time when available.
8221 @end ifclear
8222
8223 @item ^-t^/NOTIME_STAMP_CHECK^
8224 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8225 Tolerate time stamp and other consistency errors
8226
8227 @item ^-T@var{n}^/TIME_SLICE=@var{n}^
8228 @cindex @option{^-T^/TIME_SLICE^} (@code{gnatbind})
8229 Set the time slice value to @var{n} milliseconds. If the system supports
8230 the specification of a specific time slice value, then the indicated value
8231 is used. If the system does not support specific time slice values, but
8232 does support some general notion of round-robin scheduling, then any
8233 nonzero value will activate round-robin scheduling.
8234
8235 A value of zero is treated specially. It turns off time
8236 slicing, and in addition, indicates to the tasking run time that the
8237 semantics should match as closely as possible the Annex D
8238 requirements of the Ada RM, and in particular sets the default
8239 scheduling policy to @code{FIFO_Within_Priorities}.
8240
8241 @item ^-u@var{n}^/DYNAMIC_STACK_USAGE=@var{n}^
8242 @cindex @option{^-u^/DYNAMIC_STACK_USAGE^} (@code{gnatbind})
8243 Enable dynamic stack usage, with @var{n} results stored and displayed
8244 at program termination. A result is generated when a task
8245 terminates. Results that can't be stored are displayed on the fly, at
8246 task termination. This option is currently not supported on Itanium
8247 platforms. (See @ref{Dynamic Stack Usage Analysis} for details.)
8248
8249 @item ^-v^/REPORT_ERRORS=VERBOSE^
8250 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8251 Verbose mode. Write error messages, header, summary output to
8252 @file{stdout}.
8253
8254 @ifclear vms
8255 @item -w@var{x}
8256 @cindex @option{-w} (@code{gnatbind})
8257 Warning mode (@var{x}=s/e for suppress/treat as error)
8258 @end ifclear
8259
8260 @ifset vms
8261 @item /WARNINGS=NORMAL
8262 @cindex @option{/WARNINGS} (@code{gnatbind})
8263 Normal warnings mode. Warnings are issued but ignored
8264
8265 @item /WARNINGS=SUPPRESS
8266 @cindex @option{/WARNINGS} (@code{gnatbind})
8267 All warning messages are suppressed
8268
8269 @item /WARNINGS=ERROR
8270 @cindex @option{/WARNINGS} (@code{gnatbind})
8271 Warning messages are treated as fatal errors
8272 @end ifset
8273
8274 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8275 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8276 Override default wide character encoding for standard Text_IO files.
8277
8278 @item ^-x^/READ_SOURCES=NONE^
8279 @cindex @option{^-x^/READ_SOURCES^} (@code{gnatbind})
8280 Exclude source files (check object consistency only).
8281
8282 @ifset vms
8283 @item /READ_SOURCES=AVAILABLE
8284 @cindex @option{/READ_SOURCES} (@code{gnatbind})
8285 Default mode, in which sources are checked for consistency only if
8286 they are available.
8287 @end ifset
8288
8289 @item ^-y^/ENABLE_LEAP_SECONDS^
8290 @cindex @option{^-y^/ENABLE_LEAP_SECONDS^} (@code{gnatbind})
8291 Enable leap seconds support in @code{Ada.Calendar} and its children.
8292
8293 @item ^-z^/ZERO_MAIN^
8294 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8295 No main subprogram.
8296 @end table
8297
8298 @ifclear vms
8299 @noindent
8300 You may obtain this listing of switches by running @code{gnatbind} with
8301 no arguments.
8302 @end ifclear
8303
8304 @node Consistency-Checking Modes
8305 @subsection Consistency-Checking Modes
8306
8307 @noindent
8308 As described earlier, by default @code{gnatbind} checks
8309 that object files are consistent with one another and are consistent
8310 with any source files it can locate. The following switches control binder
8311 access to sources.
8312
8313 @table @option
8314 @c !sort!
8315 @item ^-s^/READ_SOURCES=ALL^
8316 @cindex @option{^-s^/READ_SOURCES=ALL^} (@code{gnatbind})
8317 Require source files to be present. In this mode, the binder must be
8318 able to locate all source files that are referenced, in order to check
8319 their consistency. In normal mode, if a source file cannot be located it
8320 is simply ignored. If you specify this switch, a missing source
8321 file is an error.
8322
8323 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8324 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8325 Override default wide character encoding for standard Text_IO files.
8326 Normally the default wide character encoding method used for standard
8327 [Wide_[Wide_]]Text_IO files is taken from the encoding specified for
8328 the main source input (see description of switch
8329 @option{^-gnatWx^/WIDE_CHARACTER_ENCODING^} for the compiler). The
8330 use of this switch for the binder (which has the same set of
8331 possible arguments) overrides this default as specified.
8332
8333 @item ^-x^/READ_SOURCES=NONE^
8334 @cindex @option{^-x^/READ_SOURCES=NONE^} (@code{gnatbind})
8335 Exclude source files. In this mode, the binder only checks that ALI
8336 files are consistent with one another. Source files are not accessed.
8337 The binder runs faster in this mode, and there is still a guarantee that
8338 the resulting program is self-consistent.
8339 If a source file has been edited since it was last compiled, and you
8340 specify this switch, the binder will not detect that the object
8341 file is out of date with respect to the source file. Note that this is the
8342 mode that is automatically used by @command{gnatmake} because in this
8343 case the checking against sources has already been performed by
8344 @command{gnatmake} in the course of compilation (i.e.@: before binding).
8345
8346 @ifset vms
8347 @item /READ_SOURCES=AVAILABLE
8348 @cindex @code{/READ_SOURCES=AVAILABLE} (@code{gnatbind})
8349 This is the default mode in which source files are checked if they are
8350 available, and ignored if they are not available.
8351 @end ifset
8352 @end table
8353
8354 @node Binder Error Message Control
8355 @subsection Binder Error Message Control
8356
8357 @noindent
8358 The following switches provide control over the generation of error
8359 messages from the binder:
8360
8361 @table @option
8362 @c !sort!
8363 @item ^-v^/REPORT_ERRORS=VERBOSE^
8364 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8365 Verbose mode. In the normal mode, brief error messages are generated to
8366 @file{stderr}. If this switch is present, a header is written
8367 to @file{stdout} and any error messages are directed to @file{stdout}.
8368 All that is written to @file{stderr} is a brief summary message.
8369
8370 @item ^-b^/REPORT_ERRORS=BRIEF^
8371 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@code{gnatbind})
8372 Generate brief error messages to @file{stderr} even if verbose mode is
8373 specified. This is relevant only when used with the
8374 @option{^-v^/REPORT_ERRORS=VERBOSE^} switch.
8375
8376 @ifclear vms
8377 @item -m@var{n}
8378 @cindex @option{-m} (@code{gnatbind})
8379 Limits the number of error messages to @var{n}, a decimal integer in the
8380 range 1-999. The binder terminates immediately if this limit is reached.
8381
8382 @item -M@var{xxx}
8383 @cindex @option{-M} (@code{gnatbind})
8384 Renames the generated main program from @code{main} to @code{xxx}.
8385 This is useful in the case of some cross-building environments, where
8386 the actual main program is separate from the one generated
8387 by @code{gnatbind}.
8388 @end ifclear
8389
8390 @item ^-ws^/WARNINGS=SUPPRESS^
8391 @cindex @option{^-ws^/WARNINGS=SUPPRESS^} (@code{gnatbind})
8392 @cindex Warnings
8393 Suppress all warning messages.
8394
8395 @item ^-we^/WARNINGS=ERROR^
8396 @cindex @option{^-we^/WARNINGS=ERROR^} (@code{gnatbind})
8397 Treat any warning messages as fatal errors.
8398
8399 @ifset vms
8400 @item /WARNINGS=NORMAL
8401 Standard mode with warnings generated, but warnings do not get treated
8402 as errors.
8403 @end ifset
8404
8405 @item ^-t^/NOTIME_STAMP_CHECK^
8406 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8407 @cindex Time stamp checks, in binder
8408 @cindex Binder consistency checks
8409 @cindex Consistency checks, in binder
8410 The binder performs a number of consistency checks including:
8411
8412 @itemize @bullet
8413 @item
8414 Check that time stamps of a given source unit are consistent
8415 @item
8416 Check that checksums of a given source unit are consistent
8417 @item
8418 Check that consistent versions of @code{GNAT} were used for compilation
8419 @item
8420 Check consistency of configuration pragmas as required
8421 @end itemize
8422
8423 @noindent
8424 Normally failure of such checks, in accordance with the consistency
8425 requirements of the Ada Reference Manual, causes error messages to be
8426 generated which abort the binder and prevent the output of a binder
8427 file and subsequent link to obtain an executable.
8428
8429 The @option{^-t^/NOTIME_STAMP_CHECK^} switch converts these error messages
8430 into warnings, so that
8431 binding and linking can continue to completion even in the presence of such
8432 errors. The result may be a failed link (due to missing symbols), or a
8433 non-functional executable which has undefined semantics.
8434 @emph{This means that
8435 @option{^-t^/NOTIME_STAMP_CHECK^} should be used only in unusual situations,
8436 with extreme care.}
8437 @end table
8438
8439 @node Elaboration Control
8440 @subsection Elaboration Control
8441
8442 @noindent
8443 The following switches provide additional control over the elaboration
8444 order. For full details see @ref{Elaboration Order Handling in GNAT}.
8445
8446 @table @option
8447 @item ^-p^/PESSIMISTIC_ELABORATION^
8448 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@code{gnatbind})
8449 Normally the binder attempts to choose an elaboration order that is
8450 likely to minimize the likelihood of an elaboration order error resulting
8451 in raising a @code{Program_Error} exception. This switch reverses the
8452 action of the binder, and requests that it deliberately choose an order
8453 that is likely to maximize the likelihood of an elaboration error.
8454 This is useful in ensuring portability and avoiding dependence on
8455 accidental fortuitous elaboration ordering.
8456
8457 Normally it only makes sense to use the @option{^-p^/PESSIMISTIC_ELABORATION^}
8458 switch if dynamic
8459 elaboration checking is used (@option{-gnatE} switch used for compilation).
8460 This is because in the default static elaboration mode, all necessary
8461 @code{Elaborate} and @code{Elaborate_All} pragmas are implicitly inserted.
8462 These implicit pragmas are still respected by the binder in
8463 @option{^-p^/PESSIMISTIC_ELABORATION^} mode, so a
8464 safe elaboration order is assured.
8465 @end table
8466
8467 @node Output Control
8468 @subsection Output Control
8469
8470 @noindent
8471 The following switches allow additional control over the output
8472 generated by the binder.
8473
8474 @table @option
8475 @c !sort!
8476
8477 @item ^-A^/BIND_FILE=ADA^
8478 @cindex @option{^-A^/BIND_FILE=ADA^} (@code{gnatbind})
8479 Generate binder program in Ada (default). The binder program is named
8480 @file{b~@var{mainprog}.adb} by default. This can be changed with
8481 @option{^-o^/OUTPUT^} @code{gnatbind} option.
8482
8483 @item ^-c^/NOOUTPUT^
8484 @cindex @option{^-c^/NOOUTPUT^} (@code{gnatbind})
8485 Check only. Do not generate the binder output file. In this mode the
8486 binder performs all error checks but does not generate an output file.
8487
8488 @item ^-C^/BIND_FILE=C^
8489 @cindex @option{^-C^/BIND_FILE=C^} (@code{gnatbind})
8490 Generate binder program in C. The binder program is named
8491 @file{b_@var{mainprog}.c}.
8492 This can be changed with @option{^-o^/OUTPUT^} @code{gnatbind}
8493 option.
8494
8495 @item ^-e^/ELABORATION_DEPENDENCIES^
8496 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@code{gnatbind})
8497 Output complete list of elaboration-order dependencies, showing the
8498 reason for each dependency. This output can be rather extensive but may
8499 be useful in diagnosing problems with elaboration order. The output is
8500 written to @file{stdout}.
8501
8502 @item ^-h^/HELP^
8503 @cindex @option{^-h^/HELP^} (@code{gnatbind})
8504 Output usage information. The output is written to @file{stdout}.
8505
8506 @item ^-K^/LINKER_OPTION_LIST^
8507 @cindex @option{^-K^/LINKER_OPTION_LIST^} (@code{gnatbind})
8508 Output linker options to @file{stdout}. Includes library search paths,
8509 contents of pragmas Ident and Linker_Options, and libraries added
8510 by @code{gnatbind}.
8511
8512 @item ^-l^/ORDER_OF_ELABORATION^
8513 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@code{gnatbind})
8514 Output chosen elaboration order. The output is written to @file{stdout}.
8515
8516 @item ^-O^/OBJECT_LIST^
8517 @cindex @option{^-O^/OBJECT_LIST^} (@code{gnatbind})
8518 Output full names of all the object files that must be linked to provide
8519 the Ada component of the program. The output is written to @file{stdout}.
8520 This list includes the files explicitly supplied and referenced by the user
8521 as well as implicitly referenced run-time unit files. The latter are
8522 omitted if the corresponding units reside in shared libraries. The
8523 directory names for the run-time units depend on the system configuration.
8524
8525 @item ^-o ^/OUTPUT=^@var{file}
8526 @cindex @option{^-o^/OUTPUT^} (@code{gnatbind})
8527 Set name of output file to @var{file} instead of the normal
8528 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
8529 binder generated body filename. In C mode you would normally give
8530 @var{file} an extension of @file{.c} because it will be a C source program.
8531 Note that if this option is used, then linking must be done manually.
8532 It is not possible to use gnatlink in this case, since it cannot locate
8533 the binder file.
8534
8535 @item ^-r^/RESTRICTION_LIST^
8536 @cindex @option{^-r^/RESTRICTION_LIST^} (@code{gnatbind})
8537 Generate list of @code{pragma Restrictions} that could be applied to
8538 the current unit. This is useful for code audit purposes, and also may
8539 be used to improve code generation in some cases.
8540
8541 @end table
8542
8543 @node Binding with Non-Ada Main Programs
8544 @subsection Binding with Non-Ada Main Programs
8545
8546 @noindent
8547 In our description so far we have assumed that the main
8548 program is in Ada, and that the task of the binder is to generate a
8549 corresponding function @code{main} that invokes this Ada main
8550 program. GNAT also supports the building of executable programs where
8551 the main program is not in Ada, but some of the called routines are
8552 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
8553 The following switch is used in this situation:
8554
8555 @table @option
8556 @item ^-n^/NOMAIN^
8557 @cindex @option{^-n^/NOMAIN^} (@code{gnatbind})
8558 No main program. The main program is not in Ada.
8559 @end table
8560
8561 @noindent
8562 In this case, most of the functions of the binder are still required,
8563 but instead of generating a main program, the binder generates a file
8564 containing the following callable routines:
8565
8566 @table @code
8567 @item adainit
8568 @findex adainit
8569 You must call this routine to initialize the Ada part of the program by
8570 calling the necessary elaboration routines. A call to @code{adainit} is
8571 required before the first call to an Ada subprogram.
8572
8573 Note that it is assumed that the basic execution environment must be setup
8574 to be appropriate for Ada execution at the point where the first Ada
8575 subprogram is called. In particular, if the Ada code will do any
8576 floating-point operations, then the FPU must be setup in an appropriate
8577 manner. For the case of the x86, for example, full precision mode is
8578 required. The procedure GNAT.Float_Control.Reset may be used to ensure
8579 that the FPU is in the right state.
8580
8581 @item adafinal
8582 @findex adafinal
8583 You must call this routine to perform any library-level finalization
8584 required by the Ada subprograms. A call to @code{adafinal} is required
8585 after the last call to an Ada subprogram, and before the program
8586 terminates.
8587 @end table
8588
8589 @noindent
8590 If the @option{^-n^/NOMAIN^} switch
8591 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8592 @cindex Binder, multiple input files
8593 is given, more than one ALI file may appear on
8594 the command line for @code{gnatbind}. The normal @dfn{closure}
8595 calculation is performed for each of the specified units. Calculating
8596 the closure means finding out the set of units involved by tracing
8597 @code{with} references. The reason it is necessary to be able to
8598 specify more than one ALI file is that a given program may invoke two or
8599 more quite separate groups of Ada units.
8600
8601 The binder takes the name of its output file from the last specified ALI
8602 file, unless overridden by the use of the @option{^-o file^/OUTPUT=file^}.
8603 @cindex @option{^-o^/OUTPUT^} (@command{gnatbind})
8604 The output is an Ada unit in source form that can
8605 be compiled with GNAT unless the -C switch is used in which case the
8606 output is a C source file, which must be compiled using the C compiler.
8607 This compilation occurs automatically as part of the @command{gnatlink}
8608 processing.
8609
8610 Currently the GNAT run time requires a FPU using 80 bits mode
8611 precision. Under targets where this is not the default it is required to
8612 call GNAT.Float_Control.Reset before using floating point numbers (this
8613 include float computation, float input and output) in the Ada code. A
8614 side effect is that this could be the wrong mode for the foreign code
8615 where floating point computation could be broken after this call.
8616
8617 @node Binding Programs with No Main Subprogram
8618 @subsection Binding Programs with No Main Subprogram
8619
8620 @noindent
8621 It is possible to have an Ada program which does not have a main
8622 subprogram. This program will call the elaboration routines of all the
8623 packages, then the finalization routines.
8624
8625 The following switch is used to bind programs organized in this manner:
8626
8627 @table @option
8628 @item ^-z^/ZERO_MAIN^
8629 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8630 Normally the binder checks that the unit name given on the command line
8631 corresponds to a suitable main subprogram. When this switch is used,
8632 a list of ALI files can be given, and the execution of the program
8633 consists of elaboration of these units in an appropriate order. Note
8634 that the default wide character encoding method for standard Text_IO
8635 files is always set to Brackets if this switch is set (you can use
8636 the binder switch
8637 @option{^-Wx^WIDE_CHARACTER_ENCODING^} to override this default).
8638 @end table
8639
8640 @node Command-Line Access
8641 @section Command-Line Access
8642
8643 @noindent
8644 The package @code{Ada.Command_Line} provides access to the command-line
8645 arguments and program name. In order for this interface to operate
8646 correctly, the two variables
8647
8648 @smallexample
8649 @group
8650 int gnat_argc;
8651 char **gnat_argv;
8652 @end group
8653 @end smallexample
8654
8655 @noindent
8656 @findex gnat_argv
8657 @findex gnat_argc
8658 are declared in one of the GNAT library routines. These variables must
8659 be set from the actual @code{argc} and @code{argv} values passed to the
8660 main program. With no @option{^n^/NOMAIN^} present, @code{gnatbind}
8661 generates the C main program to automatically set these variables.
8662 If the @option{^n^/NOMAIN^} switch is used, there is no automatic way to
8663 set these variables. If they are not set, the procedures in
8664 @code{Ada.Command_Line} will not be available, and any attempt to use
8665 them will raise @code{Constraint_Error}. If command line access is
8666 required, your main program must set @code{gnat_argc} and
8667 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
8668 it.
8669
8670 @node Search Paths for gnatbind
8671 @section Search Paths for @code{gnatbind}
8672
8673 @noindent
8674 The binder takes the name of an ALI file as its argument and needs to
8675 locate source files as well as other ALI files to verify object consistency.
8676
8677 For source files, it follows exactly the same search rules as @command{gcc}
8678 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
8679 directories searched are:
8680
8681 @enumerate
8682 @item
8683 The directory containing the ALI file named in the command line, unless
8684 the switch @option{^-I-^/NOCURRENT_DIRECTORY^} is specified.
8685
8686 @item
8687 All directories specified by @option{^-I^/SEARCH^}
8688 switches on the @code{gnatbind}
8689 command line, in the order given.
8690
8691 @item
8692 @findex ADA_PRJ_OBJECTS_FILE
8693 Each of the directories listed in the text file whose name is given
8694 by the @env{ADA_PRJ_OBJECTS_FILE} ^environment variable^logical name^.
8695
8696 @noindent
8697 @env{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
8698 driver when project files are used. It should not normally be set
8699 by other means.
8700
8701 @item
8702 @findex ADA_OBJECTS_PATH
8703 Each of the directories listed in the value of the
8704 @env{ADA_OBJECTS_PATH} ^environment variable^logical name^.
8705 @ifset unw
8706 Construct this value
8707 exactly as the @env{PATH} environment variable: a list of directory
8708 names separated by colons (semicolons when working with the NT version
8709 of GNAT).
8710 @end ifset
8711 @ifset vms
8712 Normally, define this value as a logical name containing a comma separated
8713 list of directory names.
8714
8715 This variable can also be defined by means of an environment string
8716 (an argument to the HP C exec* set of functions).
8717
8718 Logical Name:
8719 @smallexample
8720 DEFINE ANOTHER_PATH FOO:[BAG]
8721 DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
8722 @end smallexample
8723
8724 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
8725 first, followed by the standard Ada
8726 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB].
8727 If this is not redefined, the user will obtain the HP Ada 83 IO packages
8728 (Text_IO, Sequential_IO, etc)
8729 instead of the standard Ada packages. Thus, in order to get the standard Ada
8730 packages by default, ADA_OBJECTS_PATH must be redefined.
8731 @end ifset
8732
8733 @item
8734 The content of the @file{ada_object_path} file which is part of the GNAT
8735 installation tree and is used to store standard libraries such as the
8736 GNAT Run Time Library (RTL) unless the switch @option{-nostdlib} is
8737 specified.
8738 @ifclear vms
8739 @ref{Installing a library}
8740 @end ifclear
8741 @end enumerate
8742
8743 @noindent
8744 In the binder the switch @option{^-I^/SEARCH^}
8745 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8746 is used to specify both source and
8747 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
8748 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
8749 instead if you want to specify
8750 source paths only, and @option{^-aO^/LIBRARY_SEARCH^}
8751 @cindex @option{^-aO^/LIBRARY_SEARCH^} (@command{gnatbind})
8752 if you want to specify library paths
8753 only. This means that for the binder
8754 @option{^-I^/SEARCH=^}@var{dir} is equivalent to
8755 @option{^-aI^/SOURCE_SEARCH=^}@var{dir}
8756 @option{^-aO^/OBJECT_SEARCH=^}@var{dir}.
8757 The binder generates the bind file (a C language source file) in the
8758 current working directory.
8759
8760 @findex Ada
8761 @findex System
8762 @findex Interfaces
8763 @findex GNAT
8764 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
8765 children make up the GNAT Run-Time Library, together with the package
8766 GNAT and its children, which contain a set of useful additional
8767 library functions provided by GNAT. The sources for these units are
8768 needed by the compiler and are kept together in one directory. The ALI
8769 files and object files generated by compiling the RTL are needed by the
8770 binder and the linker and are kept together in one directory, typically
8771 different from the directory containing the sources. In a normal
8772 installation, you need not specify these directory names when compiling
8773 or binding. Either the environment variables or the built-in defaults
8774 cause these files to be found.
8775
8776 Besides simplifying access to the RTL, a major use of search paths is
8777 in compiling sources from multiple directories. This can make
8778 development environments much more flexible.
8779
8780 @node Examples of gnatbind Usage
8781 @section Examples of @code{gnatbind} Usage
8782
8783 @noindent
8784 This section contains a number of examples of using the GNAT binding
8785 utility @code{gnatbind}.
8786
8787 @table @code
8788 @item gnatbind hello
8789 The main program @code{Hello} (source program in @file{hello.adb}) is
8790 bound using the standard switch settings. The generated main program is
8791 @file{b~hello.adb}. This is the normal, default use of the binder.
8792
8793 @ifclear vms
8794 @item gnatbind hello -o mainprog.adb
8795 @end ifclear
8796 @ifset vms
8797 @item gnatbind HELLO.ALI /OUTPUT=Mainprog.ADB
8798 @end ifset
8799 The main program @code{Hello} (source program in @file{hello.adb}) is
8800 bound using the standard switch settings. The generated main program is
8801 @file{mainprog.adb} with the associated spec in
8802 @file{mainprog.ads}. Note that you must specify the body here not the
8803 spec, in the case where the output is in Ada. Note that if this option
8804 is used, then linking must be done manually, since gnatlink will not
8805 be able to find the generated file.
8806
8807 @ifclear vms
8808 @item gnatbind main -C -o mainprog.c -x
8809 @end ifclear
8810 @ifset vms
8811 @item gnatbind MAIN.ALI /BIND_FILE=C /OUTPUT=Mainprog.C /READ_SOURCES=NONE
8812 @end ifset
8813 The main program @code{Main} (source program in
8814 @file{main.adb}) is bound, excluding source files from the
8815 consistency checking, generating
8816 the file @file{mainprog.c}.
8817
8818 @ifclear vms
8819 @item gnatbind -x main_program -C -o mainprog.c
8820 This command is exactly the same as the previous example. Switches may
8821 appear anywhere in the command line, and single letter switches may be
8822 combined into a single switch.
8823 @end ifclear
8824
8825 @ifclear vms
8826 @item gnatbind -n math dbase -C -o ada-control.c
8827 @end ifclear
8828 @ifset vms
8829 @item gnatbind /NOMAIN math dbase /BIND_FILE=C /OUTPUT=ada-control.c
8830 @end ifset
8831 The main program is in a language other than Ada, but calls to
8832 subprograms in packages @code{Math} and @code{Dbase} appear. This call
8833 to @code{gnatbind} generates the file @file{ada-control.c} containing
8834 the @code{adainit} and @code{adafinal} routines to be called before and
8835 after accessing the Ada units.
8836 @end table
8837
8838 @c ------------------------------------
8839 @node Linking Using gnatlink
8840 @chapter Linking Using @command{gnatlink}
8841 @c ------------------------------------
8842 @findex gnatlink
8843
8844 @noindent
8845 This chapter discusses @command{gnatlink}, a tool that links
8846 an Ada program and builds an executable file. This utility
8847 invokes the system linker ^(via the @command{gcc} command)^^
8848 with a correct list of object files and library references.
8849 @command{gnatlink} automatically determines the list of files and
8850 references for the Ada part of a program. It uses the binder file
8851 generated by the @command{gnatbind} to determine this list.
8852
8853 Note: to invoke @code{gnatlink} with a project file, use the @code{gnat}
8854 driver (see @ref{The GNAT Driver and Project Files}).
8855
8856 @menu
8857 * Running gnatlink::
8858 * Switches for gnatlink::
8859 @end menu
8860
8861 @node Running gnatlink
8862 @section Running @command{gnatlink}
8863
8864 @noindent
8865 The form of the @command{gnatlink} command is
8866
8867 @smallexample
8868 $ gnatlink @ovar{switches} @var{mainprog}@r{[}.ali@r{]}
8869            @ovar{non-Ada objects} @ovar{linker options}
8870 @end smallexample
8871
8872 @noindent
8873 The arguments of @command{gnatlink} (switches, main @file{ALI} file,
8874 non-Ada objects
8875 or linker options) may be in any order, provided that no non-Ada object may
8876 be mistaken for a main @file{ALI} file.
8877 Any file name @file{F} without the @file{.ali}
8878 extension will be taken as the main @file{ALI} file if a file exists
8879 whose name is the concatenation of @file{F} and @file{.ali}.
8880
8881 @noindent
8882 @file{@var{mainprog}.ali} references the ALI file of the main program.
8883 The @file{.ali} extension of this file can be omitted. From this
8884 reference, @command{gnatlink} locates the corresponding binder file
8885 @file{b~@var{mainprog}.adb} and, using the information in this file along
8886 with the list of non-Ada objects and linker options, constructs a
8887 linker command file to create the executable.
8888
8889 The arguments other than the @command{gnatlink} switches and the main
8890 @file{ALI} file are passed to the linker uninterpreted.
8891 They typically include the names of
8892 object files for units written in other languages than Ada and any library
8893 references required to resolve references in any of these foreign language
8894 units, or in @code{Import} pragmas in any Ada units.
8895
8896 @var{linker options} is an optional list of linker specific
8897 switches.
8898 The default linker called by gnatlink is @command{gcc} which in
8899 turn calls the appropriate system linker.
8900 Standard options for the linker such as @option{-lmy_lib} or
8901 @option{-Ldir} can be added as is.
8902 For options that are not recognized by
8903 @command{gcc} as linker options, use the @command{gcc} switches
8904 @option{-Xlinker} or @option{-Wl,}.
8905 Refer to the GCC documentation for
8906 details. Here is an example showing how to generate a linker map:
8907
8908 @smallexample
8909 $ ^gnatlink my_prog -Wl,-Map,MAPFILE^GNAT LINK my_prog.ali /MAP^
8910 @end smallexample
8911
8912 Using @var{linker options} it is possible to set the program stack and
8913 heap size.
8914 @ifset unw
8915 See @ref{Setting Stack Size from gnatlink} and
8916 @ref{Setting Heap Size from gnatlink}.
8917 @end ifset
8918
8919 @command{gnatlink} determines the list of objects required by the Ada
8920 program and prepends them to the list of objects passed to the linker.
8921 @command{gnatlink} also gathers any arguments set by the use of
8922 @code{pragma Linker_Options} and adds them to the list of arguments
8923 presented to the linker.
8924
8925 @ifset vms
8926 @command{gnatlink} accepts the following types of extra files on the command
8927 line: objects (@file{.OBJ}), libraries (@file{.OLB}), sharable images
8928 (@file{.EXE}), and options files (@file{.OPT}). These are recognized and
8929 handled according to their extension.
8930 @end ifset
8931
8932 @node Switches for gnatlink
8933 @section Switches for @command{gnatlink}
8934
8935 @noindent
8936 The following switches are available with the @command{gnatlink} utility:
8937
8938 @table @option
8939 @c !sort!
8940
8941 @item --version
8942 @cindex @option{--version} @command{gnatlink}
8943 Display Copyright and version, then exit disregarding all other options.
8944
8945 @item --help
8946 @cindex @option{--help} @command{gnatlink}
8947 If @option{--version} was not used, display usage, then exit disregarding
8948 all other options.
8949
8950 @item ^-A^/BIND_FILE=ADA^
8951 @cindex @option{^-A^/BIND_FILE=ADA^} (@command{gnatlink})
8952 The binder has generated code in Ada. This is the default.
8953
8954 @item ^-C^/BIND_FILE=C^
8955 @cindex @option{^-C^/BIND_FILE=C^} (@command{gnatlink})
8956 If instead of generating a file in Ada, the binder has generated one in
8957 C, then the linker needs to know about it. Use this switch to signal
8958 to @command{gnatlink} that the binder has generated C code rather than
8959 Ada code.
8960
8961 @item ^-f^/FORCE_OBJECT_FILE_LIST^
8962 @cindex Command line length
8963 @cindex @option{^-f^/FORCE_OBJECT_FILE_LIST^} (@command{gnatlink})
8964 On some targets, the command line length is limited, and @command{gnatlink}
8965 will generate a separate file for the linker if the list of object files
8966 is too long.
8967 The @option{^-f^/FORCE_OBJECT_FILE_LIST^} switch forces this file
8968 to be generated even if
8969 the limit is not exceeded. This is useful in some cases to deal with
8970 special situations where the command line length is exceeded.
8971
8972 @item ^-g^/DEBUG^
8973 @cindex Debugging information, including
8974 @cindex @option{^-g^/DEBUG^} (@command{gnatlink})
8975 The option to include debugging information causes the Ada bind file (in
8976 other words, @file{b~@var{mainprog}.adb}) to be compiled with
8977 @option{^-g^/DEBUG^}.
8978 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
8979 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
8980 Without @option{^-g^/DEBUG^}, the binder removes these files by
8981 default. The same procedure apply if a C bind file was generated using
8982 @option{^-C^/BIND_FILE=C^} @code{gnatbind} option, in this case the filenames
8983 are @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
8984
8985 @item ^-n^/NOCOMPILE^
8986 @cindex @option{^-n^/NOCOMPILE^} (@command{gnatlink})
8987 Do not compile the file generated by the binder. This may be used when
8988 a link is rerun with different options, but there is no need to recompile
8989 the binder file.
8990
8991 @item ^-v^/VERBOSE^
8992 @cindex @option{^-v^/VERBOSE^} (@command{gnatlink})
8993 Causes additional information to be output, including a full list of the
8994 included object files. This switch option is most useful when you want
8995 to see what set of object files are being used in the link step.
8996
8997 @item ^-v -v^/VERBOSE/VERBOSE^
8998 @cindex @option{^-v -v^/VERBOSE/VERBOSE^} (@command{gnatlink})
8999 Very verbose mode. Requests that the compiler operate in verbose mode when
9000 it compiles the binder file, and that the system linker run in verbose mode.
9001
9002 @item ^-o ^/EXECUTABLE=^@var{exec-name}
9003 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatlink})
9004 @var{exec-name} specifies an alternate name for the generated
9005 executable program. If this switch is omitted, the executable has the same
9006 name as the main unit. For example, @code{gnatlink try.ali} creates
9007 an executable called @file{^try^TRY.EXE^}.
9008
9009 @ifclear vms
9010 @item -b @var{target}
9011 @cindex @option{-b} (@command{gnatlink})
9012 Compile your program to run on @var{target}, which is the name of a
9013 system configuration. You must have a GNAT cross-compiler built if
9014 @var{target} is not the same as your host system.
9015
9016 @item -B@var{dir}
9017 @cindex @option{-B} (@command{gnatlink})
9018 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
9019 from @var{dir} instead of the default location. Only use this switch
9020 when multiple versions of the GNAT compiler are available.
9021 @xref{Directory Options,,, gcc, The GNU Compiler Collection},
9022 for further details. You would normally use the @option{-b} or
9023 @option{-V} switch instead.
9024
9025 @item --GCC=@var{compiler_name}
9026 @cindex @option{--GCC=compiler_name} (@command{gnatlink})
9027 Program used for compiling the binder file. The default is
9028 @command{gcc}. You need to use quotes around @var{compiler_name} if
9029 @code{compiler_name} contains spaces or other separator characters.
9030 As an example @option{--GCC="foo -x -y"} will instruct @command{gnatlink} to
9031 use @code{foo -x -y} as your compiler. Note that switch @option{-c} is always
9032 inserted after your command name. Thus in the above example the compiler
9033 command that will be used by @command{gnatlink} will be @code{foo -c -x -y}.
9034 A limitation of this syntax is that the name and path name of the executable
9035 itself must not include any embedded spaces. If the compiler executable is
9036 different from the default one (gcc or <prefix>-gcc), then the back-end
9037 switches in the ALI file are not used to compile the binder generated source.
9038 For example, this is the case with @option{--GCC="foo -x -y"}. But the back end
9039 switches will be used for @option{--GCC="gcc -gnatv"}. If several
9040 @option{--GCC=compiler_name} are used, only the last @var{compiler_name}
9041 is taken into account. However, all the additional switches are also taken
9042 into account. Thus,
9043 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9044 @option{--GCC="bar -x -y -z -t"}.
9045
9046 @item --LINK=@var{name}
9047 @cindex @option{--LINK=} (@command{gnatlink})
9048 @var{name} is the name of the linker to be invoked. This is especially
9049 useful in mixed language programs since languages such as C++ require
9050 their own linker to be used. When this switch is omitted, the default
9051 name for the linker is @command{gcc}. When this switch is used, the
9052 specified linker is called instead of @command{gcc} with exactly the same
9053 parameters that would have been passed to @command{gcc} so if the desired
9054 linker requires different parameters it is necessary to use a wrapper
9055 script that massages the parameters before invoking the real linker. It
9056 may be useful to control the exact invocation by using the verbose
9057 switch.
9058
9059 @end ifclear
9060
9061 @ifset vms
9062 @item /DEBUG=TRACEBACK
9063 @cindex @code{/DEBUG=TRACEBACK} (@command{gnatlink})
9064 This qualifier causes sufficient information to be included in the
9065 executable file to allow a traceback, but does not include the full
9066 symbol information needed by the debugger.
9067
9068 @item /IDENTIFICATION="<string>"
9069 @code{"<string>"} specifies the string to be stored in the image file
9070 identification field in the image header.
9071 It overrides any pragma @code{Ident} specified string.
9072
9073 @item /NOINHIBIT-EXEC
9074 Generate the executable file even if there are linker warnings.
9075
9076 @item /NOSTART_FILES
9077 Don't link in the object file containing the ``main'' transfer address.
9078 Used when linking with a foreign language main program compiled with an
9079 HP compiler.
9080
9081 @item /STATIC
9082 Prefer linking with object libraries over sharable images, even without
9083 /DEBUG.
9084 @end ifset
9085
9086 @end table
9087
9088 @node The GNAT Make Program gnatmake
9089 @chapter The GNAT Make Program @command{gnatmake}
9090 @findex gnatmake
9091
9092 @menu
9093 * Running gnatmake::
9094 * Switches for gnatmake::
9095 * Mode Switches for gnatmake::
9096 * Notes on the Command Line::
9097 * How gnatmake Works::
9098 * Examples of gnatmake Usage::
9099 @end menu
9100 @noindent
9101 A typical development cycle when working on an Ada program consists of
9102 the following steps:
9103
9104 @enumerate
9105 @item
9106 Edit some sources to fix bugs.
9107
9108 @item
9109 Add enhancements.
9110
9111 @item
9112 Compile all sources affected.
9113
9114 @item
9115 Rebind and relink.
9116
9117 @item
9118 Test.
9119 @end enumerate
9120
9121 @noindent
9122 The third step can be tricky, because not only do the modified files
9123 @cindex Dependency rules
9124 have to be compiled, but any files depending on these files must also be
9125 recompiled. The dependency rules in Ada can be quite complex, especially
9126 in the presence of overloading, @code{use} clauses, generics and inlined
9127 subprograms.
9128
9129 @command{gnatmake} automatically takes care of the third and fourth steps
9130 of this process. It determines which sources need to be compiled,
9131 compiles them, and binds and links the resulting object files.
9132
9133 Unlike some other Ada make programs, the dependencies are always
9134 accurately recomputed from the new sources. The source based approach of
9135 the GNAT compilation model makes this possible. This means that if
9136 changes to the source program cause corresponding changes in
9137 dependencies, they will always be tracked exactly correctly by
9138 @command{gnatmake}.
9139
9140 @node Running gnatmake
9141 @section Running @command{gnatmake}
9142
9143 @noindent
9144 The usual form of the @command{gnatmake} command is
9145
9146 @smallexample
9147 $ gnatmake @ovar{switches} @var{file_name}
9148       @ovar{file_names} @ovar{mode_switches}
9149 @end smallexample
9150
9151 @noindent
9152 The only required argument is one @var{file_name}, which specifies
9153 a compilation unit that is a main program. Several @var{file_names} can be
9154 specified: this will result in several executables being built.
9155 If @code{switches} are present, they can be placed before the first
9156 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
9157 If @var{mode_switches} are present, they must always be placed after
9158 the last @var{file_name} and all @code{switches}.
9159
9160 If you are using standard file extensions (@file{.adb} and @file{.ads}), then the
9161 extension may be omitted from the @var{file_name} arguments. However, if
9162 you are using non-standard extensions, then it is required that the
9163 extension be given. A relative or absolute directory path can be
9164 specified in a @var{file_name}, in which case, the input source file will
9165 be searched for in the specified directory only. Otherwise, the input
9166 source file will first be searched in the directory where
9167 @command{gnatmake} was invoked and if it is not found, it will be search on
9168 the source path of the compiler as described in
9169 @ref{Search Paths and the Run-Time Library (RTL)}.
9170
9171 All @command{gnatmake} output (except when you specify
9172 @option{^-M^/DEPENDENCIES_LIST^}) is to
9173 @file{stderr}. The output produced by the
9174 @option{^-M^/DEPENDENCIES_LIST^} switch is send to
9175 @file{stdout}.
9176
9177 @node Switches for gnatmake
9178 @section Switches for @command{gnatmake}
9179
9180 @noindent
9181 You may specify any of the following switches to @command{gnatmake}:
9182
9183 @table @option
9184 @c !sort!
9185
9186 @item --version
9187 @cindex @option{--version} @command{gnatmake}
9188 Display Copyright and version, then exit disregarding all other options.
9189
9190 @item --help
9191 @cindex @option{--help} @command{gnatmake}
9192 If @option{--version} was not used, display usage, then exit disregarding
9193 all other options.
9194
9195 @ifclear vms
9196 @item --GCC=@var{compiler_name}
9197 @cindex @option{--GCC=compiler_name} (@command{gnatmake})
9198 Program used for compiling. The default is `@command{gcc}'. You need to use
9199 quotes around @var{compiler_name} if @code{compiler_name} contains
9200 spaces or other separator characters. As an example @option{--GCC="foo -x
9201 -y"} will instruct @command{gnatmake} to use @code{foo -x -y} as your
9202 compiler. A limitation of this syntax is that the name and path name of
9203 the executable itself must not include any embedded spaces. Note that
9204 switch @option{-c} is always inserted after your command name. Thus in the
9205 above example the compiler command that will be used by @command{gnatmake}
9206 will be @code{foo -c -x -y}. If several @option{--GCC=compiler_name} are
9207 used, only the last @var{compiler_name} is taken into account. However,
9208 all the additional switches are also taken into account. Thus,
9209 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9210 @option{--GCC="bar -x -y -z -t"}.
9211
9212 @item --GNATBIND=@var{binder_name}
9213 @cindex @option{--GNATBIND=binder_name} (@command{gnatmake})
9214 Program used for binding. The default is `@code{gnatbind}'. You need to
9215 use quotes around @var{binder_name} if @var{binder_name} contains spaces
9216 or other separator characters. As an example @option{--GNATBIND="bar -x
9217 -y"} will instruct @command{gnatmake} to use @code{bar -x -y} as your
9218 binder. Binder switches that are normally appended by @command{gnatmake}
9219 to `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
9220 A limitation of this syntax is that the name and path name of the executable
9221 itself must not include any embedded spaces.
9222
9223 @item --GNATLINK=@var{linker_name}
9224 @cindex @option{--GNATLINK=linker_name} (@command{gnatmake})
9225 Program used for linking. The default is `@command{gnatlink}'. You need to
9226 use quotes around @var{linker_name} if @var{linker_name} contains spaces
9227 or other separator characters. As an example @option{--GNATLINK="lan -x
9228 -y"} will instruct @command{gnatmake} to use @code{lan -x -y} as your
9229 linker. Linker switches that are normally appended by @command{gnatmake} to
9230 `@command{gnatlink}' are now appended to the end of @code{lan -x -y}.
9231 A limitation of this syntax is that the name and path name of the executable
9232 itself must not include any embedded spaces.
9233
9234 @end ifclear
9235
9236 @item ^-a^/ALL_FILES^
9237 @cindex @option{^-a^/ALL_FILES^} (@command{gnatmake})
9238 Consider all files in the make process, even the GNAT internal system
9239 files (for example, the predefined Ada library files), as well as any
9240 locked files. Locked files are files whose ALI file is write-protected.
9241 By default,
9242 @command{gnatmake} does not check these files,
9243 because the assumption is that the GNAT internal files are properly up
9244 to date, and also that any write protected ALI files have been properly
9245 installed. Note that if there is an installation problem, such that one
9246 of these files is not up to date, it will be properly caught by the
9247 binder.
9248 You may have to specify this switch if you are working on GNAT
9249 itself. The switch @option{^-a^/ALL_FILES^} is also useful
9250 in conjunction with @option{^-f^/FORCE_COMPILE^}
9251 if you need to recompile an entire application,
9252 including run-time files, using special configuration pragmas,
9253 such as a @code{Normalize_Scalars} pragma.
9254
9255 By default
9256 @code{gnatmake ^-a^/ALL_FILES^} compiles all GNAT
9257 internal files with
9258 @ifclear vms
9259 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
9260 @end ifclear
9261 @ifset vms
9262 the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} switch.
9263 @end ifset
9264
9265 @item ^-b^/ACTIONS=BIND^
9266 @cindex @option{^-b^/ACTIONS=BIND^} (@command{gnatmake})
9267 Bind only. Can be combined with @option{^-c^/ACTIONS=COMPILE^} to do
9268 compilation and binding, but no link.
9269 Can be combined with @option{^-l^/ACTIONS=LINK^}
9270 to do binding and linking. When not combined with
9271 @option{^-c^/ACTIONS=COMPILE^}
9272 all the units in the closure of the main program must have been previously
9273 compiled and must be up to date. The root unit specified by @var{file_name}
9274 may be given without extension, with the source extension or, if no GNAT
9275 Project File is specified, with the ALI file extension.
9276
9277 @item ^-c^/ACTIONS=COMPILE^
9278 @cindex @option{^-c^/ACTIONS=COMPILE^} (@command{gnatmake})
9279 Compile only. Do not perform binding, except when @option{^-b^/ACTIONS=BIND^}
9280 is also specified. Do not perform linking, except if both
9281 @option{^-b^/ACTIONS=BIND^} and
9282 @option{^-l^/ACTIONS=LINK^} are also specified.
9283 If the root unit specified by @var{file_name} is not a main unit, this is the
9284 default. Otherwise @command{gnatmake} will attempt binding and linking
9285 unless all objects are up to date and the executable is more recent than
9286 the objects.
9287
9288 @item ^-C^/MAPPING^
9289 @cindex @option{^-C^/MAPPING^} (@command{gnatmake})
9290 Use a temporary mapping file. A mapping file is a way to communicate
9291 to the compiler two mappings: from unit names to file names (without
9292 any directory information) and from file names to path names (with
9293 full directory information). A mapping file can make the compiler's
9294 file searches faster, especially if there are many source directories,
9295 or the sources are read over a slow network connection. If
9296 @option{^-P^/PROJECT_FILE^} is used, a mapping file is always used, so
9297 @option{^-C^/MAPPING^} is unnecessary; in this case the mapping file
9298 is initially populated based on the project file. If
9299 @option{^-C^/MAPPING^} is used without
9300 @option{^-P^/PROJECT_FILE^},
9301 the mapping file is initially empty. Each invocation of the compiler
9302 will add any newly accessed sources to the mapping file.
9303
9304 @item ^-C=^/USE_MAPPING_FILE=^@var{file}
9305 @cindex @option{^-C=^/USE_MAPPING^} (@command{gnatmake})
9306 Use a specific mapping file. The file, specified as a path name (absolute or
9307 relative) by this switch, should already exist, otherwise the switch is
9308 ineffective. The specified mapping file will be communicated to the compiler.
9309 This switch is not compatible with a project file
9310 (^-P^/PROJECT_FILE=^@var{file}) or with multiple compiling processes
9311 (^-j^/PROCESSES=^nnn, when nnn is greater than 1).
9312
9313 @item ^-d^/DISPLAY_PROGRESS^
9314 @cindex @option{^-d^/DISPLAY_PROGRESS^} (@command{gnatmake})
9315 Display progress for each source, up to date or not, as a single line
9316
9317 @smallexample
9318 completed x out of y (zz%)
9319 @end smallexample
9320
9321 If the file needs to be compiled this is displayed after the invocation of
9322 the compiler. These lines are displayed even in quiet output mode.
9323
9324 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
9325 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@command{gnatmake})
9326 Put all object files and ALI file in directory @var{dir}.
9327 If the @option{^-D^/DIRECTORY_OBJECTS^} switch is not used, all object files
9328 and ALI files go in the current working directory.
9329
9330 This switch cannot be used when using a project file.
9331
9332 @ifclear vms
9333 @item -eL
9334 @cindex @option{-eL} (@command{gnatmake})
9335 @cindex symbolic links
9336 Follow all symbolic links when processing project files.
9337 This should be used if your project uses symbolic links for files or
9338 directories, but is not needed in other cases.
9339
9340 @cindex naming scheme
9341 This also assumes that no directory matches the naming scheme for files (for
9342 instance that you do not have a directory called "sources.ads" when using the
9343 default GNAT naming scheme).
9344
9345 When you do not have to use this switch (ie by default), gnatmake is able to
9346 save a lot of system calls (several per source file and object file), which
9347 can result in a significant speed up to load and manipulate a project file,
9348 especially when using source files from a remote system.
9349
9350 @end ifclear
9351
9352 @item ^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^
9353 @cindex @option{^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^} (@command{gnatmake})
9354 Output the commands for the compiler, the binder and the linker
9355 on ^standard output^SYS$OUTPUT^,
9356 instead of ^standard error^SYS$ERROR^.
9357
9358 @item ^-f^/FORCE_COMPILE^
9359 @cindex @option{^-f^/FORCE_COMPILE^} (@command{gnatmake})
9360 Force recompilations. Recompile all sources, even though some object
9361 files may be up to date, but don't recompile predefined or GNAT internal
9362 files or locked files (files with a write-protected ALI file),
9363 unless the @option{^-a^/ALL_FILES^} switch is also specified.
9364
9365 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
9366 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@command{gnatmake})
9367 When using project files, if some errors or warnings are detected during
9368 parsing and verbose mode is not in effect (no use of switch
9369 ^-v^/VERBOSE^), then error lines start with the full path name of the project
9370 file, rather than its simple file name.
9371
9372 @item ^-g^/DEBUG^
9373 @cindex @option{^-g^/DEBUG^} (@command{gnatmake})
9374 Enable debugging. This switch is simply passed to the compiler and to the
9375 linker.
9376
9377 @item ^-i^/IN_PLACE^
9378 @cindex @option{^-i^/IN_PLACE^} (@command{gnatmake})
9379 In normal mode, @command{gnatmake} compiles all object files and ALI files
9380 into the current directory. If the @option{^-i^/IN_PLACE^} switch is used,
9381 then instead object files and ALI files that already exist are overwritten
9382 in place. This means that once a large project is organized into separate
9383 directories in the desired manner, then @command{gnatmake} will automatically
9384 maintain and update this organization. If no ALI files are found on the
9385 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
9386 the new object and ALI files are created in the
9387 directory containing the source being compiled. If another organization
9388 is desired, where objects and sources are kept in different directories,
9389 a useful technique is to create dummy ALI files in the desired directories.
9390 When detecting such a dummy file, @command{gnatmake} will be forced to
9391 recompile the corresponding source file, and it will be put the resulting
9392 object and ALI files in the directory where it found the dummy file.
9393
9394 @item ^-j^/PROCESSES=^@var{n}
9395 @cindex @option{^-j^/PROCESSES^} (@command{gnatmake})
9396 @cindex Parallel make
9397 Use @var{n} processes to carry out the (re)compilations. On a
9398 multiprocessor machine compilations will occur in parallel. In the
9399 event of compilation errors, messages from various compilations might
9400 get interspersed (but @command{gnatmake} will give you the full ordered
9401 list of failing compiles at the end). If this is problematic, rerun
9402 the make process with n set to 1 to get a clean list of messages.
9403
9404 @item ^-k^/CONTINUE_ON_ERROR^
9405 @cindex @option{^-k^/CONTINUE_ON_ERROR^} (@command{gnatmake})
9406 Keep going. Continue as much as possible after a compilation error. To
9407 ease the programmer's task in case of compilation errors, the list of
9408 sources for which the compile fails is given when @command{gnatmake}
9409 terminates.
9410
9411 If @command{gnatmake} is invoked with several @file{file_names} and with this
9412 switch, if there are compilation errors when building an executable,
9413 @command{gnatmake} will not attempt to build the following executables.
9414
9415 @item ^-l^/ACTIONS=LINK^
9416 @cindex @option{^-l^/ACTIONS=LINK^} (@command{gnatmake})
9417 Link only. Can be combined with @option{^-b^/ACTIONS=BIND^} to binding
9418 and linking. Linking will not be performed if combined with
9419 @option{^-c^/ACTIONS=COMPILE^}
9420 but not with @option{^-b^/ACTIONS=BIND^}.
9421 When not combined with @option{^-b^/ACTIONS=BIND^}
9422 all the units in the closure of the main program must have been previously
9423 compiled and must be up to date, and the main program needs to have been bound.
9424 The root unit specified by @var{file_name}
9425 may be given without extension, with the source extension or, if no GNAT
9426 Project File is specified, with the ALI file extension.
9427
9428 @item ^-m^/MINIMAL_RECOMPILATION^
9429 @cindex @option{^-m^/MINIMAL_RECOMPILATION^} (@command{gnatmake})
9430 Specify that the minimum necessary amount of recompilations
9431 be performed. In this mode @command{gnatmake} ignores time
9432 stamp differences when the only
9433 modifications to a source file consist in adding/removing comments,
9434 empty lines, spaces or tabs. This means that if you have changed the
9435 comments in a source file or have simply reformatted it, using this
9436 switch will tell @command{gnatmake} not to recompile files that depend on it
9437 (provided other sources on which these files depend have undergone no
9438 semantic modifications). Note that the debugging information may be
9439 out of date with respect to the sources if the @option{-m} switch causes
9440 a compilation to be switched, so the use of this switch represents a
9441 trade-off between compilation time and accurate debugging information.
9442
9443 @item ^-M^/DEPENDENCIES_LIST^
9444 @cindex Dependencies, producing list
9445 @cindex @option{^-M^/DEPENDENCIES_LIST^} (@command{gnatmake})
9446 Check if all objects are up to date. If they are, output the object
9447 dependences to @file{stdout} in a form that can be directly exploited in
9448 a @file{Makefile}. By default, each source file is prefixed with its
9449 (relative or absolute) directory name. This name is whatever you
9450 specified in the various @option{^-aI^/SOURCE_SEARCH^}
9451 and @option{^-I^/SEARCH^} switches. If you use
9452 @code{gnatmake ^-M^/DEPENDENCIES_LIST^}
9453 @option{^-q^/QUIET^}
9454 (see below), only the source file names,
9455 without relative paths, are output. If you just specify the
9456 @option{^-M^/DEPENDENCIES_LIST^}
9457 switch, dependencies of the GNAT internal system files are omitted. This
9458 is typically what you want. If you also specify
9459 the @option{^-a^/ALL_FILES^} switch,
9460 dependencies of the GNAT internal files are also listed. Note that
9461 dependencies of the objects in external Ada libraries (see switch
9462 @option{^-aL^/SKIP_MISSING=^}@var{dir} in the following list)
9463 are never reported.
9464
9465 @item ^-n^/DO_OBJECT_CHECK^
9466 @cindex @option{^-n^/DO_OBJECT_CHECK^} (@command{gnatmake})
9467 Don't compile, bind, or link. Checks if all objects are up to date.
9468 If they are not, the full name of the first file that needs to be
9469 recompiled is printed.
9470 Repeated use of this option, followed by compiling the indicated source
9471 file, will eventually result in recompiling all required units.
9472
9473 @item ^-o ^/EXECUTABLE=^@var{exec_name}
9474 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatmake})
9475 Output executable name. The name of the final executable program will be
9476 @var{exec_name}. If the @option{^-o^/EXECUTABLE^} switch is omitted the default
9477 name for the executable will be the name of the input file in appropriate form
9478 for an executable file on the host system.
9479
9480 This switch cannot be used when invoking @command{gnatmake} with several
9481 @file{file_names}.
9482
9483 @item ^-p or --create-missing-dirs^/CREATE_MISSING_DIRS^
9484 @cindex @option{^-p^/CREATE_MISSING_DIRS^} (@command{gnatmake})
9485 When using project files (^-P^/PROJECT_FILE=^@var{project}), create
9486 automatically missing object directories, library directories and exec
9487 directories.
9488
9489 @item ^-P^/PROJECT_FILE=^@var{project}
9490 @cindex @option{^-P^/PROJECT_FILE^} (@command{gnatmake})
9491 Use project file @var{project}. Only one such switch can be used.
9492 @xref{gnatmake and Project Files}.
9493
9494 @item ^-q^/QUIET^
9495 @cindex @option{^-q^/QUIET^} (@command{gnatmake})
9496 Quiet. When this flag is not set, the commands carried out by
9497 @command{gnatmake} are displayed.
9498
9499 @item ^-s^/SWITCH_CHECK/^
9500 @cindex @option{^-s^/SWITCH_CHECK^} (@command{gnatmake})
9501 Recompile if compiler switches have changed since last compilation.
9502 All compiler switches but -I and -o are taken into account in the
9503 following way:
9504 orders between different ``first letter'' switches are ignored, but
9505 orders between same switches are taken into account. For example,
9506 @option{-O -O2} is different than @option{-O2 -O}, but @option{-g -O}
9507 is equivalent to @option{-O -g}.
9508
9509 This switch is recommended when Integrated Preprocessing is used.
9510
9511 @item ^-u^/UNIQUE^
9512 @cindex @option{^-u^/UNIQUE^} (@command{gnatmake})
9513 Unique. Recompile at most the main files. It implies -c. Combined with
9514 -f, it is equivalent to calling the compiler directly. Note that using
9515 ^-u^/UNIQUE^ with a project file and no main has a special meaning
9516 (@pxref{Project Files and Main Subprograms}).
9517
9518 @item ^-U^/ALL_PROJECTS^
9519 @cindex @option{^-U^/ALL_PROJECTS^} (@command{gnatmake})
9520 When used without a project file or with one or several mains on the command
9521 line, is equivalent to ^-u^/UNIQUE^. When used with a project file and no main
9522 on the command line, all sources of all project files are checked and compiled
9523 if not up to date, and libraries are rebuilt, if necessary.
9524
9525 @item ^-v^/REASONS^
9526 @cindex @option{^-v^/REASONS^} (@command{gnatmake})
9527 Verbose. Display the reason for all recompilations @command{gnatmake}
9528 decides are necessary, with the highest verbosity level.
9529
9530 @item ^-vl^/LOW_VERBOSITY^
9531 @cindex @option{^-vl^/LOW_VERBOSITY^} (@command{gnatmake})
9532 Verbosity level Low. Display fewer lines than in verbosity Medium.
9533
9534 @item ^-vm^/MEDIUM_VERBOSITY^
9535 @cindex @option{^-vm^/MEDIUM_VERBOSITY^} (@command{gnatmake})
9536 Verbosity level Medium. Potentially display fewer lines than in verbosity High.
9537
9538 @item ^-vh^/HIGH_VERBOSITY^
9539 @cindex @option{^-vm^/HIGH_VERBOSITY^} (@command{gnatmake})
9540 Verbosity level High. Equivalent to ^-v^/REASONS^.
9541
9542 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
9543 Indicate the verbosity of the parsing of GNAT project files.
9544 @xref{Switches Related to Project Files}.
9545
9546 @item ^-x^/NON_PROJECT_UNIT_COMPILATION^
9547 @cindex @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} (@command{gnatmake})
9548 Indicate that sources that are not part of any Project File may be compiled.
9549 Normally, when using Project Files, only sources that are part of a Project
9550 File may be compile. When this switch is used, a source outside of all Project
9551 Files may be compiled. The ALI file and the object file will be put in the
9552 object directory of the main Project. The compilation switches used will only
9553 be those specified on the command line. Even when
9554 @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} is used, mains specified on the
9555 command line need to be sources of a project file.
9556
9557 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
9558 Indicate that external variable @var{name} has the value @var{value}.
9559 The Project Manager will use this value for occurrences of
9560 @code{external(name)} when parsing the project file.
9561 @xref{Switches Related to Project Files}.
9562
9563 @item ^-z^/NOMAIN^
9564 @cindex @option{^-z^/NOMAIN^} (@command{gnatmake})
9565 No main subprogram. Bind and link the program even if the unit name
9566 given on the command line is a package name. The resulting executable
9567 will execute the elaboration routines of the package and its closure,
9568 then the finalization routines.
9569
9570 @end table
9571
9572 @table @asis
9573 @item @command{gcc} @asis{switches}
9574 @ifclear vms
9575 Any uppercase or multi-character switch that is not a @command{gnatmake} switch
9576 is passed to @command{gcc} (e.g.@: @option{-O}, @option{-gnato,} etc.)
9577 @end ifclear
9578 @ifset vms
9579 Any qualifier that cannot be recognized as a qualifier for @code{GNAT MAKE}
9580 but is recognizable as a valid qualifier for @code{GNAT COMPILE} is
9581 automatically treated as a compiler switch, and passed on to all
9582 compilations that are carried out.
9583 @end ifset
9584 @end table
9585
9586 @noindent
9587 Source and library search path switches:
9588
9589 @table @option
9590 @c !sort!
9591 @item ^-aI^/SOURCE_SEARCH=^@var{dir}
9592 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatmake})
9593 When looking for source files also look in directory @var{dir}.
9594 The order in which source files search is undertaken is
9595 described in @ref{Search Paths and the Run-Time Library (RTL)}.
9596
9597 @item ^-aL^/SKIP_MISSING=^@var{dir}
9598 @cindex @option{^-aL^/SKIP_MISSING^} (@command{gnatmake})
9599 Consider @var{dir} as being an externally provided Ada library.
9600 Instructs @command{gnatmake} to skip compilation units whose @file{.ALI}
9601 files have been located in directory @var{dir}. This allows you to have
9602 missing bodies for the units in @var{dir} and to ignore out of date bodies
9603 for the same units. You still need to specify
9604 the location of the specs for these units by using the switches
9605 @option{^-aI^/SOURCE_SEARCH=^@var{dir}}
9606 or @option{^-I^/SEARCH=^@var{dir}}.
9607 Note: this switch is provided for compatibility with previous versions
9608 of @command{gnatmake}. The easier method of causing standard libraries
9609 to be excluded from consideration is to write-protect the corresponding
9610 ALI files.
9611
9612 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
9613 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatmake})
9614 When searching for library and object files, look in directory
9615 @var{dir}. The order in which library files are searched is described in
9616 @ref{Search Paths for gnatbind}.
9617
9618 @item ^-A^/CONDITIONAL_SOURCE_SEARCH=^@var{dir}
9619 @cindex Search paths, for @command{gnatmake}
9620 @cindex @option{^-A^/CONDITIONAL_SOURCE_SEARCH^} (@command{gnatmake})
9621 Equivalent to @option{^-aL^/SKIP_MISSING=^@var{dir}
9622 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9623
9624 @item ^-I^/SEARCH=^@var{dir}
9625 @cindex @option{^-I^/SEARCH^} (@command{gnatmake})
9626 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}
9627 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9628
9629 @item ^-I-^/NOCURRENT_DIRECTORY^
9630 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatmake})
9631 @cindex Source files, suppressing search
9632 Do not look for source files in the directory containing the source
9633 file named in the command line.
9634 Do not look for ALI or object files in the directory
9635 where @command{gnatmake} was invoked.
9636
9637 @item ^-L^/LIBRARY_SEARCH=^@var{dir}
9638 @cindex @option{^-L^/LIBRARY_SEARCH^} (@command{gnatmake})
9639 @cindex Linker libraries
9640 Add directory @var{dir} to the list of directories in which the linker
9641 will search for libraries. This is equivalent to
9642 @option{-largs ^-L^/LIBRARY_SEARCH=^}@var{dir}.
9643 @ifclear vms
9644 Furthermore, under Windows, the sources pointed to by the libraries path
9645 set in the registry are not searched for.
9646 @end ifclear
9647
9648 @item -nostdinc
9649 @cindex @option{-nostdinc} (@command{gnatmake})
9650 Do not look for source files in the system default directory.
9651
9652 @item -nostdlib
9653 @cindex @option{-nostdlib} (@command{gnatmake})
9654 Do not look for library files in the system default directory.
9655
9656 @item --RTS=@var{rts-path}
9657 @cindex @option{--RTS} (@command{gnatmake})
9658 Specifies the default location of the runtime library. GNAT looks for the
9659 runtime
9660 in the following directories, and stops as soon as a valid runtime is found
9661 (@file{adainclude} or @file{ada_source_path}, and @file{adalib} or
9662 @file{ada_object_path} present):
9663
9664 @itemize @bullet
9665 @item <current directory>/$rts_path
9666
9667 @item <default-search-dir>/$rts_path
9668
9669 @item <default-search-dir>/rts-$rts_path
9670 @end itemize
9671
9672 @noindent
9673 The selected path is handled like a normal RTS path.
9674
9675 @end table
9676
9677 @node Mode Switches for gnatmake
9678 @section Mode Switches for @command{gnatmake}
9679
9680 @noindent
9681 The mode switches (referred to as @code{mode_switches}) allow the
9682 inclusion of switches that are to be passed to the compiler itself, the
9683 binder or the linker. The effect of a mode switch is to cause all
9684 subsequent switches up to the end of the switch list, or up to the next
9685 mode switch, to be interpreted as switches to be passed on to the
9686 designated component of GNAT.
9687
9688 @table @option
9689 @c !sort!
9690 @item -cargs @var{switches}
9691 @cindex @option{-cargs} (@command{gnatmake})
9692 Compiler switches. Here @var{switches} is a list of switches
9693 that are valid switches for @command{gcc}. They will be passed on to
9694 all compile steps performed by @command{gnatmake}.
9695
9696 @item -bargs @var{switches}
9697 @cindex @option{-bargs} (@command{gnatmake})
9698 Binder switches. Here @var{switches} is a list of switches
9699 that are valid switches for @code{gnatbind}. They will be passed on to
9700 all bind steps performed by @command{gnatmake}.
9701
9702 @item -largs @var{switches}
9703 @cindex @option{-largs} (@command{gnatmake})
9704 Linker switches. Here @var{switches} is a list of switches
9705 that are valid switches for @command{gnatlink}. They will be passed on to
9706 all link steps performed by @command{gnatmake}.
9707
9708 @item -margs @var{switches}
9709 @cindex @option{-margs} (@command{gnatmake})
9710 Make switches. The switches are directly interpreted by @command{gnatmake},
9711 regardless of any previous occurrence of @option{-cargs}, @option{-bargs}
9712 or @option{-largs}.
9713 @end table
9714
9715 @node Notes on the Command Line
9716 @section Notes on the Command Line
9717
9718 @noindent
9719 This section contains some additional useful notes on the operation
9720 of the @command{gnatmake} command.
9721
9722 @itemize @bullet
9723 @item
9724 @cindex Recompilation, by @command{gnatmake}
9725 If @command{gnatmake} finds no ALI files, it recompiles the main program
9726 and all other units required by the main program.
9727 This means that @command{gnatmake}
9728 can be used for the initial compile, as well as during subsequent steps of
9729 the development cycle.
9730
9731 @item
9732 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
9733 is a subunit or body of a generic unit, @command{gnatmake} recompiles
9734 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
9735 warning.
9736
9737 @item
9738 In @command{gnatmake} the switch @option{^-I^/SEARCH^}
9739 is used to specify both source and
9740 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
9741 instead if you just want to specify
9742 source paths only and @option{^-aO^/OBJECT_SEARCH^}
9743 if you want to specify library paths
9744 only.
9745
9746 @item
9747 @command{gnatmake} will ignore any files whose ALI file is write-protected.
9748 This may conveniently be used to exclude standard libraries from
9749 consideration and in particular it means that the use of the
9750 @option{^-f^/FORCE_COMPILE^} switch will not recompile these files
9751 unless @option{^-a^/ALL_FILES^} is also specified.
9752
9753 @item
9754 @command{gnatmake} has been designed to make the use of Ada libraries
9755 particularly convenient. Assume you have an Ada library organized
9756 as follows: @i{^obj-dir^[OBJ_DIR]^} contains the objects and ALI files for
9757 of your Ada compilation units,
9758 whereas @i{^include-dir^[INCLUDE_DIR]^} contains the
9759 specs of these units, but no bodies. Then to compile a unit
9760 stored in @code{main.adb}, which uses this Ada library you would just type
9761
9762 @smallexample
9763 @ifclear vms
9764 $ gnatmake -aI@var{include-dir}  -aL@var{obj-dir}  main
9765 @end ifclear
9766 @ifset vms
9767 $ gnatmake /SOURCE_SEARCH=@i{[INCLUDE_DIR]}
9768            /SKIP_MISSING=@i{[OBJ_DIR]} main
9769 @end ifset
9770 @end smallexample
9771
9772 @item
9773 Using @command{gnatmake} along with the
9774 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}
9775 switch provides a mechanism for avoiding unnecessary recompilations. Using
9776 this switch,
9777 you can update the comments/format of your
9778 source files without having to recompile everything. Note, however, that
9779 adding or deleting lines in a source files may render its debugging
9780 info obsolete. If the file in question is a spec, the impact is rather
9781 limited, as that debugging info will only be useful during the
9782 elaboration phase of your program. For bodies the impact can be more
9783 significant. In all events, your debugger will warn you if a source file
9784 is more recent than the corresponding object, and alert you to the fact
9785 that the debugging information may be out of date.
9786 @end itemize
9787
9788 @node How gnatmake Works
9789 @section How @command{gnatmake} Works
9790
9791 @noindent
9792 Generally @command{gnatmake} automatically performs all necessary
9793 recompilations and you don't need to worry about how it works. However,
9794 it may be useful to have some basic understanding of the @command{gnatmake}
9795 approach and in particular to understand how it uses the results of
9796 previous compilations without incorrectly depending on them.
9797
9798 First a definition: an object file is considered @dfn{up to date} if the
9799 corresponding ALI file exists and if all the source files listed in the
9800 dependency section of this ALI file have time stamps matching those in
9801 the ALI file. This means that neither the source file itself nor any
9802 files that it depends on have been modified, and hence there is no need
9803 to recompile this file.
9804
9805 @command{gnatmake} works by first checking if the specified main unit is up
9806 to date. If so, no compilations are required for the main unit. If not,
9807 @command{gnatmake} compiles the main program to build a new ALI file that
9808 reflects the latest sources. Then the ALI file of the main unit is
9809 examined to find all the source files on which the main program depends,
9810 and @command{gnatmake} recursively applies the above procedure on all these
9811 files.
9812
9813 This process ensures that @command{gnatmake} only trusts the dependencies
9814 in an existing ALI file if they are known to be correct. Otherwise it
9815 always recompiles to determine a new, guaranteed accurate set of
9816 dependencies. As a result the program is compiled ``upside down'' from what may
9817 be more familiar as the required order of compilation in some other Ada
9818 systems. In particular, clients are compiled before the units on which
9819 they depend. The ability of GNAT to compile in any order is critical in
9820 allowing an order of compilation to be chosen that guarantees that
9821 @command{gnatmake} will recompute a correct set of new dependencies if
9822 necessary.
9823
9824 When invoking @command{gnatmake} with several @var{file_names}, if a unit is
9825 imported by several of the executables, it will be recompiled at most once.
9826
9827 Note: when using non-standard naming conventions
9828 (@pxref{Using Other File Names}), changing through a configuration pragmas
9829 file the version of a source and invoking @command{gnatmake} to recompile may
9830 have no effect, if the previous version of the source is still accessible
9831 by @command{gnatmake}. It may be necessary to use the switch
9832 ^-f^/FORCE_COMPILE^.
9833
9834 @node Examples of gnatmake Usage
9835 @section Examples of @command{gnatmake} Usage
9836
9837 @table @code
9838 @item gnatmake hello.adb
9839 Compile all files necessary to bind and link the main program
9840 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
9841 resulting object files to generate an executable file @file{^hello^HELLO.EXE^}.
9842
9843 @item gnatmake main1 main2 main3
9844 Compile all files necessary to bind and link the main programs
9845 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
9846 (containing unit @code{Main2}) and @file{main3.adb}
9847 (containing unit @code{Main3}) and bind and link the resulting object files
9848 to generate three executable files @file{^main1^MAIN1.EXE^},
9849 @file{^main2^MAIN2.EXE^}
9850 and @file{^main3^MAIN3.EXE^}.
9851
9852 @ifclear vms
9853 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
9854 @end ifclear
9855
9856 @ifset vms
9857 @item gnatmake Main_Unit /QUIET
9858 /COMPILER_QUALIFIERS /OPTIMIZE=ALL
9859 /BINDER_QUALIFIERS /ORDER_OF_ELABORATION
9860 @end ifset
9861 Compile all files necessary to bind and link the main program unit
9862 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
9863 be done with optimization level 2 and the order of elaboration will be
9864 listed by the binder. @command{gnatmake} will operate in quiet mode, not
9865 displaying commands it is executing.
9866 @end table
9867
9868 @c *************************
9869 @node Improving Performance
9870 @chapter Improving Performance
9871 @cindex Improving performance
9872
9873 @noindent
9874 This chapter presents several topics related to program performance.
9875 It first describes some of the tradeoffs that need to be considered
9876 and some of the techniques for making your program run faster.
9877 It then documents the @command{gnatelim} tool and unused subprogram/data
9878 elimination feature, which can reduce the size of program executables.
9879
9880 Note: to invoke @command{gnatelim} with a project file, use the @code{gnat}
9881 driver (see @ref{The GNAT Driver and Project Files}).
9882
9883 @ifnottex
9884 @menu
9885 * Performance Considerations::
9886 * Text_IO Suggestions::
9887 * Reducing Size of Ada Executables with gnatelim::
9888 * Reducing Size of Executables with unused subprogram/data elimination::
9889 @end menu
9890 @end ifnottex
9891
9892 @c *****************************
9893 @node Performance Considerations
9894 @section Performance Considerations
9895
9896 @noindent
9897 The GNAT system provides a number of options that allow a trade-off
9898 between
9899
9900 @itemize @bullet
9901 @item
9902 performance of the generated code
9903
9904 @item
9905 speed of compilation
9906
9907 @item
9908 minimization of dependences and recompilation
9909
9910 @item
9911 the degree of run-time checking.
9912 @end itemize
9913
9914 @noindent
9915 The defaults (if no options are selected) aim at improving the speed
9916 of compilation and minimizing dependences, at the expense of performance
9917 of the generated code:
9918
9919 @itemize @bullet
9920 @item
9921 no optimization
9922
9923 @item
9924 no inlining of subprogram calls
9925
9926 @item
9927 all run-time checks enabled except overflow and elaboration checks
9928 @end itemize
9929
9930 @noindent
9931 These options are suitable for most program development purposes. This
9932 chapter describes how you can modify these choices, and also provides
9933 some guidelines on debugging optimized code.
9934
9935 @menu
9936 * Controlling Run-Time Checks::
9937 * Use of Restrictions::
9938 * Optimization Levels::
9939 * Debugging Optimized Code::
9940 * Inlining of Subprograms::
9941 * Other Optimization Switches::
9942 * Optimization and Strict Aliasing::
9943
9944 @ifset vms
9945 * Coverage Analysis::
9946 @end ifset
9947 @end menu
9948
9949 @node Controlling Run-Time Checks
9950 @subsection Controlling Run-Time Checks
9951
9952 @noindent
9953 By default, GNAT generates all run-time checks, except integer overflow
9954 checks, stack overflow checks, and checks for access before elaboration on
9955 subprogram calls. The latter are not required in default mode, because all
9956 necessary checking is done at compile time.
9957 @cindex @option{-gnatp} (@command{gcc})
9958 @cindex @option{-gnato} (@command{gcc})
9959 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
9960 be modified. @xref{Run-Time Checks}.
9961
9962 Our experience is that the default is suitable for most development
9963 purposes.
9964
9965 We treat integer overflow specially because these
9966 are quite expensive and in our experience are not as important as other
9967 run-time checks in the development process. Note that division by zero
9968 is not considered an overflow check, and divide by zero checks are
9969 generated where required by default.
9970
9971 Elaboration checks are off by default, and also not needed by default, since
9972 GNAT uses a static elaboration analysis approach that avoids the need for
9973 run-time checking. This manual contains a full chapter discussing the issue
9974 of elaboration checks, and if the default is not satisfactory for your use,
9975 you should read this chapter.
9976
9977 For validity checks, the minimal checks required by the Ada Reference
9978 Manual (for case statements and assignments to array elements) are on
9979 by default. These can be suppressed by use of the @option{-gnatVn} switch.
9980 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
9981 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
9982 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
9983 are also suppressed entirely if @option{-gnatp} is used.
9984
9985 @cindex Overflow checks
9986 @cindex Checks, overflow
9987 @findex Suppress
9988 @findex Unsuppress
9989 @cindex pragma Suppress
9990 @cindex pragma Unsuppress
9991 Note that the setting of the switches controls the default setting of
9992 the checks. They may be modified using either @code{pragma Suppress} (to
9993 remove checks) or @code{pragma Unsuppress} (to add back suppressed
9994 checks) in the program source.
9995
9996 @node Use of Restrictions
9997 @subsection Use of Restrictions
9998
9999 @noindent
10000 The use of pragma Restrictions allows you to control which features are
10001 permitted in your program. Apart from the obvious point that if you avoid
10002 relatively expensive features like finalization (enforceable by the use
10003 of pragma Restrictions (No_Finalization), the use of this pragma does not
10004 affect the generated code in most cases.
10005
10006 One notable exception to this rule is that the possibility of task abort
10007 results in some distributed overhead, particularly if finalization or
10008 exception handlers are used. The reason is that certain sections of code
10009 have to be marked as non-abortable.
10010
10011 If you use neither the @code{abort} statement, nor asynchronous transfer
10012 of control (@code{select @dots{} then abort}), then this distributed overhead
10013 is removed, which may have a general positive effect in improving
10014 overall performance.  Especially code involving frequent use of tasking
10015 constructs and controlled types will show much improved performance.
10016 The relevant restrictions pragmas are
10017
10018 @smallexample @c ada
10019    pragma Restrictions (No_Abort_Statements);
10020    pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
10021 @end smallexample
10022
10023 @noindent
10024 It is recommended that these restriction pragmas be used if possible. Note
10025 that this also means that you can write code without worrying about the
10026 possibility of an immediate abort at any point.
10027
10028 @node Optimization Levels
10029 @subsection Optimization Levels
10030 @cindex @option{^-O^/OPTIMIZE^} (@command{gcc})
10031
10032 @noindent
10033 Without any optimization ^option,^qualifier,^
10034 the compiler's goal is to reduce the cost of
10035 compilation and to make debugging produce the expected results.
10036 Statements are independent: if you stop the program with a breakpoint between
10037 statements, you can then assign a new value to any variable or change
10038 the program counter to any other statement in the subprogram and get exactly
10039 the results you would expect from the source code.
10040
10041 Turning on optimization makes the compiler attempt to improve the
10042 performance and/or code size at the expense of compilation time and
10043 possibly the ability to debug the program.
10044
10045 If you use multiple
10046 ^-O options, with or without level numbers,^/OPTIMIZE qualifiers,^
10047 the last such option is the one that is effective.
10048
10049 @noindent
10050 The default is optimization off. This results in the fastest compile
10051 times, but GNAT makes absolutely no attempt to optimize, and the
10052 generated programs are considerably larger and slower than when
10053 optimization is enabled. You can use the
10054 @ifclear vms
10055 @option{-O} switch (the permitted forms are @option{-O0}, @option{-O1}
10056 @option{-O2}, @option{-O3}, and @option{-Os})
10057 @end ifclear
10058 @ifset vms
10059 @code{OPTIMIZE} qualifier
10060 @end ifset
10061 to @command{gcc} to control the optimization level:
10062
10063 @table @option
10064 @item ^-O0^/OPTIMIZE=NONE^
10065 No optimization (the default);
10066 generates unoptimized code but has
10067 the fastest compilation time.
10068
10069 Note that many other compilers do fairly extensive optimization
10070 even if ``no optimization'' is specified. With gcc, it is
10071 very unusual to use ^-O0^/OPTIMIZE=NONE^ for production if
10072 execution time is of any concern, since ^-O0^/OPTIMIZE=NONE^
10073 really does mean no optimization at all. This difference between
10074 gcc and other compilers should be kept in mind when doing
10075 performance comparisons.
10076
10077 @item ^-O1^/OPTIMIZE=SOME^
10078 Moderate optimization;
10079 optimizes reasonably well but does not
10080 degrade compilation time significantly.
10081
10082 @item ^-O2^/OPTIMIZE=ALL^
10083 @ifset vms
10084 @itemx /OPTIMIZE=DEVELOPMENT
10085 @end ifset
10086 Full optimization;
10087 generates highly optimized code and has
10088 the slowest compilation time.
10089
10090 @item ^-O3^/OPTIMIZE=INLINING^
10091 Full optimization as in @option{-O2},
10092 and also attempts automatic inlining of small
10093 subprograms within a unit (@pxref{Inlining of Subprograms}).
10094
10095 @item ^-Os^/OPTIMIZE=SPACE^
10096 Optimize space usage of resulting program.
10097 @end table
10098
10099 @noindent
10100 Higher optimization levels perform more global transformations on the
10101 program and apply more expensive analysis algorithms in order to generate
10102 faster and more compact code. The price in compilation time, and the
10103 resulting improvement in execution time,
10104 both depend on the particular application and the hardware environment.
10105 You should experiment to find the best level for your application.
10106
10107 Since the precise set of optimizations done at each level will vary from
10108 release to release (and sometime from target to target), it is best to think
10109 of the optimization settings in general terms.
10110 @xref{Optimize Options,, Options That Control Optimization, gcc, Using
10111 the GNU Compiler Collection (GCC)}, for details about
10112 ^the @option{-O} settings and a number of @option{-f} options that^how to^
10113 individually enable or disable specific optimizations.
10114
10115 Unlike some other compilation systems, ^@command{gcc}^GNAT^ has
10116 been tested extensively at all optimization levels. There are some bugs
10117 which appear only with optimization turned on, but there have also been
10118 bugs which show up only in @emph{unoptimized} code. Selecting a lower
10119 level of optimization does not improve the reliability of the code
10120 generator, which in practice is highly reliable at all optimization
10121 levels.
10122
10123 Note regarding the use of @option{-O3}: The use of this optimization level
10124 is generally discouraged with GNAT, since it often results in larger
10125 executables which run more slowly. See further discussion of this point
10126 in @ref{Inlining of Subprograms}.
10127
10128 @node Debugging Optimized Code
10129 @subsection Debugging Optimized Code
10130 @cindex Debugging optimized code
10131 @cindex Optimization and debugging
10132
10133 @noindent
10134 Although it is possible to do a reasonable amount of debugging at
10135 @ifclear vms
10136 nonzero optimization levels,
10137 the higher the level the more likely that
10138 @end ifclear
10139 @ifset vms
10140 @option{/OPTIMIZE} settings other than @code{NONE},
10141 such settings will make it more likely that
10142 @end ifset
10143 source-level constructs will have been eliminated by optimization.
10144 For example, if a loop is strength-reduced, the loop
10145 control variable may be completely eliminated and thus cannot be
10146 displayed in the debugger.
10147 This can only happen at @option{-O2} or @option{-O3}.
10148 Explicit temporary variables that you code might be eliminated at
10149 ^level^setting^ @option{-O1} or higher.
10150
10151 The use of the @option{^-g^/DEBUG^} switch,
10152 @cindex @option{^-g^/DEBUG^} (@command{gcc})
10153 which is needed for source-level debugging,
10154 affects the size of the program executable on disk,
10155 and indeed the debugging information can be quite large.
10156 However, it has no effect on the generated code (and thus does not
10157 degrade performance)
10158
10159 Since the compiler generates debugging tables for a compilation unit before
10160 it performs optimizations, the optimizing transformations may invalidate some
10161 of the debugging data.  You therefore need to anticipate certain
10162 anomalous situations that may arise while debugging optimized code.
10163 These are the most common cases:
10164
10165 @enumerate
10166 @item
10167 @i{The ``hopping Program Counter'':}  Repeated @code{step} or @code{next}
10168 commands show
10169 the PC bouncing back and forth in the code.  This may result from any of
10170 the following optimizations:
10171
10172 @itemize @bullet
10173 @item
10174 @i{Common subexpression elimination:} using a single instance of code for a
10175 quantity that the source computes several times.  As a result you
10176 may not be able to stop on what looks like a statement.
10177
10178 @item
10179 @i{Invariant code motion:} moving an expression that does not change within a
10180 loop, to the beginning of the loop.
10181
10182 @item
10183 @i{Instruction scheduling:} moving instructions so as to
10184 overlap loads and stores (typically) with other code, or in
10185 general to move computations of values closer to their uses. Often
10186 this causes you to pass an assignment statement without the assignment
10187 happening and then later bounce back to the statement when the
10188 value is actually needed.  Placing a breakpoint on a line of code
10189 and then stepping over it may, therefore, not always cause all the
10190 expected side-effects.
10191 @end itemize
10192
10193 @item
10194 @i{The ``big leap'':} More commonly known as @emph{cross-jumping}, in which
10195 two identical pieces of code are merged and the program counter suddenly
10196 jumps to a statement that is not supposed to be executed, simply because
10197 it (and the code following) translates to the same thing as the code
10198 that @emph{was} supposed to be executed.  This effect is typically seen in
10199 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
10200 a @code{break} in a C @code{^switch^switch^} statement.
10201
10202 @item
10203 @i{The ``roving variable'':} The symptom is an unexpected value in a variable.
10204 There are various reasons for this effect:
10205
10206 @itemize @bullet
10207 @item
10208 In a subprogram prologue, a parameter may not yet have been moved to its
10209 ``home''.
10210
10211 @item
10212 A variable may be dead, and its register re-used.  This is
10213 probably the most common cause.
10214
10215 @item
10216 As mentioned above, the assignment of a value to a variable may
10217 have been moved.
10218
10219 @item
10220 A variable may be eliminated entirely by value propagation or
10221 other means.  In this case, GCC may incorrectly generate debugging
10222 information for the variable
10223 @end itemize
10224
10225 @noindent
10226 In general, when an unexpected value appears for a local variable or parameter
10227 you should first ascertain if that value was actually computed by
10228 your program, as opposed to being incorrectly reported by the debugger.
10229 Record fields or
10230 array elements in an object designated by an access value
10231 are generally less of a problem, once you have ascertained that the access
10232 value is sensible.
10233 Typically, this means checking variables in the preceding code and in the
10234 calling subprogram to verify that the value observed is explainable from other
10235 values (one must apply the procedure recursively to those
10236 other values); or re-running the code and stopping a little earlier
10237 (perhaps before the call) and stepping to better see how the variable obtained
10238 the value in question; or continuing to step @emph{from} the point of the
10239 strange value to see if code motion had simply moved the variable's
10240 assignments later.
10241 @end enumerate
10242
10243 @noindent
10244 In light of such anomalies, a recommended technique is to use @option{-O0}
10245 early in the software development cycle, when extensive debugging capabilities
10246 are most needed, and then move to @option{-O1} and later @option{-O2} as
10247 the debugger becomes less critical.
10248 Whether to use the @option{^-g^/DEBUG^} switch in the release version is
10249 a release management issue.
10250 @ifclear vms
10251 Note that if you use @option{-g} you can then use the @command{strip} program
10252 on the resulting executable,
10253 which removes both debugging information and global symbols.
10254 @end ifclear
10255
10256 @node Inlining of Subprograms
10257 @subsection Inlining of Subprograms
10258
10259 @noindent
10260 A call to a subprogram in the current unit is inlined if all the
10261 following conditions are met:
10262
10263 @itemize @bullet
10264 @item
10265 The optimization level is at least @option{-O1}.
10266
10267 @item
10268 The called subprogram is suitable for inlining: It must be small enough
10269 and not contain something that @command{gcc} cannot support in inlined
10270 subprograms.
10271
10272 @item
10273 @cindex pragma Inline
10274 @findex Inline
10275 Either @code{pragma Inline} applies to the subprogram, or it is local
10276 to the unit and called once from within it, or it is small and automatic
10277 inlining (optimization level @option{-O3}) is specified.
10278 @end itemize
10279
10280 @noindent
10281 Calls to subprograms in @code{with}'ed units are normally not inlined.
10282 To achieve actual inlining (that is, replacement of the call by the code
10283 in the body of the subprogram), the following conditions must all be true.
10284
10285 @itemize @bullet
10286 @item
10287 The optimization level is at least @option{-O1}.
10288
10289 @item
10290 The called subprogram is suitable for inlining: It must be small enough
10291 and not contain something that @command{gcc} cannot support in inlined
10292 subprograms.
10293
10294 @item
10295 The call appears in a body (not in a package spec).
10296
10297 @item
10298 There is a @code{pragma Inline} for the subprogram.
10299
10300 @item
10301 @cindex @option{-gnatn} (@command{gcc})
10302 The @option{^-gnatn^/INLINE^} switch
10303 is used in the @command{gcc} command line
10304 @end itemize
10305
10306 Even if all these conditions are met, it may not be possible for
10307 the compiler to inline the call, due to the length of the body,
10308 or features in the body that make it impossible for the compiler
10309 to do the inlining.
10310
10311 Note that specifying the @option{-gnatn} switch causes additional
10312 compilation dependencies. Consider the following:
10313
10314 @smallexample @c ada
10315 @cartouche
10316 package R is
10317    procedure Q;
10318    pragma Inline (Q);
10319 end R;
10320 package body R is
10321    @dots{}
10322 end R;
10323
10324 with R;
10325 procedure Main is
10326 begin
10327    @dots{}
10328    R.Q;
10329 end Main;
10330 @end cartouche
10331 @end smallexample
10332
10333 @noindent
10334 With the default behavior (no @option{-gnatn} switch specified), the
10335 compilation of the @code{Main} procedure depends only on its own source,
10336 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
10337 means that editing the body of @code{R} does not require recompiling
10338 @code{Main}.
10339
10340 On the other hand, the call @code{R.Q} is not inlined under these
10341 circumstances. If the @option{-gnatn} switch is present when @code{Main}
10342 is compiled, the call will be inlined if the body of @code{Q} is small
10343 enough, but now @code{Main} depends on the body of @code{R} in
10344 @file{r.adb} as well as on the spec. This means that if this body is edited,
10345 the main program must be recompiled. Note that this extra dependency
10346 occurs whether or not the call is in fact inlined by @command{gcc}.
10347
10348 The use of front end inlining with @option{-gnatN} generates similar
10349 additional dependencies.
10350
10351 @cindex @option{^-fno-inline^/INLINE=SUPPRESS^} (@command{gcc})
10352 Note: The @option{^-fno-inline^/INLINE=SUPPRESS^} switch
10353 can be used to prevent
10354 all inlining. This switch overrides all other conditions and ensures
10355 that no inlining occurs. The extra dependences resulting from
10356 @option{-gnatn} will still be active, even if
10357 this switch is used to suppress the resulting inlining actions.
10358
10359 @cindex @option{-fno-inline-functions} (@command{gcc})
10360 Note: The @option{-fno-inline-functions} switch can be used to prevent
10361 automatic inlining of small subprograms if @option{-O3} is used.
10362
10363 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
10364 Note: The @option{-fno-inline-functions-called-once} switch
10365 can be used to prevent inlining of subprograms local to the unit
10366 and called once from within it if @option{-O1} is used.
10367
10368 Note regarding the use of @option{-O3}: There is no difference in inlining
10369 behavior between @option{-O2} and @option{-O3} for subprograms with an explicit
10370 pragma @code{Inline} assuming the use of @option{-gnatn}
10371 or @option{-gnatN} (the switches that activate inlining). If you have used
10372 pragma @code{Inline} in appropriate cases, then it is usually much better
10373 to use @option{-O2} and @option{-gnatn} and avoid the use of @option{-O3} which
10374 in this case only has the effect of inlining subprograms you did not
10375 think should be inlined. We often find that the use of @option{-O3} slows
10376 down code by performing excessive inlining, leading to increased instruction
10377 cache pressure from the increased code size. So the bottom line here is
10378 that you should not automatically assume that @option{-O3} is better than
10379 @option{-O2}, and indeed you should use @option{-O3} only if tests show that
10380 it actually improves performance.
10381
10382 @node Other Optimization Switches
10383 @subsection Other Optimization Switches
10384 @cindex Optimization Switches
10385
10386 Since @code{GNAT} uses the @command{gcc} back end, all the specialized
10387 @command{gcc} optimization switches are potentially usable. These switches
10388 have not been extensively tested with GNAT but can generally be expected
10389 to work. Examples of switches in this category are
10390 @option{-funroll-loops} and
10391 the various target-specific @option{-m} options (in particular, it has been
10392 observed that @option{-march=pentium4} can significantly improve performance
10393 on appropriate machines). For full details of these switches, see
10394 @ref{Submodel Options,, Hardware Models and Configurations, gcc, Using
10395 the GNU Compiler Collection (GCC)}.
10396
10397 @node Optimization and Strict Aliasing
10398 @subsection Optimization and Strict Aliasing
10399 @cindex Aliasing
10400 @cindex Strict Aliasing
10401 @cindex No_Strict_Aliasing
10402
10403 @noindent
10404 The strong typing capabilities of Ada allow an optimizer to generate
10405 efficient code in situations where other languages would be forced to
10406 make worst case assumptions preventing such optimizations. Consider
10407 the following example:
10408
10409 @smallexample @c ada
10410 @cartouche
10411 procedure R is
10412    type Int1 is new Integer;
10413    type Int2 is new Integer;
10414    type Int1A is access Int1;
10415    type Int2A is access Int2;
10416    Int1V : Int1A;
10417    Int2V : Int2A;
10418    @dots{}
10419
10420 begin
10421    @dots{}
10422    for J in Data'Range loop
10423       if Data (J) = Int1V.all then
10424          Int2V.all := Int2V.all + 1;
10425       end if;
10426    end loop;
10427    @dots{}
10428 end R;
10429 @end cartouche
10430 @end smallexample
10431
10432 @noindent
10433 In this example, since the variable @code{Int1V} can only access objects
10434 of type @code{Int1}, and @code{Int2V} can only access objects of type
10435 @code{Int2}, there is no possibility that the assignment to
10436 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
10437 the compiler optimizer can "know" that the value @code{Int1V.all} is constant
10438 for all iterations of the loop and avoid the extra memory reference
10439 required to dereference it each time through the loop.
10440
10441 This kind of optimization, called strict aliasing analysis, is
10442 triggered by specifying an optimization level of @option{-O2} or
10443 higher or @option{-Os} and allows @code{GNAT} to generate more efficient code
10444 when access values are involved.
10445
10446 However, although this optimization is always correct in terms of
10447 the formal semantics of the Ada Reference Manual, difficulties can
10448 arise if features like @code{Unchecked_Conversion} are used to break
10449 the typing system. Consider the following complete program example:
10450
10451 @smallexample @c ada
10452 @cartouche
10453 package p1 is
10454    type int1 is new integer;
10455    type int2 is new integer;
10456    type a1 is access int1;
10457    type a2 is access int2;
10458 end p1;
10459
10460 with p1; use p1;
10461 package p2 is
10462    function to_a2 (Input : a1) return a2;
10463 end p2;
10464
10465 with Unchecked_Conversion;
10466 package body p2 is
10467    function to_a2 (Input : a1) return a2 is
10468       function to_a2u is
10469         new Unchecked_Conversion (a1, a2);
10470    begin
10471       return to_a2u (Input);
10472    end to_a2;
10473 end p2;
10474
10475 with p2; use p2;
10476 with p1; use p1;
10477 with Text_IO; use Text_IO;
10478 procedure m is
10479    v1 : a1 := new int1;
10480    v2 : a2 := to_a2 (v1);
10481 begin
10482    v1.all := 1;
10483    v2.all := 0;
10484    put_line (int1'image (v1.all));
10485 end;
10486 @end cartouche
10487 @end smallexample
10488
10489 @noindent
10490 This program prints out 0 in @option{-O0} or @option{-O1}
10491 mode, but it prints out 1 in @option{-O2} mode. That's
10492 because in strict aliasing mode, the compiler can and
10493 does assume that the assignment to @code{v2.all} could not
10494 affect the value of @code{v1.all}, since different types
10495 are involved.
10496
10497 This behavior is not a case of non-conformance with the standard, since
10498 the Ada RM specifies that an unchecked conversion where the resulting
10499 bit pattern is not a correct value of the target type can result in an
10500 abnormal value and attempting to reference an abnormal value makes the
10501 execution of a program erroneous.  That's the case here since the result
10502 does not point to an object of type @code{int2}.  This means that the
10503 effect is entirely unpredictable.
10504
10505 However, although that explanation may satisfy a language
10506 lawyer, in practice an applications programmer expects an
10507 unchecked conversion involving pointers to create true
10508 aliases and the behavior of printing 1 seems plain wrong.
10509 In this case, the strict aliasing optimization is unwelcome.
10510
10511 Indeed the compiler recognizes this possibility, and the
10512 unchecked conversion generates a warning:
10513
10514 @smallexample
10515 p2.adb:5:07: warning: possible aliasing problem with type "a2"
10516 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
10517 p2.adb:5:07: warning:  or use "pragma No_Strict_Aliasing (a2);"
10518 @end smallexample
10519
10520 @noindent
10521 Unfortunately the problem is recognized when compiling the body of
10522 package @code{p2}, but the actual "bad" code is generated while
10523 compiling the body of @code{m} and this latter compilation does not see
10524 the suspicious @code{Unchecked_Conversion}.
10525
10526 As implied by the warning message, there are approaches you can use to
10527 avoid the unwanted strict aliasing optimization in a case like this.
10528
10529 One possibility is to simply avoid the use of @option{-O2}, but
10530 that is a bit drastic, since it throws away a number of useful
10531 optimizations that do not involve strict aliasing assumptions.
10532
10533 A less drastic approach is to compile the program using the
10534 option @option{-fno-strict-aliasing}. Actually it is only the
10535 unit containing the dereferencing of the suspicious pointer
10536 that needs to be compiled. So in this case, if we compile
10537 unit @code{m} with this switch, then we get the expected
10538 value of zero printed. Analyzing which units might need
10539 the switch can be painful, so a more reasonable approach
10540 is to compile the entire program with options @option{-O2}
10541 and @option{-fno-strict-aliasing}. If the performance is
10542 satisfactory with this combination of options, then the
10543 advantage is that the entire issue of possible "wrong"
10544 optimization due to strict aliasing is avoided.
10545
10546 To avoid the use of compiler switches, the configuration
10547 pragma @code{No_Strict_Aliasing} with no parameters may be
10548 used to specify that for all access types, the strict
10549 aliasing optimization should be suppressed.
10550
10551 However, these approaches are still overkill, in that they causes
10552 all manipulations of all access values to be deoptimized. A more
10553 refined approach is to concentrate attention on the specific
10554 access type identified as problematic.
10555
10556 First, if a careful analysis of uses of the pointer shows
10557 that there are no possible problematic references, then
10558 the warning can be suppressed by bracketing the
10559 instantiation of @code{Unchecked_Conversion} to turn
10560 the warning off:
10561
10562 @smallexample @c ada
10563    pragma Warnings (Off);
10564    function to_a2u is
10565      new Unchecked_Conversion (a1, a2);
10566    pragma Warnings (On);
10567 @end smallexample
10568
10569 @noindent
10570 Of course that approach is not appropriate for this particular
10571 example, since indeed there is a problematic reference. In this
10572 case we can take one of two other approaches.
10573
10574 The first possibility is to move the instantiation of unchecked
10575 conversion to the unit in which the type is declared. In
10576 this example, we would move the instantiation of
10577 @code{Unchecked_Conversion} from the body of package
10578 @code{p2} to the spec of package @code{p1}. Now the
10579 warning disappears. That's because any use of the
10580 access type knows there is a suspicious unchecked
10581 conversion, and the strict aliasing optimization
10582 is automatically suppressed for the type.
10583
10584 If it is not practical to move the unchecked conversion to the same unit
10585 in which the destination access type is declared (perhaps because the
10586 source type is not visible in that unit), you may use pragma
10587 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
10588 same declarative sequence as the declaration of the access type:
10589
10590 @smallexample @c ada
10591    type a2 is access int2;
10592    pragma No_Strict_Aliasing (a2);
10593 @end smallexample
10594
10595 @noindent
10596 Here again, the compiler now knows that the strict aliasing optimization
10597 should be suppressed for any reference to type @code{a2} and the
10598 expected behavior is obtained.
10599
10600 Finally, note that although the compiler can generate warnings for
10601 simple cases of unchecked conversions, there are tricker and more
10602 indirect ways of creating type incorrect aliases which the compiler
10603 cannot detect. Examples are the use of address overlays and unchecked
10604 conversions involving composite types containing access types as
10605 components. In such cases, no warnings are generated, but there can
10606 still be aliasing problems. One safe coding practice is to forbid the
10607 use of address clauses for type overlaying, and to allow unchecked
10608 conversion only for primitive types. This is not really a significant
10609 restriction since any possible desired effect can be achieved by
10610 unchecked conversion of access values.
10611
10612 The aliasing analysis done in strict aliasing mode can certainly
10613 have significant benefits. We have seen cases of large scale
10614 application code where the time is increased by up to 5% by turning
10615 this optimization off. If you have code that includes significant
10616 usage of unchecked conversion, you might want to just stick with
10617 @option{-O1} and avoid the entire issue. If you get adequate
10618 performance at this level of optimization level, that's probably
10619 the safest approach. If tests show that you really need higher
10620 levels of optimization, then you can experiment with @option{-O2}
10621 and @option{-O2 -fno-strict-aliasing} to see how much effect this
10622 has on size and speed of the code. If you really need to use
10623 @option{-O2} with strict aliasing in effect, then you should
10624 review any uses of unchecked conversion of access types,
10625 particularly if you are getting the warnings described above.
10626
10627 @ifset vms
10628 @node Coverage Analysis
10629 @subsection Coverage Analysis
10630
10631 @noindent
10632 GNAT supports the HP Performance Coverage Analyzer (PCA), which allows
10633 the user to determine the distribution of execution time across a program,
10634 @pxref{Profiling} for details of usage.
10635 @end ifset
10636
10637
10638 @node Text_IO Suggestions
10639 @section @code{Text_IO} Suggestions
10640 @cindex @code{Text_IO} and performance
10641
10642 @noindent
10643 The @code{Ada.Text_IO} package has fairly high overheads due in part to
10644 the requirement of maintaining page and line counts. If performance
10645 is critical, a recommendation is to use @code{Stream_IO} instead of
10646 @code{Text_IO} for volume output, since this package has less overhead.
10647
10648 If @code{Text_IO} must be used, note that by default output to the standard
10649 output and standard error files is unbuffered (this provides better
10650 behavior when output statements are used for debugging, or if the
10651 progress of a program is observed by tracking the output, e.g. by
10652 using the Unix @command{tail -f} command to watch redirected output.
10653
10654 If you are generating large volumes of output with @code{Text_IO} and
10655 performance is an important factor, use a designated file instead
10656 of the standard output file, or change the standard output file to
10657 be buffered using @code{Interfaces.C_Streams.setvbuf}.
10658
10659
10660
10661 @node Reducing Size of Ada Executables with gnatelim
10662 @section Reducing Size of Ada Executables with @code{gnatelim}
10663 @findex gnatelim
10664
10665 @noindent
10666 This section describes @command{gnatelim}, a tool which detects unused
10667 subprograms and helps the compiler to create a smaller executable for your
10668 program.
10669
10670 @menu
10671 * About gnatelim::
10672 * Running gnatelim::
10673 * Correcting the List of Eliminate Pragmas::
10674 * Making Your Executables Smaller::
10675 * Summary of the gnatelim Usage Cycle::
10676 @end menu
10677
10678 @node About gnatelim
10679 @subsection About @code{gnatelim}
10680
10681 @noindent
10682 When a program shares a set of Ada
10683 packages with other programs, it may happen that this program uses
10684 only a fraction of the subprograms defined in these packages. The code
10685 created for these unused subprograms increases the size of the executable.
10686
10687 @code{gnatelim} tracks unused subprograms in an Ada program and
10688 outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the
10689 subprograms that are declared but never called. By placing the list of
10690 @code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and
10691 recompiling your program, you may decrease the size of its executable,
10692 because the compiler will not generate the code for 'eliminated' subprograms.
10693 @xref{Pragma Eliminate,,, gnat_rm, GNAT Reference Manual}, for more
10694 information about this pragma.
10695
10696 @code{gnatelim} needs as its input data the name of the main subprogram
10697 and a bind file for a main subprogram.
10698
10699 To create a bind file for @code{gnatelim}, run @code{gnatbind} for
10700 the main subprogram. @code{gnatelim} can work with both Ada and C
10701 bind files; when both are present, it uses the Ada bind file.
10702 The following commands will build the program and create the bind file:
10703
10704 @smallexample
10705 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
10706 $ gnatbind main_prog
10707 @end smallexample
10708
10709 Note that @code{gnatelim} needs neither object nor ALI files.
10710
10711 @node Running gnatelim
10712 @subsection Running @code{gnatelim}
10713
10714 @noindent
10715 @code{gnatelim} has the following command-line interface:
10716
10717 @smallexample
10718 $ gnatelim @ovar{options} name
10719 @end smallexample
10720
10721 @noindent
10722 @code{name} should be a name of a source file that contains the main subprogram
10723 of a program (partition).
10724
10725 @code{gnatelim} has the following switches:
10726
10727 @table @option
10728 @c !sort!
10729 @item ^-q^/QUIET^
10730 @cindex @option{^-q^/QUIET^} (@command{gnatelim})
10731 Quiet mode: by default @code{gnatelim} outputs to the standard error
10732 stream the number of program units left to be processed. This option turns
10733 this trace off.
10734
10735 @item ^-v^/VERBOSE^
10736 @cindex @option{^-v^/VERBOSE^} (@command{gnatelim})
10737 Verbose mode: @code{gnatelim} version information is printed as Ada
10738 comments to the standard output stream. Also, in addition to the number of
10739 program units left @code{gnatelim} will output the name of the current unit
10740 being processed.
10741
10742 @item ^-a^/ALL^
10743 @cindex @option{^-a^/ALL^} (@command{gnatelim})
10744 Also look for subprograms from the GNAT run time that can be eliminated. Note
10745 that when @file{gnat.adc} is produced using this switch, the entire program
10746 must be recompiled with switch @option{^-a^/ALL_FILES^} to @command{gnatmake}.
10747
10748 @item ^-I^/INCLUDE_DIRS=^@var{dir}
10749 @cindex @option{^-I^/INCLUDE_DIRS^} (@command{gnatelim})
10750 When looking for source files also look in directory @var{dir}. Specifying
10751 @option{^-I-^/INCLUDE_DIRS=-^} instructs @code{gnatelim} not to look for
10752 sources in the current directory.
10753
10754 @item ^-b^/BIND_FILE=^@var{bind_file}
10755 @cindex @option{^-b^/BIND_FILE^} (@command{gnatelim})
10756 Specifies @var{bind_file} as the bind file to process. If not set, the name
10757 of the bind file is computed from the full expanded Ada name
10758 of a main subprogram.
10759
10760 @item ^-C^/CONFIG_FILE=^@var{config_file}
10761 @cindex @option{^-C^/CONFIG_FILE^} (@command{gnatelim})
10762 Specifies a file @var{config_file} that contains configuration pragmas. The
10763 file must be specified with full path.
10764
10765 @item ^--GCC^/COMPILER^=@var{compiler_name}
10766 @cindex @option{^-GCC^/COMPILER^} (@command{gnatelim})
10767 Instructs @code{gnatelim} to use specific @command{gcc} compiler instead of one
10768 available on the path.
10769
10770 @item ^--GNATMAKE^/GNATMAKE^=@var{gnatmake_name}
10771 @cindex @option{^--GNATMAKE^/GNATMAKE^} (@command{gnatelim})
10772 Instructs @code{gnatelim} to use specific @command{gnatmake} instead of one
10773 available on the path.
10774 @end table
10775
10776 @noindent
10777 @code{gnatelim} sends its output to the standard output stream, and all the
10778 tracing and debug information is sent to the standard error stream.
10779 In order to produce a proper GNAT configuration file
10780 @file{gnat.adc}, redirection must be used:
10781
10782 @smallexample
10783 @ifset vms
10784 $ PIPE GNAT ELIM MAIN_PROG.ADB > GNAT.ADC
10785 @end ifset
10786 @ifclear vms
10787 $ gnatelim main_prog.adb > gnat.adc
10788 @end ifclear
10789 @end smallexample
10790
10791 @ifclear vms
10792 @noindent
10793 or
10794
10795 @smallexample
10796 $ gnatelim main_prog.adb >> gnat.adc
10797 @end smallexample
10798
10799 @noindent
10800 in order to append the @code{gnatelim} output to the existing contents of
10801 @file{gnat.adc}.
10802 @end ifclear
10803
10804 @node Correcting the List of Eliminate Pragmas
10805 @subsection Correcting the List of Eliminate Pragmas
10806
10807 @noindent
10808 In some rare cases @code{gnatelim} may try to eliminate
10809 subprograms that are actually called in the program. In this case, the
10810 compiler will generate an error message of the form:
10811
10812 @smallexample
10813 file.adb:106:07: cannot call eliminated subprogram "My_Prog"
10814 @end smallexample
10815
10816 @noindent
10817 You will need to manually remove the wrong @code{Eliminate} pragmas from
10818 the @file{gnat.adc} file. You should recompile your program
10819 from scratch after that, because you need a consistent @file{gnat.adc} file
10820 during the entire compilation.
10821
10822 @node Making Your Executables Smaller
10823 @subsection Making Your Executables Smaller
10824
10825 @noindent
10826 In order to get a smaller executable for your program you now have to
10827 recompile the program completely with the new @file{gnat.adc} file
10828 created by @code{gnatelim} in your current directory:
10829
10830 @smallexample
10831 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
10832 @end smallexample
10833
10834 @noindent
10835 (Use the @option{^-f^/FORCE_COMPILE^} option for @command{gnatmake} to
10836 recompile everything
10837 with the set of pragmas @code{Eliminate} that you have obtained with
10838 @command{gnatelim}).
10839
10840 Be aware that the set of @code{Eliminate} pragmas is specific to each
10841 program. It is not recommended to merge sets of @code{Eliminate}
10842 pragmas created for different programs in one @file{gnat.adc} file.
10843
10844 @node Summary of the gnatelim Usage Cycle
10845 @subsection Summary of the gnatelim Usage Cycle
10846
10847 @noindent
10848 Here is a quick summary of the steps to be taken in order to reduce
10849 the size of your executables with @code{gnatelim}. You may use
10850 other GNAT options to control the optimization level,
10851 to produce the debugging information, to set search path, etc.
10852
10853 @enumerate
10854 @item
10855 Produce a bind file
10856
10857 @smallexample
10858 $ gnatmake ^-c main_prog^/ACTIONS=COMPILE MAIN_PROG^
10859 $ gnatbind main_prog
10860 @end smallexample
10861
10862 @item
10863 Generate a list of @code{Eliminate} pragmas
10864 @smallexample
10865 @ifset vms
10866 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
10867 @end ifset
10868 @ifclear vms
10869 $ gnatelim main_prog >@r{[}>@r{]} gnat.adc
10870 @end ifclear
10871 @end smallexample
10872
10873 @item
10874 Recompile the application
10875
10876 @smallexample
10877 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
10878 @end smallexample
10879
10880 @end enumerate
10881
10882 @node Reducing Size of Executables with unused subprogram/data elimination
10883 @section Reducing Size of Executables with Unused Subprogram/Data Elimination
10884 @findex unused subprogram/data elimination
10885
10886 @noindent
10887 This section describes how you can eliminate unused subprograms and data from
10888 your executable just by setting options at compilation time.
10889
10890 @menu
10891 * About unused subprogram/data elimination::
10892 * Compilation options::
10893 * Example of unused subprogram/data elimination::
10894 @end menu
10895
10896 @node About unused subprogram/data elimination
10897 @subsection About unused subprogram/data elimination
10898
10899 @noindent
10900 By default, an executable contains all code and data of its composing objects
10901 (directly linked or coming from statically linked libraries), even data or code
10902 never used by this executable.
10903
10904 This feature will allow you to eliminate such unused code from your
10905 executable, making it smaller (in disk and in memory).
10906
10907 This functionality is available on all Linux platforms except for the IA-64
10908 architecture and on all cross platforms using the ELF binary file format.
10909 In both cases GNU binutils version 2.16 or later are required to enable it.
10910
10911 @node Compilation options
10912 @subsection Compilation options
10913
10914 @noindent
10915 The operation of eliminating the unused code and data from the final executable
10916 is directly performed by the linker.
10917
10918 In order to do this, it has to work with objects compiled with the
10919 following options:
10920 @option{-ffunction-sections} @option{-fdata-sections}.
10921 @cindex @option{-ffunction-sections} (@command{gcc})
10922 @cindex @option{-fdata-sections} (@command{gcc})
10923 These options are usable with C and Ada files.
10924 They will place respectively each
10925 function or data in a separate section in the resulting object file.
10926
10927 Once the objects and static libraries are created with these options, the
10928 linker can perform the dead code elimination. You can do this by setting
10929 the @option{-Wl,--gc-sections} option to gcc command or in the
10930 @option{-largs} section of @command{gnatmake}. This will perform a
10931 garbage collection of code and data never referenced.
10932
10933 If the linker performs a partial link (@option{-r} ld linker option), then you
10934 will need to provide one or several entry point using the
10935 @option{-e} / @option{--entry} ld option.
10936
10937 Note that objects compiled without the @option{-ffunction-sections} and
10938 @option{-fdata-sections} options can still be linked with the executable.
10939 However, no dead code elimination will be performed on those objects (they will
10940 be linked as is).
10941
10942 The GNAT static library is now compiled with -ffunction-sections and
10943 -fdata-sections on some platforms. This allows you to eliminate the unused code
10944 and data of the GNAT library from your executable.
10945
10946 @node Example of unused subprogram/data elimination
10947 @subsection Example of unused subprogram/data elimination
10948
10949 @noindent
10950 Here is a simple example:
10951
10952 @smallexample @c ada
10953 with Aux;
10954
10955 procedure Test is
10956 begin
10957    Aux.Used (10);
10958 end Test;
10959
10960 package Aux is
10961    Used_Data   : Integer;
10962    Unused_Data : Integer;
10963
10964    procedure Used   (Data : Integer);
10965    procedure Unused (Data : Integer);
10966 end Aux;
10967
10968 package body Aux is
10969    procedure Used (Data : Integer) is
10970    begin
10971       Used_Data := Data;
10972    end Used;
10973
10974    procedure Unused (Data : Integer) is
10975    begin
10976       Unused_Data := Data;
10977    end Unused;
10978 end Aux;
10979 @end smallexample
10980
10981 @noindent
10982 @code{Unused} and @code{Unused_Data} are never referenced in this code
10983 excerpt, and hence they may be safely removed from the final executable.
10984
10985 @smallexample
10986 $ gnatmake test
10987
10988 $ nm test | grep used
10989 020015f0 T aux__unused
10990 02005d88 B aux__unused_data
10991 020015cc T aux__used
10992 02005d84 B aux__used_data
10993
10994 $ gnatmake test -cargs -fdata-sections -ffunction-sections \
10995      -largs -Wl,--gc-sections
10996
10997 $ nm test | grep used
10998 02005350 T aux__used
10999 0201ffe0 B aux__used_data
11000 @end smallexample
11001
11002 @noindent
11003 It can be observed that the procedure @code{Unused} and the object
11004 @code{Unused_Data} are removed by the linker when using the
11005 appropriate options.
11006
11007 @c ********************************
11008 @node Renaming Files Using gnatchop
11009 @chapter Renaming Files Using @code{gnatchop}
11010 @findex gnatchop
11011
11012 @noindent
11013 This chapter discusses how to handle files with multiple units by using
11014 the @code{gnatchop} utility. This utility is also useful in renaming
11015 files to meet the standard GNAT default file naming conventions.
11016
11017 @menu
11018 * Handling Files with Multiple Units::
11019 * Operating gnatchop in Compilation Mode::
11020 * Command Line for gnatchop::
11021 * Switches for gnatchop::
11022 * Examples of gnatchop Usage::
11023 @end menu
11024
11025 @node Handling Files with Multiple Units
11026 @section Handling Files with Multiple Units
11027
11028 @noindent
11029 The basic compilation model of GNAT requires that a file submitted to the
11030 compiler have only one unit and there be a strict correspondence
11031 between the file name and the unit name.
11032
11033 The @code{gnatchop} utility allows both of these rules to be relaxed,
11034 allowing GNAT to process files which contain multiple compilation units
11035 and files with arbitrary file names. @code{gnatchop}
11036 reads the specified file and generates one or more output files,
11037 containing one unit per file. The unit and the file name correspond,
11038 as required by GNAT.
11039
11040 If you want to permanently restructure a set of ``foreign'' files so that
11041 they match the GNAT rules, and do the remaining development using the
11042 GNAT structure, you can simply use @command{gnatchop} once, generate the
11043 new set of files and work with them from that point on.
11044
11045 Alternatively, if you want to keep your files in the ``foreign'' format,
11046 perhaps to maintain compatibility with some other Ada compilation
11047 system, you can set up a procedure where you use @command{gnatchop} each
11048 time you compile, regarding the source files that it writes as temporary
11049 files that you throw away.
11050
11051 Note that if your file containing multiple units starts with a byte order
11052 mark (BOM) specifying UTF-8 encoding, then the files generated by gnatchop
11053 will each start with a copy of this BOM, meaning that they can be compiled
11054 automatically in UTF-8 mode without needing to specify an explicit encoding.
11055
11056 @node Operating gnatchop in Compilation Mode
11057 @section Operating gnatchop in Compilation Mode
11058
11059 @noindent
11060 The basic function of @code{gnatchop} is to take a file with multiple units
11061 and split it into separate files. The boundary between files is reasonably
11062 clear, except for the issue of comments and pragmas. In default mode, the
11063 rule is that any pragmas between units belong to the previous unit, except
11064 that configuration pragmas always belong to the following unit. Any comments
11065 belong to the following unit. These rules
11066 almost always result in the right choice of
11067 the split point without needing to mark it explicitly and most users will
11068 find this default to be what they want. In this default mode it is incorrect to
11069 submit a file containing only configuration pragmas, or one that ends in
11070 configuration pragmas, to @code{gnatchop}.
11071
11072 However, using a special option to activate ``compilation mode'',
11073 @code{gnatchop}
11074 can perform another function, which is to provide exactly the semantics
11075 required by the RM for handling of configuration pragmas in a compilation.
11076 In the absence of configuration pragmas (at the main file level), this
11077 option has no effect, but it causes such configuration pragmas to be handled
11078 in a quite different manner.
11079
11080 First, in compilation mode, if @code{gnatchop} is given a file that consists of
11081 only configuration pragmas, then this file is appended to the
11082 @file{gnat.adc} file in the current directory. This behavior provides
11083 the required behavior described in the RM for the actions to be taken
11084 on submitting such a file to the compiler, namely that these pragmas
11085 should apply to all subsequent compilations in the same compilation
11086 environment. Using GNAT, the current directory, possibly containing a
11087 @file{gnat.adc} file is the representation
11088 of a compilation environment. For more information on the
11089 @file{gnat.adc} file, see @ref{Handling of Configuration Pragmas}.
11090
11091 Second, in compilation mode, if @code{gnatchop}
11092 is given a file that starts with
11093 configuration pragmas, and contains one or more units, then these
11094 configuration pragmas are prepended to each of the chopped files. This
11095 behavior provides the required behavior described in the RM for the
11096 actions to be taken on compiling such a file, namely that the pragmas
11097 apply to all units in the compilation, but not to subsequently compiled
11098 units.
11099
11100 Finally, if configuration pragmas appear between units, they are appended
11101 to the previous unit. This results in the previous unit being illegal,
11102 since the compiler does not accept configuration pragmas that follow
11103 a unit. This provides the required RM behavior that forbids configuration
11104 pragmas other than those preceding the first compilation unit of a
11105 compilation.
11106
11107 For most purposes, @code{gnatchop} will be used in default mode. The
11108 compilation mode described above is used only if you need exactly
11109 accurate behavior with respect to compilations, and you have files
11110 that contain multiple units and configuration pragmas. In this
11111 circumstance the use of @code{gnatchop} with the compilation mode
11112 switch provides the required behavior, and is for example the mode
11113 in which GNAT processes the ACVC tests.
11114
11115 @node Command Line for gnatchop
11116 @section Command Line for @code{gnatchop}
11117
11118 @noindent
11119 The @code{gnatchop} command has the form:
11120
11121 @smallexample
11122 $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11123       @ovar{directory}
11124 @end smallexample
11125
11126 @noindent
11127 The only required argument is the file name of the file to be chopped.
11128 There are no restrictions on the form of this file name. The file itself
11129 contains one or more Ada units, in normal GNAT format, concatenated
11130 together. As shown, more than one file may be presented to be chopped.
11131
11132 When run in default mode, @code{gnatchop} generates one output file in
11133 the current directory for each unit in each of the files.
11134
11135 @var{directory}, if specified, gives the name of the directory to which
11136 the output files will be written. If it is not specified, all files are
11137 written to the current directory.
11138
11139 For example, given a
11140 file called @file{hellofiles} containing
11141
11142 @smallexample @c ada
11143 @group
11144 @cartouche
11145 procedure hello;
11146
11147 with Text_IO; use Text_IO;
11148 procedure hello is
11149 begin
11150    Put_Line ("Hello");
11151 end hello;
11152 @end cartouche
11153 @end group
11154 @end smallexample
11155
11156 @noindent
11157 the command
11158
11159 @smallexample
11160 $ gnatchop ^hellofiles^HELLOFILES.^
11161 @end smallexample
11162
11163 @noindent
11164 generates two files in the current directory, one called
11165 @file{hello.ads} containing the single line that is the procedure spec,
11166 and the other called @file{hello.adb} containing the remaining text. The
11167 original file is not affected. The generated files can be compiled in
11168 the normal manner.
11169
11170 @noindent
11171 When gnatchop is invoked on a file that is empty or that contains only empty
11172 lines and/or comments, gnatchop will not fail, but will not produce any
11173 new sources.
11174
11175 For example, given a
11176 file called @file{toto.txt} containing
11177
11178 @smallexample @c ada
11179 @group
11180 @cartouche
11181 --  Just a comment
11182 @end cartouche
11183 @end group
11184 @end smallexample
11185
11186 @noindent
11187 the command
11188
11189 @smallexample
11190 $ gnatchop ^toto.txt^TOT.TXT^
11191 @end smallexample
11192
11193 @noindent
11194 will not produce any new file and will result in the following warnings:
11195
11196 @smallexample
11197 toto.txt:1:01: warning: empty file, contains no compilation units
11198 no compilation units found
11199 no source files written
11200 @end smallexample
11201
11202 @node Switches for gnatchop
11203 @section Switches for @code{gnatchop}
11204
11205 @noindent
11206 @command{gnatchop} recognizes the following switches:
11207
11208 @table @option
11209 @c !sort!
11210
11211 @item --version
11212 @cindex @option{--version} @command{gnatchop}
11213 Display Copyright and version, then exit disregarding all other options.
11214
11215 @item --help
11216 @cindex @option{--help} @command{gnatchop}
11217 If @option{--version} was not used, display usage, then exit disregarding
11218 all other options.
11219
11220 @item ^-c^/COMPILATION^
11221 @cindex @option{^-c^/COMPILATION^} (@code{gnatchop})
11222 Causes @code{gnatchop} to operate in compilation mode, in which
11223 configuration pragmas are handled according to strict RM rules. See
11224 previous section for a full description of this mode.
11225
11226 @ifclear vms
11227 @item -gnat@var{xxx}
11228 This passes the given @option{-gnat@var{xxx}} switch to @code{gnat} which is
11229 used to parse the given file. Not all @var{xxx} options make sense,
11230 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
11231 process a source file that uses Latin-2 coding for identifiers.
11232 @end ifclear
11233
11234 @item ^-h^/HELP^
11235 Causes @code{gnatchop} to generate a brief help summary to the standard
11236 output file showing usage information.
11237
11238 @item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^
11239 @cindex @option{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop})
11240 Limit generated file names to the specified number @code{mm}
11241 of characters.
11242 This is useful if the
11243 resulting set of files is required to be interoperable with systems
11244 which limit the length of file names.
11245 @ifset vms
11246 If no value is given, or
11247 if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given,
11248 a default of 39, suitable for OpenVMS Alpha
11249 Systems, is assumed
11250 @end ifset
11251 @ifclear vms
11252 No space is allowed between the @option{-k} and the numeric value. The numeric
11253 value may be omitted in which case a default of @option{-k8},
11254 suitable for use
11255 with DOS-like file systems, is used. If no @option{-k} switch
11256 is present then
11257 there is no limit on the length of file names.
11258 @end ifclear
11259
11260 @item ^-p^/PRESERVE^
11261 @cindex @option{^-p^/PRESERVE^} (@code{gnatchop})
11262 Causes the file ^modification^creation^ time stamp of the input file to be
11263 preserved and used for the time stamp of the output file(s). This may be
11264 useful for preserving coherency of time stamps in an environment where
11265 @code{gnatchop} is used as part of a standard build process.
11266
11267 @item ^-q^/QUIET^
11268 @cindex @option{^-q^/QUIET^} (@code{gnatchop})
11269 Causes output of informational messages indicating the set of generated
11270 files to be suppressed. Warnings and error messages are unaffected.
11271
11272 @item ^-r^/REFERENCE^
11273 @cindex @option{^-r^/REFERENCE^} (@code{gnatchop})
11274 @findex Source_Reference
11275 Generate @code{Source_Reference} pragmas. Use this switch if the output
11276 files are regarded as temporary and development is to be done in terms
11277 of the original unchopped file. This switch causes
11278 @code{Source_Reference} pragmas to be inserted into each of the
11279 generated files to refers back to the original file name and line number.
11280 The result is that all error messages refer back to the original
11281 unchopped file.
11282 In addition, the debugging information placed into the object file (when
11283 the @option{^-g^/DEBUG^} switch of @command{gcc} or @command{gnatmake} is
11284 specified)
11285 also refers back to this original file so that tools like profilers and
11286 debuggers will give information in terms of the original unchopped file.
11287
11288 If the original file to be chopped itself contains
11289 a @code{Source_Reference}
11290 pragma referencing a third file, then gnatchop respects
11291 this pragma, and the generated @code{Source_Reference} pragmas
11292 in the chopped file refer to the original file, with appropriate
11293 line numbers. This is particularly useful when @code{gnatchop}
11294 is used in conjunction with @code{gnatprep} to compile files that
11295 contain preprocessing statements and multiple units.
11296
11297 @item ^-v^/VERBOSE^
11298 @cindex @option{^-v^/VERBOSE^} (@code{gnatchop})
11299 Causes @code{gnatchop} to operate in verbose mode. The version
11300 number and copyright notice are output, as well as exact copies of
11301 the gnat1 commands spawned to obtain the chop control information.
11302
11303 @item ^-w^/OVERWRITE^
11304 @cindex @option{^-w^/OVERWRITE^} (@code{gnatchop})
11305 Overwrite existing file names. Normally @code{gnatchop} regards it as a
11306 fatal error if there is already a file with the same name as a
11307 file it would otherwise output, in other words if the files to be
11308 chopped contain duplicated units. This switch bypasses this
11309 check, and causes all but the last instance of such duplicated
11310 units to be skipped.
11311
11312 @ifclear vms
11313 @item --GCC=@var{xxxx}
11314 @cindex @option{--GCC=} (@code{gnatchop})
11315 Specify the path of the GNAT parser to be used. When this switch is used,
11316 no attempt is made to add the prefix to the GNAT parser executable.
11317 @end ifclear
11318 @end table
11319
11320 @node Examples of gnatchop Usage
11321 @section Examples of @code{gnatchop} Usage
11322
11323 @table @code
11324 @ifset vms
11325 @item gnatchop /OVERWRITE HELLO_S.ADA [PRERELEASE.FILES]
11326 @end ifset
11327 @ifclear vms
11328 @item gnatchop -w hello_s.ada prerelease/files
11329 @end ifclear
11330
11331 Chops the source file @file{hello_s.ada}. The output files will be
11332 placed in the directory @file{^prerelease/files^[PRERELEASE.FILES]^},
11333 overwriting any
11334 files with matching names in that directory (no files in the current
11335 directory are modified).
11336
11337 @item gnatchop ^archive^ARCHIVE.^
11338 Chops the source file @file{^archive^ARCHIVE.^}
11339 into the current directory. One
11340 useful application of @code{gnatchop} is in sending sets of sources
11341 around, for example in email messages. The required sources are simply
11342 concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^
11343 command), and then
11344 @command{gnatchop} is used at the other end to reconstitute the original
11345 file names.
11346
11347 @item gnatchop file1 file2 file3 direc
11348 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
11349 the resulting files in the directory @file{direc}. Note that if any units
11350 occur more than once anywhere within this set of files, an error message
11351 is generated, and no files are written. To override this check, use the
11352 @option{^-w^/OVERWRITE^} switch,
11353 in which case the last occurrence in the last file will
11354 be the one that is output, and earlier duplicate occurrences for a given
11355 unit will be skipped.
11356 @end table
11357
11358 @node Configuration Pragmas
11359 @chapter Configuration Pragmas
11360 @cindex Configuration pragmas
11361 @cindex Pragmas, configuration
11362
11363 @noindent
11364 Configuration pragmas include those pragmas described as
11365 such in the Ada Reference Manual, as well as
11366 implementation-dependent pragmas that are configuration pragmas.
11367 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
11368 for details on these additional GNAT-specific configuration pragmas.
11369 Most notably, the pragma @code{Source_File_Name}, which allows
11370 specifying non-default names for source files, is a configuration
11371 pragma. The following is a complete list of configuration pragmas
11372 recognized by GNAT:
11373
11374 @smallexample
11375    Ada_83
11376    Ada_95
11377    Ada_05
11378    Ada_2005
11379    Assertion_Policy
11380    Assume_No_Invalid_Values
11381    C_Pass_By_Copy
11382    Check_Name
11383    Check_Policy
11384    Compile_Time_Error
11385    Compile_Time_Warning
11386    Compiler_Unit
11387    Component_Alignment
11388    Convention_Identifier
11389    Debug_Policy
11390    Detect_Blocking
11391    Discard_Names
11392    Elaboration_Checks
11393    Eliminate
11394    Extend_System
11395    Extensions_Allowed
11396    External_Name_Casing
11397    Fast_Math
11398    Favor_Top_Level
11399    Float_Representation
11400    Implicit_Packing
11401    Initialize_Scalars
11402    Interrupt_State
11403    License
11404    Locking_Policy
11405    Long_Float
11406    No_Run_Time
11407    No_Strict_Aliasing
11408    Normalize_Scalars
11409    Optimize_Alignment
11410    Persistent_BSS
11411    Polling
11412    Priority_Specific_Dispatching
11413    Profile
11414    Profile_Warnings
11415    Propagate_Exceptions
11416    Queuing_Policy
11417    Ravenscar
11418    Restricted_Run_Time
11419    Restrictions
11420    Restrictions_Warnings
11421    Reviewable
11422    Source_File_Name
11423    Source_File_Name_Project
11424    Style_Checks
11425    Suppress
11426    Suppress_Exception_Locations
11427    Task_Dispatching_Policy
11428    Universal_Data
11429    Unsuppress
11430    Use_VADS_Size
11431    Validity_Checks
11432    Warnings
11433    Wide_Character_Encoding
11434
11435 @end smallexample
11436
11437 @menu
11438 * Handling of Configuration Pragmas::
11439 * The Configuration Pragmas Files::
11440 @end menu
11441
11442 @node Handling of Configuration Pragmas
11443 @section Handling of Configuration Pragmas
11444
11445 Configuration pragmas may either appear at the start of a compilation
11446 unit, in which case they apply only to that unit, or they may apply to
11447 all compilations performed in a given compilation environment.
11448
11449 GNAT also provides the @code{gnatchop} utility to provide an automatic
11450 way to handle configuration pragmas following the semantics for
11451 compilations (that is, files with multiple units), described in the RM.
11452 See @ref{Operating gnatchop in Compilation Mode} for details.
11453 However, for most purposes, it will be more convenient to edit the
11454 @file{gnat.adc} file that contains configuration pragmas directly,
11455 as described in the following section.
11456
11457 @node The Configuration Pragmas Files
11458 @section The Configuration Pragmas Files
11459 @cindex @file{gnat.adc}
11460
11461 @noindent
11462 In GNAT a compilation environment is defined by the current
11463 directory at the time that a compile command is given. This current
11464 directory is searched for a file whose name is @file{gnat.adc}. If
11465 this file is present, it is expected to contain one or more
11466 configuration pragmas that will be applied to the current compilation.
11467 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
11468 considered.
11469
11470 Configuration pragmas may be entered into the @file{gnat.adc} file
11471 either by running @code{gnatchop} on a source file that consists only of
11472 configuration pragmas, or more conveniently  by
11473 direct editing of the @file{gnat.adc} file, which is a standard format
11474 source file.
11475
11476 In addition to @file{gnat.adc}, additional files containing configuration
11477 pragmas may be applied to the current compilation using the switch
11478 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
11479 contains only configuration pragmas. These configuration pragmas are
11480 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
11481 is present and switch @option{-gnatA} is not used).
11482
11483 It is allowed to specify several switches @option{-gnatec}, all of which
11484 will be taken into account.
11485
11486 If you are using project file, a separate mechanism is provided using
11487 project attributes, see @ref{Specifying Configuration Pragmas} for more
11488 details.
11489
11490 @ifset vms
11491 Of special interest to GNAT OpenVMS Alpha is the following
11492 configuration pragma:
11493
11494 @smallexample @c ada
11495 @cartouche
11496 pragma Extend_System (Aux_DEC);
11497 @end cartouche
11498 @end smallexample
11499
11500 @noindent
11501 In the presence of this pragma, GNAT adds to the definition of the
11502 predefined package SYSTEM all the additional types and subprograms that are
11503 defined in HP Ada. See @ref{Compatibility with HP Ada} for details.
11504 @end ifset
11505
11506 @node Handling Arbitrary File Naming Conventions Using gnatname
11507 @chapter Handling Arbitrary File Naming Conventions Using @code{gnatname}
11508 @cindex Arbitrary File Naming Conventions
11509
11510 @menu
11511 * Arbitrary File Naming Conventions::
11512 * Running gnatname::
11513 * Switches for gnatname::
11514 * Examples of gnatname Usage::
11515 @end menu
11516
11517 @node Arbitrary File Naming Conventions
11518 @section Arbitrary File Naming Conventions
11519
11520 @noindent
11521 The GNAT compiler must be able to know the source file name of a compilation
11522 unit.  When using the standard GNAT default file naming conventions
11523 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
11524 does not need additional information.
11525
11526 @noindent
11527 When the source file names do not follow the standard GNAT default file naming
11528 conventions, the GNAT compiler must be given additional information through
11529 a configuration pragmas file (@pxref{Configuration Pragmas})
11530 or a project file.
11531 When the non-standard file naming conventions are well-defined,
11532 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
11533 (@pxref{Alternative File Naming Schemes}) may be sufficient. However,
11534 if the file naming conventions are irregular or arbitrary, a number
11535 of pragma @code{Source_File_Name} for individual compilation units
11536 must be defined.
11537 To help maintain the correspondence between compilation unit names and
11538 source file names within the compiler,
11539 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
11540 set of files.
11541
11542 @node Running gnatname
11543 @section Running @code{gnatname}
11544
11545 @noindent
11546 The usual form of the @code{gnatname} command is
11547
11548 @smallexample
11549 $ gnatname @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}
11550       @r{[}--and @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}@r{]}
11551 @end smallexample
11552
11553 @noindent
11554 All of the arguments are optional. If invoked without any argument,
11555 @code{gnatname} will display its usage.
11556
11557 @noindent
11558 When used with at least one naming pattern, @code{gnatname} will attempt to
11559 find all the compilation units in files that follow at least one of the
11560 naming patterns. To find these compilation units,
11561 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
11562 regular files.
11563
11564 @noindent
11565 One or several Naming Patterns may be given as arguments to @code{gnatname}.
11566 Each Naming Pattern is enclosed between double quotes.
11567 A Naming Pattern is a regular expression similar to the wildcard patterns
11568 used in file names by the Unix shells or the DOS prompt.
11569
11570 @noindent
11571 @code{gnatname} may be called with several sections of directories/patterns.
11572 Sections are separated by switch @code{--and}. In each section, there must be
11573 at least one pattern. If no directory is specified in a section, the current
11574 directory (or the project directory is @code{-P} is used) is implied.
11575 The options other that the directory switches and the patterns apply globally
11576 even if they are in different sections.
11577
11578 @noindent
11579 Examples of Naming Patterns are
11580
11581 @smallexample
11582    "*.[12].ada"
11583    "*.ad[sb]*"
11584    "body_*"    "spec_*"
11585 @end smallexample
11586
11587 @noindent
11588 For a more complete description of the syntax of Naming Patterns,
11589 see the second kind of regular expressions described in @file{g-regexp.ads}
11590 (the ``Glob'' regular expressions).
11591
11592 @noindent
11593 When invoked with no switch @code{-P}, @code{gnatname} will create a
11594 configuration pragmas file @file{gnat.adc} in the current working directory,
11595 with pragmas @code{Source_File_Name} for each file that contains a valid Ada
11596 unit.
11597
11598 @node Switches for gnatname
11599 @section Switches for @code{gnatname}
11600
11601 @noindent
11602 Switches for @code{gnatname} must precede any specified Naming Pattern.
11603
11604 @noindent
11605 You may specify any of the following switches to @code{gnatname}:
11606
11607 @table @option
11608 @c !sort!
11609
11610 @item --version
11611 @cindex @option{--version} @command{gnatname}
11612 Display Copyright and version, then exit disregarding all other options.
11613
11614 @item --help
11615 @cindex @option{--help} @command{gnatname}
11616 If @option{--version} was not used, display usage, then exit disregarding
11617 all other options.
11618
11619 @item --and
11620 Start another section of directories/patterns.
11621
11622 @item ^-c^/CONFIG_FILE=^@file{file}
11623 @cindex @option{^-c^/CONFIG_FILE^} (@code{gnatname})
11624 Create a configuration pragmas file @file{file} (instead of the default
11625 @file{gnat.adc}).
11626 @ifclear vms
11627 There may be zero, one or more space between @option{-c} and
11628 @file{file}.
11629 @end ifclear
11630 @file{file} may include directory information. @file{file} must be
11631 writable. There may be only one switch @option{^-c^/CONFIG_FILE^}.
11632 When a switch @option{^-c^/CONFIG_FILE^} is
11633 specified, no switch @option{^-P^/PROJECT_FILE^} may be specified (see below).
11634
11635 @item ^-d^/SOURCE_DIRS=^@file{dir}
11636 @cindex @option{^-d^/SOURCE_DIRS^} (@code{gnatname})
11637 Look for source files in directory @file{dir}. There may be zero, one or more
11638 spaces between @option{^-d^/SOURCE_DIRS=^} and @file{dir}.
11639 When a switch @option{^-d^/SOURCE_DIRS^}
11640 is specified, the current working directory will not be searched for source
11641 files, unless it is explicitly specified with a @option{^-d^/SOURCE_DIRS^}
11642 or @option{^-D^/DIR_FILES^} switch.
11643 Several switches @option{^-d^/SOURCE_DIRS^} may be specified.
11644 If @file{dir} is a relative path, it is relative to the directory of
11645 the configuration pragmas file specified with switch
11646 @option{^-c^/CONFIG_FILE^},
11647 or to the directory of the project file specified with switch
11648 @option{^-P^/PROJECT_FILE^} or,
11649 if neither switch @option{^-c^/CONFIG_FILE^}
11650 nor switch @option{^-P^/PROJECT_FILE^} are specified, it is relative to the
11651 current working directory. The directory
11652 specified with switch @option{^-d^/SOURCE_DIRS^} must exist and be readable.
11653
11654 @item ^-D^/DIRS_FILE=^@file{file}
11655 @cindex @option{^-D^/DIRS_FILE^} (@code{gnatname})
11656 Look for source files in all directories listed in text file @file{file}.
11657 There may be zero, one or more spaces between @option{^-D^/DIRS_FILE=^}
11658 and @file{file}.
11659 @file{file} must be an existing, readable text file.
11660 Each nonempty line in @file{file} must be a directory.
11661 Specifying switch @option{^-D^/DIRS_FILE^} is equivalent to specifying as many
11662 switches @option{^-d^/SOURCE_DIRS^} as there are nonempty lines in
11663 @file{file}.
11664
11665 @item ^-f^/FOREIGN_PATTERN=^@file{pattern}
11666 @cindex @option{^-f^/FOREIGN_PATTERN^} (@code{gnatname})
11667 Foreign patterns. Using this switch, it is possible to add sources of languages
11668 other than Ada to the list of sources of a project file.
11669 It is only useful if a ^-P^/PROJECT_FILE^ switch is used.
11670 For example,
11671 @smallexample
11672 gnatname ^-Pprj -f"*.c"^/PROJECT_FILE=PRJ /FOREIGN_PATTERN=*.C^ "*.ada"
11673 @end smallexample
11674 @noindent
11675 will look for Ada units in all files with the @file{.ada} extension,
11676 and will add to the list of file for project @file{prj.gpr} the C files
11677 with extension @file{.^c^C^}.
11678
11679 @item ^-h^/HELP^
11680 @cindex @option{^-h^/HELP^} (@code{gnatname})
11681 Output usage (help) information. The output is written to @file{stdout}.
11682
11683 @item ^-P^/PROJECT_FILE=^@file{proj}
11684 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatname})
11685 Create or update project file @file{proj}. There may be zero, one or more space
11686 between @option{-P} and @file{proj}. @file{proj} may include directory
11687 information. @file{proj} must be writable.
11688 There may be only one switch @option{^-P^/PROJECT_FILE^}.
11689 When a switch @option{^-P^/PROJECT_FILE^} is specified,
11690 no switch @option{^-c^/CONFIG_FILE^} may be specified.
11691
11692 @item ^-v^/VERBOSE^
11693 @cindex @option{^-v^/VERBOSE^} (@code{gnatname})
11694 Verbose mode. Output detailed explanation of behavior to @file{stdout}.
11695 This includes name of the file written, the name of the directories to search
11696 and, for each file in those directories whose name matches at least one of
11697 the Naming Patterns, an indication of whether the file contains a unit,
11698 and if so the name of the unit.
11699
11700 @item ^-v -v^/VERBOSE /VERBOSE^
11701 @cindex @option{^-v -v^/VERBOSE /VERBOSE^} (@code{gnatname})
11702 Very Verbose mode. In addition to the output produced in verbose mode,
11703 for each file in the searched directories whose name matches none of
11704 the Naming Patterns, an indication is given that there is no match.
11705
11706 @item ^-x^/EXCLUDED_PATTERN=^@file{pattern}
11707 @cindex @option{^-x^/EXCLUDED_PATTERN^} (@code{gnatname})
11708 Excluded patterns. Using this switch, it is possible to exclude some files
11709 that would match the name patterns. For example,
11710 @smallexample
11711 gnatname ^-x "*_nt.ada"^/EXCLUDED_PATTERN=*_nt.ada^ "*.ada"
11712 @end smallexample
11713 @noindent
11714 will look for Ada units in all files with the @file{.ada} extension,
11715 except those whose names end with @file{_nt.ada}.
11716
11717 @end table
11718
11719 @node Examples of gnatname Usage
11720 @section Examples of @code{gnatname} Usage
11721
11722 @ifset vms
11723 @smallexample
11724 $ gnatname /CONFIG_FILE=[HOME.ME]NAMES.ADC /SOURCE_DIRS=SOURCES "[a-z]*.ada*"
11725 @end smallexample
11726 @end ifset
11727
11728 @ifclear vms
11729 @smallexample
11730 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
11731 @end smallexample
11732 @end ifclear
11733
11734 @noindent
11735 In this example, the directory @file{^/home/me^[HOME.ME]^} must already exist
11736 and be writable. In addition, the directory
11737 @file{^/home/me/sources^[HOME.ME.SOURCES]^} (specified by
11738 @option{^-d sources^/SOURCE_DIRS=SOURCES^}) must exist and be readable.
11739
11740 @ifclear vms
11741 Note the optional spaces after @option{-c} and @option{-d}.
11742 @end ifclear
11743
11744 @smallexample
11745 @ifclear vms
11746 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
11747   -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
11748 @end ifclear
11749 @ifset vms
11750 $ gnatname  /PROJECT_FILE=[HOME.ME]PROJ
11751   /EXCLUDED_PATTERN=*_nt_body.ada
11752   /SOURCE_DIRS=(SOURCES,[SOURCES.PLUS])
11753   /DIRS_FILE=COMMON_DIRS.TXT "body_*" "spec_*"
11754 @end ifset
11755 @end smallexample
11756
11757 Note that several switches @option{^-d^/SOURCE_DIRS^} may be used,
11758 even in conjunction with one or several switches
11759 @option{^-D^/DIRS_FILE^}. Several Naming Patterns and one excluded pattern
11760 are used in this example.
11761
11762 @c *****************************************
11763 @c * G N A T  P r o j e c t  M a n a g e r *
11764 @c *****************************************
11765 @node GNAT Project Manager
11766 @chapter GNAT Project Manager
11767
11768 @menu
11769 * Introduction::
11770 * Examples of Project Files::
11771 * Project File Syntax::
11772 * Objects and Sources in Project Files::
11773 * Importing Projects::
11774 * Project Extension::
11775 * Project Hierarchy Extension::
11776 * External References in Project Files::
11777 * Packages in Project Files::
11778 * Variables from Imported Projects::
11779 * Naming Schemes::
11780 * Library Projects::
11781 * Stand-alone Library Projects::
11782 * Switches Related to Project Files::
11783 * Tools Supporting Project Files::
11784 * An Extended Example::
11785 * Project File Complete Syntax::
11786 @end menu
11787
11788 @c ****************
11789 @c * Introduction *
11790 @c ****************
11791
11792 @node Introduction
11793 @section Introduction
11794
11795 @noindent
11796 This chapter describes GNAT's @emph{Project Manager}, a facility that allows
11797 you to manage complex builds involving a number of source files, directories,
11798 and compilation options for different system configurations. In particular,
11799 project files allow you to specify:
11800 @itemize @bullet
11801 @item
11802 The directory or set of directories containing the source files, and/or the
11803 names of the specific source files themselves
11804 @item
11805 The directory in which the compiler's output
11806 (@file{ALI} files, object files, tree files) is to be placed
11807 @item
11808 The directory in which the executable programs is to be placed
11809 @item
11810 ^Switch^Switch^ settings for any of the project-enabled tools
11811 (@command{gnatmake}, compiler, binder, linker, @code{gnatls}, @code{gnatxref},
11812 @code{gnatfind}); you can apply these settings either globally or to individual
11813 compilation units.
11814 @item
11815 The source files containing the main subprogram(s) to be built
11816 @item
11817 The source programming language(s) (currently Ada and/or C)
11818 @item
11819 Source file naming conventions; you can specify these either globally or for
11820 individual compilation units
11821 @end itemize
11822
11823 @menu
11824 * Project Files::
11825 @end menu
11826
11827 @node Project Files
11828 @subsection Project Files
11829
11830 @noindent
11831 Project files are written in a syntax close to that of Ada, using  familiar
11832 notions such as packages, context clauses, declarations, default values,
11833 assignments, and inheritance. Finally, project files can be built
11834 hierarchically from other project files, simplifying complex system
11835 integration and project reuse.
11836
11837 A @dfn{project} is a specific set of values for various compilation properties.
11838 The settings for a given project are described by means of
11839 a @dfn{project file}, which is a text file written in an Ada-like syntax.
11840 Property values in project files are either strings or lists of strings.
11841 Properties that are not explicitly set receive default values.  A project
11842 file may interrogate the values of @dfn{external variables} (user-defined
11843 command-line switches or environment variables), and it may specify property
11844 settings conditionally, based on the value of such variables.
11845
11846 In simple cases, a project's source files depend only on other source files
11847 in the same project, or on the predefined libraries.  (@emph{Dependence} is
11848 used in
11849 the Ada technical sense; as in one Ada unit @code{with}ing another.)  However,
11850 the Project Manager also allows more sophisticated arrangements,
11851 where the source files in one project depend on source files in other
11852 projects:
11853 @itemize @bullet
11854 @item
11855 One project can @emph{import} other projects containing needed source files.
11856 @item
11857 You can organize GNAT projects in a hierarchy: a @emph{child} project
11858 can extend a @emph{parent} project, inheriting the parent's source files and
11859 optionally overriding any of them with alternative versions
11860 @end itemize
11861
11862 @noindent
11863 More generally, the Project Manager lets you structure large development
11864 efforts into hierarchical subsystems, where build decisions are delegated
11865 to the subsystem level, and thus different compilation environments
11866 (^switch^switch^ settings) used for different subsystems.
11867
11868 The Project Manager is invoked through the
11869 @option{^-P^/PROJECT_FILE=^@emph{projectfile}}
11870 switch to @command{gnatmake} or to the @command{^gnat^GNAT^} front driver.
11871 @ifclear vms
11872 There may be zero, one or more spaces between @option{-P} and
11873 @option{@emph{projectfile}}.
11874 @end ifclear
11875 If you want to define (on the command line) an external variable that is
11876 queried by the project file, you must use the
11877 @option{^-X^/EXTERNAL_REFERENCE=^@emph{vbl}=@emph{value}} switch.
11878 The Project Manager parses and interprets the project file, and drives the
11879 invoked tool based on the project settings.
11880
11881 The Project Manager supports a wide range of development strategies,
11882 for systems of all sizes.  Here are some typical practices that are
11883 easily handled:
11884 @itemize @bullet
11885 @item
11886 Using a common set of source files, but generating object files in different
11887 directories via different ^switch^switch^ settings
11888 @item
11889 Using a mostly-shared set of source files, but with different versions of
11890 some unit or units
11891 @end itemize
11892
11893 @noindent
11894 The destination of an executable can be controlled inside a project file
11895 using the @option{^-o^-o^}
11896 ^switch^switch^.
11897 In the absence of such a ^switch^switch^ either inside
11898 the project file or on the command line, any executable files generated by
11899 @command{gnatmake} are placed in the directory @code{Exec_Dir} specified
11900 in the project file. If no @code{Exec_Dir} is specified, they will be placed
11901 in the object directory of the project.
11902
11903 You can use project files to achieve some of the effects of a source
11904 versioning system (for example, defining separate projects for
11905 the different sets of sources that comprise different releases) but the
11906 Project Manager is independent of any source configuration management tools
11907 that might be used by the developers.
11908
11909 The next section introduces the main features of GNAT's project facility
11910 through a sequence of examples; subsequent sections will present the syntax
11911 and semantics in more detail. A more formal description of the project
11912 facility appears in @ref{Project File Reference,,, gnat_rm, GNAT
11913 Reference Manual}.
11914
11915 @c *****************************
11916 @c * Examples of Project Files *
11917 @c *****************************
11918
11919 @node Examples of Project Files
11920 @section Examples of Project Files
11921 @noindent
11922 This section illustrates some of the typical uses of project files and
11923 explains their basic structure and behavior.
11924
11925 @menu
11926 * Common Sources with Different ^Switches^Switches^ and Directories::
11927 * Using External Variables::
11928 * Importing Other Projects::
11929 * Extending a Project::
11930 @end menu
11931
11932 @node Common Sources with Different ^Switches^Switches^ and Directories
11933 @subsection Common Sources with Different ^Switches^Switches^ and Directories
11934
11935 @menu
11936 * Source Files::
11937 * Specifying the Object Directory::
11938 * Specifying the Exec Directory::
11939 * Project File Packages::
11940 * Specifying ^Switch^Switch^ Settings::
11941 * Main Subprograms::
11942 * Executable File Names::
11943 * Source File Naming Conventions::
11944 * Source Language(s)::
11945 @end menu
11946
11947 @noindent
11948 Suppose that the Ada source files @file{pack.ads}, @file{pack.adb}, and
11949 @file{proc.adb} are in the @file{/common} directory.  The file
11950 @file{proc.adb} contains an Ada main subprogram @code{Proc} that @code{with}s
11951 package @code{Pack}.  We want to compile these source files under two sets
11952 of ^switches^switches^:
11953 @itemize @bullet
11954 @item
11955 When debugging, we want to pass the @option{-g} switch to @command{gnatmake},
11956 and the @option{^-gnata^-gnata^},
11957 @option{^-gnato^-gnato^},
11958 and @option{^-gnatE^-gnatE^} switches to the
11959 compiler; the compiler's output is to appear in @file{/common/debug}
11960 @item
11961 When preparing a release version, we want to pass the @option{^-O2^O2^} switch
11962 to the compiler; the compiler's output is to appear in @file{/common/release}
11963 @end itemize
11964
11965 @noindent
11966 The GNAT project files shown below, respectively @file{debug.gpr} and
11967 @file{release.gpr} in the @file{/common} directory, achieve these effects.
11968
11969 Schematically:
11970 @smallexample
11971 @group
11972 ^/common^[COMMON]^
11973   debug.gpr
11974   release.gpr
11975   pack.ads
11976   pack.adb
11977   proc.adb
11978 @end group
11979 @group
11980 ^/common/debug^[COMMON.DEBUG]^
11981   proc.ali, proc.o
11982   pack.ali, pack.o
11983 @end group
11984 @group
11985 ^/common/release^[COMMON.RELEASE]^
11986   proc.ali, proc.o
11987   pack.ali, pack.o
11988 @end group
11989 @end smallexample
11990 Here are the corresponding project files:
11991
11992 @smallexample @c projectfile
11993 @group
11994 project Debug is
11995   for Object_Dir use "debug";
11996   for Main use ("proc");
11997
11998   package Builder is
11999     for ^Default_Switches^Default_Switches^ ("Ada")
12000         use ("^-g^-g^");
12001     for Executable ("proc.adb") use "proc1";
12002   end Builder;
12003 @end group
12004
12005 @group
12006   package Compiler is
12007     for ^Default_Switches^Default_Switches^ ("Ada")
12008        use ("-fstack-check",
12009             "^-gnata^-gnata^",
12010             "^-gnato^-gnato^",
12011             "^-gnatE^-gnatE^");
12012   end Compiler;
12013 end Debug;
12014 @end group
12015 @end smallexample
12016
12017 @smallexample @c projectfile
12018 @group
12019 project Release is
12020   for Object_Dir use "release";
12021   for Exec_Dir use ".";
12022   for Main use ("proc");
12023
12024   package Compiler is
12025     for ^Default_Switches^Default_Switches^ ("Ada")
12026         use ("^-O2^-O2^");
12027   end Compiler;
12028 end Release;
12029 @end group
12030 @end smallexample
12031
12032 @noindent
12033 The name of the project defined by @file{debug.gpr} is @code{"Debug"} (case
12034 insensitive), and analogously the project defined by @file{release.gpr} is
12035 @code{"Release"}.  For consistency the file should have the same name as the
12036 project, and the project file's extension should be @code{"gpr"}. These
12037 conventions are not required, but a warning is issued if they are not followed.
12038
12039 If the current directory is @file{^/temp^[TEMP]^}, then the command
12040 @smallexample
12041 gnatmake ^-P/common/debug.gpr^/PROJECT_FILE=[COMMON]DEBUG^
12042 @end smallexample
12043
12044 @noindent
12045 generates object and ALI files in @file{^/common/debug^[COMMON.DEBUG]^},
12046 as well as the @code{^proc1^PROC1.EXE^} executable,
12047 using the ^switch^switch^ settings defined in the project file.
12048
12049 Likewise, the command
12050 @smallexample
12051 gnatmake ^-P/common/release.gpr^/PROJECT_FILE=[COMMON]RELEASE^
12052 @end smallexample
12053
12054 @noindent
12055 generates object and ALI files in @file{^/common/release^[COMMON.RELEASE]^},
12056 and the @code{^proc^PROC.EXE^}
12057 executable in @file{^/common^[COMMON]^},
12058 using the ^switch^switch^ settings from the project file.
12059
12060 @node Source Files
12061 @unnumberedsubsubsec Source Files
12062
12063 @noindent
12064 If a project file does not explicitly specify a set of source directories or
12065 a set of source files, then by default the project's source files are the
12066 Ada source files in the project file directory.  Thus @file{pack.ads},
12067 @file{pack.adb}, and @file{proc.adb} are the source files for both projects.
12068
12069 @node Specifying the Object Directory
12070 @unnumberedsubsubsec Specifying the Object Directory
12071
12072 @noindent
12073 Several project properties are modeled by Ada-style @emph{attributes};
12074 a property is defined by supplying the equivalent of an Ada attribute
12075 definition clause in the project file.
12076 A project's object directory is another such a property; the corresponding
12077 attribute is @code{Object_Dir}, and its value is also a string expression,
12078 specified either as absolute or relative. In the later case,
12079 it is relative to the project file directory. Thus the compiler's
12080 output is directed to @file{^/common/debug^[COMMON.DEBUG]^}
12081 (for the @code{Debug} project)
12082 and to @file{^/common/release^[COMMON.RELEASE]^}
12083 (for the @code{Release} project).
12084 If @code{Object_Dir} is not specified, then the default is the project file
12085 directory itself.
12086
12087 @node Specifying the Exec Directory
12088 @unnumberedsubsubsec Specifying the Exec Directory
12089
12090 @noindent
12091 A project's exec directory is another property; the corresponding
12092 attribute is @code{Exec_Dir}, and its value is also a string expression,
12093 either specified as relative or absolute. If @code{Exec_Dir} is not specified,
12094 then the default is the object directory (which may also be the project file
12095 directory if attribute @code{Object_Dir} is not specified). Thus the executable
12096 is placed in @file{^/common/debug^[COMMON.DEBUG]^}
12097 for the @code{Debug} project (attribute @code{Exec_Dir} not specified)
12098 and in @file{^/common^[COMMON]^} for the @code{Release} project.
12099
12100 @node Project File Packages
12101 @unnumberedsubsubsec Project File Packages
12102
12103 @noindent
12104 A GNAT tool that is integrated with the Project Manager is modeled by a
12105 corresponding package in the project file. In the example above,
12106 The @code{Debug} project defines the packages @code{Builder}
12107 (for @command{gnatmake}) and @code{Compiler};
12108 the @code{Release} project defines only the @code{Compiler} package.
12109
12110 The Ada-like package syntax is not to be taken literally.  Although packages in
12111 project files bear a surface resemblance to packages in Ada source code, the
12112 notation is simply a way to convey a grouping of properties for a named
12113 entity.  Indeed, the package names permitted in project files are restricted
12114 to a predefined set, corresponding to the project-aware tools, and the contents
12115 of packages are limited to a small set of constructs.
12116 The packages in the example above contain attribute definitions.
12117
12118 @node Specifying ^Switch^Switch^ Settings
12119 @unnumberedsubsubsec Specifying ^Switch^Switch^ Settings
12120
12121 @noindent
12122 ^Switch^Switch^ settings for a project-aware tool can be specified through
12123 attributes in the package that corresponds to the tool.
12124 The example above illustrates one of the relevant attributes,
12125 @code{^Default_Switches^Default_Switches^}, which is defined in packages
12126 in both project files.
12127 Unlike simple attributes like @code{Source_Dirs},
12128 @code{^Default_Switches^Default_Switches^} is
12129 known as an @emph{associative array}.  When you define this attribute, you must
12130 supply an ``index'' (a literal string), and the effect of the attribute
12131 definition is to set the value of the array at the specified index.
12132 For the @code{^Default_Switches^Default_Switches^} attribute,
12133 the index is a programming language (in our case, Ada),
12134 and the value specified (after @code{use}) must be a list
12135 of string expressions.
12136
12137 The attributes permitted in project files are restricted to a predefined set.
12138 Some may appear at project level, others in packages.
12139 For any attribute that is an associative array, the index must always be a
12140 literal string, but the restrictions on this string (e.g., a file name or a
12141 language name) depend on the individual attribute.
12142 Also depending on the attribute, its specified value will need to be either a
12143 string or a string list.
12144
12145 In the @code{Debug} project, we set the switches for two tools,
12146 @command{gnatmake} and the compiler, and thus we include the two corresponding
12147 packages; each package defines the @code{^Default_Switches^Default_Switches^}
12148 attribute with index @code{"Ada"}.
12149 Note that the package corresponding to
12150 @command{gnatmake} is named @code{Builder}.  The @code{Release} project is
12151 similar, but only includes the @code{Compiler} package.
12152
12153 In project @code{Debug} above, the ^switches^switches^ starting with
12154 @option{-gnat} that are specified in package @code{Compiler}
12155 could have been placed in package @code{Builder}, since @command{gnatmake}
12156 transmits all such ^switches^switches^ to the compiler.
12157
12158 @node Main Subprograms
12159 @unnumberedsubsubsec Main Subprograms
12160
12161 @noindent
12162 One of the specifiable properties of a project is a list of files that contain
12163 main subprograms.  This property is captured in the @code{Main} attribute,
12164 whose value is a list of strings.  If a project defines the @code{Main}
12165 attribute, it is not necessary to identify the main subprogram(s) when
12166 invoking @command{gnatmake} (@pxref{gnatmake and Project Files}).
12167
12168 @node Executable File Names
12169 @unnumberedsubsubsec Executable File Names
12170
12171 @noindent
12172 By default, the executable file name corresponding to a main source is
12173 deduced from the main source file name. Through the attributes
12174 @code{Executable} and @code{Executable_Suffix} of package @code{Builder},
12175 it is possible to change this default.
12176 In project @code{Debug} above, the executable file name
12177 for main source @file{^proc.adb^PROC.ADB^} is
12178 @file{^proc1^PROC1.EXE^}.
12179 Attribute @code{Executable_Suffix}, when specified, may change the suffix
12180 of the executable files, when no attribute @code{Executable} applies:
12181 its value replace the platform-specific executable suffix.
12182 Attributes @code{Executable} and @code{Executable_Suffix} are the only ways to
12183 specify a non-default executable file name when several mains are built at once
12184 in a single @command{gnatmake} command.
12185
12186 @node Source File Naming Conventions
12187 @unnumberedsubsubsec Source File Naming Conventions
12188
12189 @noindent
12190 Since the project files above do not specify any source file naming
12191 conventions, the GNAT defaults are used.  The mechanism for defining source
12192 file naming conventions -- a package named @code{Naming} --
12193 is described below (@pxref{Naming Schemes}).
12194
12195 @node Source Language(s)
12196 @unnumberedsubsubsec Source Language(s)
12197
12198 @noindent
12199 Since the project files do not specify a @code{Languages} attribute, by
12200 default the GNAT tools assume that the language of the project file is Ada.
12201 More generally, a project can comprise source files
12202 in Ada, C, and/or other languages.
12203
12204 @node Using External Variables
12205 @subsection Using External Variables
12206
12207 @noindent
12208 Instead of supplying different project files for debug and release, we can
12209 define a single project file that queries an external variable (set either
12210 on the command line or via an ^environment variable^logical name^) in order to
12211 conditionally define the appropriate settings.  Again, assume that the
12212 source files @file{pack.ads}, @file{pack.adb}, and @file{proc.adb} are
12213 located in directory @file{^/common^[COMMON]^}.  The following project file,
12214 @file{build.gpr}, queries the external variable named @code{STYLE} and
12215 defines an object directory and ^switch^switch^ settings based on whether
12216 the value is @code{"deb"} (debug) or @code{"rel"} (release), and where
12217 the default is @code{"deb"}.
12218
12219 @smallexample @c projectfile
12220 @group
12221 project Build is
12222   for Main use ("proc");
12223
12224   type Style_Type is ("deb", "rel");
12225   Style : Style_Type := external ("STYLE", "deb");
12226
12227   case Style is
12228     when "deb" =>
12229       for Object_Dir use "debug";
12230
12231     when "rel" =>
12232       for Object_Dir use "release";
12233       for Exec_Dir use ".";
12234   end case;
12235 @end group
12236
12237 @group
12238   package Builder is
12239
12240     case Style is
12241       when "deb" =>
12242         for ^Default_Switches^Default_Switches^ ("Ada")
12243             use ("^-g^-g^");
12244         for Executable ("proc") use "proc1";
12245       when others =>
12246         null;
12247     end case;
12248
12249   end Builder;
12250 @end group
12251
12252 @group
12253   package Compiler is
12254
12255     case Style is
12256       when "deb" =>
12257         for ^Default_Switches^Default_Switches^ ("Ada")
12258             use ("^-gnata^-gnata^",
12259                  "^-gnato^-gnato^",
12260                  "^-gnatE^-gnatE^");
12261
12262       when "rel" =>
12263         for ^Default_Switches^Default_Switches^ ("Ada")
12264             use ("^-O2^-O2^");
12265     end case;
12266
12267   end Compiler;
12268
12269 end Build;
12270 @end group
12271 @end smallexample
12272
12273 @noindent
12274 @code{Style_Type} is an example of a @emph{string type}, which is the project
12275 file analog of an Ada enumeration type but whose components are string literals
12276 rather than identifiers.  @code{Style} is declared as a variable of this type.
12277
12278 The form @code{external("STYLE", "deb")} is known as an
12279 @emph{external reference}; its first argument is the name of an
12280 @emph{external variable}, and the second argument is a default value to be
12281 used if the external variable doesn't exist.  You can define an external
12282 variable on the command line via the @option{^-X^/EXTERNAL_REFERENCE^} switch,
12283 or you can use ^an environment variable^a logical name^
12284 as an external variable.
12285
12286 Each @code{case} construct is expanded by the Project Manager based on the
12287 value of @code{Style}. Thus the command
12288 @ifclear vms
12289 @smallexample
12290 gnatmake -P/common/build.gpr -XSTYLE=deb
12291 @end smallexample
12292 @end ifclear
12293
12294 @ifset vms
12295 @smallexample
12296 gnatmake /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=deb
12297 @end smallexample
12298 @end ifset
12299
12300 @noindent
12301 is equivalent to the @command{gnatmake} invocation using the project file
12302 @file{debug.gpr} in the earlier example.  So is the command
12303 @smallexample
12304 gnatmake ^-P/common/build.gpr^/PROJECT_FILE=[COMMON]BUILD.GPR^
12305 @end smallexample
12306
12307 @noindent
12308 since @code{"deb"} is the default for @code{STYLE}.
12309
12310 Analogously,
12311
12312 @ifclear vms
12313 @smallexample
12314 gnatmake -P/common/build.gpr -XSTYLE=rel
12315 @end smallexample
12316 @end ifclear
12317
12318 @ifset vms
12319 @smallexample
12320 GNAT MAKE /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=rel
12321 @end smallexample
12322 @end ifset
12323
12324 @noindent
12325 is equivalent to the @command{gnatmake} invocation using the project file
12326 @file{release.gpr} in the earlier example.
12327
12328 @node Importing Other Projects
12329 @subsection Importing Other Projects
12330 @cindex @code{ADA_PROJECT_PATH}
12331 @cindex @code{GPR_PROJECT_PATH}
12332
12333 @noindent
12334 A compilation unit in a source file in one project may depend on compilation
12335 units in source files in other projects.  To compile this unit under
12336 control of a project file, the
12337 dependent project must @emph{import} the projects containing the needed source
12338 files.
12339 This effect is obtained using syntax similar to an Ada @code{with} clause,
12340 but where @code{with}ed entities are strings that denote project files.
12341
12342 As an example, suppose that the two projects @code{GUI_Proj} and
12343 @code{Comm_Proj} are defined in the project files @file{gui_proj.gpr} and
12344 @file{comm_proj.gpr} in directories @file{^/gui^[GUI]^}
12345 and @file{^/comm^[COMM]^}, respectively.
12346 Suppose that the source files for @code{GUI_Proj} are
12347 @file{gui.ads} and @file{gui.adb}, and that the source files for
12348 @code{Comm_Proj} are @file{comm.ads} and @file{comm.adb}, where each set of
12349 files is located in its respective project file directory.  Schematically:
12350
12351 @smallexample
12352 @group
12353 ^/gui^[GUI]^
12354   gui_proj.gpr
12355   gui.ads
12356   gui.adb
12357 @end group
12358
12359 @group
12360 ^/comm^[COMM]^
12361   comm_proj.gpr
12362   comm.ads
12363   comm.adb
12364 @end group
12365 @end smallexample
12366
12367 @noindent
12368 We want to develop an application in directory @file{^/app^[APP]^} that
12369 @code{with} the packages @code{GUI} and @code{Comm}, using the properties of
12370 the corresponding project files (e.g.@: the ^switch^switch^ settings
12371 and object directory).
12372 Skeletal code for a main procedure might be something like the following:
12373
12374 @smallexample @c ada
12375 @group
12376 with GUI, Comm;
12377 procedure App_Main is
12378    @dots{}
12379 begin
12380    @dots{}
12381 end App_Main;
12382 @end group
12383 @end smallexample
12384
12385 @noindent
12386 Here is a project file, @file{app_proj.gpr}, that achieves the desired
12387 effect:
12388
12389 @smallexample @c projectfile
12390 @group
12391 with "/gui/gui_proj", "/comm/comm_proj";
12392 project App_Proj is
12393    for Main use ("app_main");
12394 end App_Proj;
12395 @end group
12396 @end smallexample
12397
12398 @noindent
12399 Building an executable is achieved through the command:
12400 @smallexample
12401 gnatmake ^-P/app/app_proj^/PROJECT_FILE=[APP]APP_PROJ^
12402 @end smallexample
12403 @noindent
12404 which will generate the @code{^app_main^APP_MAIN.EXE^} executable
12405 in the directory where @file{app_proj.gpr} resides.
12406
12407 If an imported project file uses the standard extension (@code{^gpr^GPR^}) then
12408 (as illustrated above) the @code{with} clause can omit the extension.
12409
12410 Our example specified an absolute path for each imported project file.
12411 Alternatively, the directory name of an imported object can be omitted
12412 if either
12413 @itemize @bullet
12414 @item
12415 The imported project file is in the same directory as the importing project
12416 file, or
12417 @item
12418 You have defined one or two ^environment variables^logical names^
12419 that includes the directory containing
12420 the needed project file. The syntax of @code{GPR_PROJECT_PATH} and
12421 @code{ADA_PROJECT_PATH} is the same as
12422 the syntax of @code{ADA_INCLUDE_PATH} and @code{ADA_OBJECTS_PATH}: a list of
12423 directory names separated by colons (semicolons on Windows).
12424 @end itemize
12425
12426 @noindent
12427 Thus, if we define @code{ADA_PROJECT_PATH} or @code{GPR_PROJECT_PATH}
12428 to include @file{^/gui^[GUI]^} and
12429 @file{^/comm^[COMM]^}, then our project file @file{app_proj.gpr} can be written
12430 as follows:
12431
12432 @smallexample @c projectfile
12433 @group
12434 with "gui_proj", "comm_proj";
12435 project App_Proj is
12436    for Main use ("app_main");
12437 end App_Proj;
12438 @end group
12439 @end smallexample
12440
12441 @noindent
12442 Importing other projects can create ambiguities.
12443 For example, the same unit might be present in different imported projects, or
12444 it might be present in both the importing project and in an imported project.
12445 Both of these conditions are errors.  Note that in the current version of
12446 the Project Manager, it is illegal to have an ambiguous unit even if the
12447 unit is never referenced by the importing project.  This restriction may be
12448 relaxed in a future release.
12449
12450 @node Extending a Project
12451 @subsection Extending a Project
12452
12453 @noindent
12454 In large software systems it is common to have multiple
12455 implementations of a common interface; in Ada terms, multiple versions of a
12456 package body for the same spec.  For example, one implementation
12457 might be safe for use in tasking programs, while another might only be used
12458 in sequential applications.  This can be modeled in GNAT using the concept
12459 of @emph{project extension}.  If one project (the ``child'') @emph{extends}
12460 another project (the ``parent'') then by default all source files of the
12461 parent project are inherited by the child, but the child project can
12462 override any of the parent's source files with new versions, and can also
12463 add new files.  This facility is the project analog of a type extension in
12464 Object-Oriented Programming.  Project hierarchies are permitted (a child
12465 project may be the parent of yet another project), and a project that
12466 inherits one project can also import other projects.
12467
12468 As an example, suppose that directory @file{^/seq^[SEQ]^} contains the project
12469 file @file{seq_proj.gpr} as well as the source files @file{pack.ads},
12470 @file{pack.adb}, and @file{proc.adb}:
12471
12472 @smallexample
12473 @group
12474 ^/seq^[SEQ]^
12475   pack.ads
12476   pack.adb
12477   proc.adb
12478   seq_proj.gpr
12479 @end group
12480 @end smallexample
12481
12482 @noindent
12483 Note that the project file can simply be empty (that is, no attribute or
12484 package is defined):
12485
12486 @smallexample @c projectfile
12487 @group
12488 project Seq_Proj is
12489 end Seq_Proj;
12490 @end group
12491 @end smallexample
12492
12493 @noindent
12494 implying that its source files are all the Ada source files in the project
12495 directory.
12496
12497 Suppose we want to supply an alternate version of @file{pack.adb}, in
12498 directory @file{^/tasking^[TASKING]^}, but use the existing versions of
12499 @file{pack.ads} and @file{proc.adb}.  We can define a project
12500 @code{Tasking_Proj} that inherits @code{Seq_Proj}:
12501
12502 @smallexample
12503 @group
12504 ^/tasking^[TASKING]^
12505   pack.adb
12506   tasking_proj.gpr
12507 @end group
12508
12509 @group
12510 project Tasking_Proj extends "/seq/seq_proj" is
12511 end Tasking_Proj;
12512 @end group
12513 @end smallexample
12514
12515 @noindent
12516 The version of @file{pack.adb} used in a build depends on which project file
12517 is specified.
12518
12519 Note that we could have obtained the desired behavior using project import
12520 rather than project inheritance; a @code{base} project would contain the
12521 sources for @file{pack.ads} and @file{proc.adb}, a sequential project would
12522 import @code{base} and add @file{pack.adb}, and likewise a tasking project
12523 would import @code{base} and add a different version of @file{pack.adb}.  The
12524 choice depends on whether other sources in the original project need to be
12525 overridden.  If they do, then project extension is necessary, otherwise,
12526 importing is sufficient.
12527
12528 @noindent
12529 In a project file that extends another project file, it is possible to
12530 indicate that an inherited source is not part of the sources of the extending
12531 project. This is necessary sometimes when a package spec has been overloaded
12532 and no longer requires a body: in this case, it is necessary to indicate that
12533 the inherited body is not part of the sources of the project, otherwise there
12534 will be a compilation error when compiling the spec.
12535
12536 For that purpose, the attribute @code{Excluded_Source_Files} is used.
12537 Its value is a string list: a list of file names. It is also possible to use
12538 attribute @code{Excluded_Source_List_File}. Its value is a single string:
12539 the file name of a text file containing a list of file names, one per line.
12540
12541 @smallexample @c @projectfile
12542 project B extends "a" is
12543    for Source_Files use ("pkg.ads");
12544    --  New spec of Pkg does not need a completion
12545    for Excluded_Source_Files use ("pkg.adb");
12546 end B;
12547 @end smallexample
12548
12549 Attribute @code{Excluded_Source_Files} may also be used to check if a source
12550 is still needed: if it is possible to build using @command{gnatmake} when such
12551 a source is put in attribute @code{Excluded_Source_Files} of a project P, then
12552 it is possible to remove the source completely from a system that includes
12553 project P.
12554
12555 @c ***********************
12556 @c * Project File Syntax *
12557 @c ***********************
12558
12559 @node Project File Syntax
12560 @section Project File Syntax
12561
12562 @menu
12563 * Basic Syntax::
12564 * Qualified Projects::
12565 * Packages::
12566 * Expressions::
12567 * String Types::
12568 * Variables::
12569 * Attributes::
12570 * Associative Array Attributes::
12571 * case Constructions::
12572 @end menu
12573
12574 @noindent
12575 This section describes the structure of project files.
12576
12577 A project may be an @emph{independent project}, entirely defined by a single
12578 project file. Any Ada source file in an independent project depends only
12579 on the predefined library and other Ada source files in the same project.
12580
12581 @noindent
12582 A project may also @dfn{depend on} other projects, in either or both of
12583 the following ways:
12584 @itemize @bullet
12585 @item It may import any number of projects
12586 @item It may extend at most one other project
12587 @end itemize
12588
12589 @noindent
12590 The dependence relation is a directed acyclic graph (the subgraph reflecting
12591 the ``extends'' relation is a tree).
12592
12593 A project's @dfn{immediate sources} are the source files directly defined by
12594 that project, either implicitly by residing in the project file's directory,
12595 or explicitly through any of the source-related attributes described below.
12596 More generally, a project @var{proj}'s @dfn{sources} are the immediate sources
12597 of @var{proj} together with the immediate sources (unless overridden) of any
12598 project on which @var{proj} depends (either directly or indirectly).
12599
12600 @node Basic Syntax
12601 @subsection Basic Syntax
12602
12603 @noindent
12604 As seen in the earlier examples, project files have an Ada-like syntax.
12605 The minimal project file is:
12606 @smallexample @c projectfile
12607 @group
12608 project Empty is
12609
12610 end Empty;
12611 @end group
12612 @end smallexample
12613
12614 @noindent
12615 The identifier @code{Empty} is the name of the project.
12616 This project name must be present after the reserved
12617 word @code{end} at the end of the project file, followed by a semi-colon.
12618
12619 Any name in a project file, such as the project name or a variable name,
12620 has the same syntax as an Ada identifier.
12621
12622 The reserved words of project files are the Ada 95 reserved words plus
12623 @code{extends}, @code{external}, and @code{project}.  Note that the only Ada
12624 reserved words currently used in project file syntax are:
12625
12626 @itemize @bullet
12627 @item
12628 @code{all}
12629 @item
12630 @code{at}
12631 @item
12632 @code{case}
12633 @item
12634 @code{end}
12635 @item
12636 @code{for}
12637 @item
12638 @code{is}
12639 @item
12640 @code{limited}
12641 @item
12642 @code{null}
12643 @item
12644 @code{others}
12645 @item
12646 @code{package}
12647 @item
12648 @code{renames}
12649 @item
12650 @code{type}
12651 @item
12652 @code{use}
12653 @item
12654 @code{when}
12655 @item
12656 @code{with}
12657 @end itemize
12658
12659 @noindent
12660 Comments in project files have the same syntax as in Ada, two consecutive
12661 hyphens through the end of the line.
12662
12663 @node Qualified Projects
12664 @subsection Qualified Projects
12665
12666 @noindent
12667 Before the reserved @code{project}, there may be one or two "qualifiers", that
12668 is identifiers or other reserved words, to qualify the project.
12669
12670 The current list of qualifiers is:
12671
12672 @itemize @bullet
12673 @item
12674 @code{abstract}: qualify a project with no sources. A qualified abstract
12675 project must either have no declaration of attributes @code{Source_Dirs},
12676 @code{Source_Files}, @code{Languages} or @code{Source_List_File}, or one of
12677 @code{Source_Dirs}, @code{Source_Files}, or @code{Languages} must be declared
12678 as empty. If it extends another project, the project it extends must also be a
12679 qualified abstract project.
12680
12681 @item
12682 @code{standard}: a standard project is a non library project with sources.
12683
12684 @item
12685 @code{aggregate}: for future extension
12686
12687 @item
12688 @code{aggregate library}: for future extension
12689
12690 @item
12691 @code{library}: a library project must declare both attributes
12692 @code{Library_Name} and @code{Library_Dir}.
12693
12694 @item
12695 @code{configuration}: a configuration project cannot be in a project tree.
12696 @end itemize
12697
12698 @node Packages
12699 @subsection Packages
12700
12701 @noindent
12702 A project file may contain @emph{packages}. The name of a package must be one
12703 of the identifiers from the following list. A package
12704 with a given name may only appear once in a project file. Package names are
12705 case insensitive. The following package names are legal:
12706
12707 @itemize @bullet
12708 @item
12709 @code{Naming}
12710 @item
12711 @code{Builder}
12712 @item
12713 @code{Compiler}
12714 @item
12715 @code{Binder}
12716 @item
12717 @code{Linker}
12718 @item
12719 @code{Finder}
12720 @item
12721 @code{Cross_Reference}
12722 @item
12723 @code{Check}
12724 @item
12725 @code{Eliminate}
12726 @item
12727 @code{Pretty_Printer}
12728 @item
12729 @code{Metrics}
12730 @item
12731 @code{gnatls}
12732 @item
12733 @code{gnatstub}
12734 @item
12735 @code{IDE}
12736 @item
12737 @code{Language_Processing}
12738 @end itemize
12739
12740 @noindent
12741 In its simplest form, a package may be empty:
12742
12743 @smallexample @c projectfile
12744 @group
12745 project Simple is
12746   package Builder is
12747   end Builder;
12748 end Simple;
12749 @end group
12750 @end smallexample
12751
12752 @noindent
12753 A package may contain @emph{attribute declarations},
12754 @emph{variable declarations} and @emph{case constructions}, as will be
12755 described below.
12756
12757 When there is ambiguity between a project name and a package name,
12758 the name always designates the project. To avoid possible confusion, it is
12759 always a good idea to avoid naming a project with one of the
12760 names allowed for packages or any name that starts with @code{gnat}.
12761
12762 @node Expressions
12763 @subsection Expressions
12764
12765 @noindent
12766 An @emph{expression} is either a @emph{string expression} or a
12767 @emph{string list expression}.
12768
12769 A @emph{string expression} is either a @emph{simple string expression} or a
12770 @emph{compound string expression}.
12771
12772 A @emph{simple string expression} is one of the following:
12773 @itemize @bullet
12774 @item A literal string; e.g.@: @code{"comm/my_proj.gpr"}
12775 @item A string-valued variable reference (@pxref{Variables})
12776 @item A string-valued attribute reference (@pxref{Attributes})
12777 @item An external reference (@pxref{External References in Project Files})
12778 @end itemize
12779
12780 @noindent
12781 A @emph{compound string expression} is a concatenation of string expressions,
12782 using the operator @code{"&"}
12783 @smallexample
12784        Path & "/" & File_Name & ".ads"
12785 @end smallexample
12786
12787 @noindent
12788 A @emph{string list expression} is either a
12789 @emph{simple string list expression} or a
12790 @emph{compound string list expression}.
12791
12792 A @emph{simple string list expression} is one of the following:
12793 @itemize @bullet
12794 @item A parenthesized list of zero or more string expressions,
12795 separated by commas
12796 @smallexample
12797    File_Names := (File_Name, "gnat.adc", File_Name & ".orig");
12798    Empty_List := ();
12799 @end smallexample
12800 @item A string list-valued variable reference
12801 @item A string list-valued attribute reference
12802 @end itemize
12803
12804 @noindent
12805 A @emph{compound string list expression} is the concatenation (using
12806 @code{"&"}) of a simple string list expression and an expression.  Note that
12807 each term in a compound string list expression, except the first, may be
12808 either a string expression or a string list expression.
12809
12810 @smallexample @c projectfile
12811 @group
12812    File_Name_List := () & File_Name; --  One string in this list
12813    Extended_File_Name_List := File_Name_List & (File_Name & ".orig");
12814    --  Two strings
12815    Big_List := File_Name_List & Extended_File_Name_List;
12816    --  Concatenation of two string lists: three strings
12817    Illegal_List := "gnat.adc" & Extended_File_Name_List;
12818    --  Illegal: must start with a string list
12819 @end group
12820 @end smallexample
12821
12822 @node String Types
12823 @subsection String Types
12824
12825 @noindent
12826 A @emph{string type declaration} introduces a discrete set of string literals.
12827 If a string variable is declared to have this type, its value
12828 is restricted to the given set of literals.
12829
12830 Here is an example of a string type declaration:
12831
12832 @smallexample @c projectfile
12833    type OS is ("NT", "nt", "Unix", "GNU/Linux", "other OS");
12834 @end smallexample
12835
12836 @noindent
12837 Variables of a string type are called @emph{typed variables}; all other
12838 variables are called @emph{untyped variables}. Typed variables are
12839 particularly useful in @code{case} constructions, to support conditional
12840 attribute declarations.
12841 (@pxref{case Constructions}).
12842
12843 The string literals in the list are case sensitive and must all be different.
12844 They may include any graphic characters allowed in Ada, including spaces.
12845
12846 A string type may only be declared at the project level, not inside a package.
12847
12848 A string type may be referenced by its name if it has been declared in the same
12849 project file, or by an expanded name whose prefix is the name of the project
12850 in which it is declared.
12851
12852 @node Variables
12853 @subsection Variables
12854
12855 @noindent
12856 A variable may be declared at the project file level, or within a package.
12857 Here are some examples of variable declarations:
12858
12859 @smallexample @c projectfile
12860 @group
12861    This_OS : OS := external ("OS"); --  a typed variable declaration
12862    That_OS := "GNU/Linux";          --  an untyped variable declaration
12863 @end group
12864 @end smallexample
12865
12866 @noindent
12867 The syntax of a @emph{typed variable declaration} is identical to the Ada
12868 syntax for an object declaration. By contrast, the syntax of an untyped
12869 variable declaration is identical to an Ada assignment statement. In fact,
12870 variable declarations in project files have some of the characteristics of
12871 an assignment, in that successive declarations for the same variable are
12872 allowed. Untyped variable declarations do establish the expected kind of the
12873 variable (string or string list), and successive declarations for it must
12874 respect the initial kind.
12875
12876 @noindent
12877 A string variable declaration (typed or untyped) declares a variable
12878 whose value is a string. This variable may be used as a string expression.
12879 @smallexample @c projectfile
12880    File_Name       := "readme.txt";
12881    Saved_File_Name := File_Name & ".saved";
12882 @end smallexample
12883
12884 @noindent
12885 A string list variable declaration declares a variable whose value is a list
12886 of strings. The list may contain any number (zero or more) of strings.
12887
12888 @smallexample @c projectfile
12889    Empty_List := ();
12890    List_With_One_Element := ("^-gnaty^-gnaty^");
12891    List_With_Two_Elements := List_With_One_Element & "^-gnatg^-gnatg^";
12892    Long_List := ("main.ada", "pack1_.ada", "pack1.ada", "pack2_.ada"
12893                  "pack2.ada", "util_.ada", "util.ada");
12894 @end smallexample
12895
12896 @noindent
12897 The same typed variable may not be declared more than once at project level,
12898 and it may not be declared more than once in any package; it is in effect
12899 a constant.
12900
12901 The same untyped variable may be declared several times. Declarations are
12902 elaborated in the order in which they appear, so  the new value replaces
12903 the old one, and any subsequent reference to the variable uses the new value.
12904 However, as noted above, if a variable has been declared as a string, all
12905 subsequent
12906 declarations must give it a string value. Similarly, if a variable has
12907 been declared as a string list, all subsequent declarations
12908 must give it a string list value.
12909
12910 A @emph{variable reference} may take several forms:
12911
12912 @itemize @bullet
12913 @item The simple variable name, for a variable in the current package (if any)
12914 or in the current project
12915 @item An expanded name, whose prefix is a context name.
12916 @end itemize
12917
12918 @noindent
12919 A @emph{context} may be one of the following:
12920
12921 @itemize @bullet
12922 @item The name of an existing package in the current project
12923 @item The name of an imported project of the current project
12924 @item The name of an ancestor project (i.e., a project extended by the current
12925 project, either directly or indirectly)
12926 @item An expanded name whose prefix is an imported/parent project name, and
12927 whose selector is a package name in that project.
12928 @end itemize
12929
12930 @noindent
12931 A variable reference may be used in an expression.
12932
12933 @node Attributes
12934 @subsection Attributes
12935
12936 @noindent
12937 A project (and its packages) may have @emph{attributes} that define
12938 the project's properties.  Some attributes have values that are strings;
12939 others have values that are string lists.
12940
12941 There are two categories of attributes: @emph{simple attributes}
12942 and @emph{associative arrays} (@pxref{Associative Array Attributes}).
12943
12944 Legal project attribute names, and attribute names for each legal package are
12945 listed below. Attributes names are case-insensitive.
12946
12947 The following attributes are defined on projects (all are simple attributes):
12948
12949 @multitable @columnfractions .4 .3
12950 @item @emph{Attribute Name}
12951 @tab @emph{Value}
12952 @item @code{Source_Files}
12953 @tab string list
12954 @item @code{Source_Dirs}
12955 @tab string list
12956 @item @code{Source_List_File}
12957 @tab string
12958 @item @code{Object_Dir}
12959 @tab string
12960 @item @code{Exec_Dir}
12961 @tab string
12962 @item @code{Excluded_Source_Dirs}
12963 @tab string list
12964 @item @code{Excluded_Source_Files}
12965 @tab string list
12966 @item @code{Excluded_Source_List_File}
12967 @tab string
12968 @item @code{Languages}
12969 @tab string list
12970 @item @code{Main}
12971 @tab string list
12972 @item @code{Library_Dir}
12973 @tab string
12974 @item @code{Library_Name}
12975 @tab string
12976 @item @code{Library_Kind}
12977 @tab string
12978 @item @code{Library_Version}
12979 @tab string
12980 @item @code{Library_Interface}
12981 @tab string
12982 @item @code{Library_Auto_Init}
12983 @tab string
12984 @item @code{Library_Options}
12985 @tab string list
12986 @item @code{Library_Src_Dir}
12987 @tab string
12988 @item @code{Library_ALI_Dir}
12989 @tab string
12990 @item @code{Library_GCC}
12991 @tab string
12992 @item @code{Library_Symbol_File}
12993 @tab string
12994 @item @code{Library_Symbol_Policy}
12995 @tab string
12996 @item @code{Library_Reference_Symbol_File}
12997 @tab string
12998 @item @code{Externally_Built}
12999 @tab string
13000 @end multitable
13001
13002 @noindent
13003 The following attributes are defined for package  @code{Naming}
13004 (@pxref{Naming Schemes}):
13005
13006 @multitable @columnfractions .4 .2 .2 .2
13007 @item Attribute Name @tab Category @tab Index @tab Value
13008 @item @code{Spec_Suffix}
13009 @tab associative array
13010 @tab language name
13011 @tab string
13012 @item @code{Body_Suffix}
13013 @tab associative array
13014 @tab language name
13015 @tab string
13016 @item @code{Separate_Suffix}
13017 @tab simple attribute
13018 @tab n/a
13019 @tab string
13020 @item @code{Casing}
13021 @tab simple attribute
13022 @tab n/a
13023 @tab string
13024 @item @code{Dot_Replacement}
13025 @tab simple attribute
13026 @tab n/a
13027 @tab string
13028 @item @code{Spec}
13029 @tab associative array
13030 @tab Ada unit name
13031 @tab string
13032 @item @code{Body}
13033 @tab associative array
13034 @tab Ada unit name
13035 @tab string
13036 @item @code{Specification_Exceptions}
13037 @tab associative array
13038 @tab language name
13039 @tab string list
13040 @item @code{Implementation_Exceptions}
13041 @tab associative array
13042 @tab language name
13043 @tab string list
13044 @end multitable
13045
13046 @noindent
13047 The following attributes are defined for packages @code{Builder},
13048 @code{Compiler}, @code{Binder},
13049 @code{Linker}, @code{Cross_Reference}, and @code{Finder}
13050 (@pxref{^Switches^Switches^ and Project Files}).
13051
13052 @multitable @columnfractions .4 .2 .2 .2
13053 @item Attribute Name @tab Category @tab Index @tab Value
13054 @item @code{^Default_Switches^Default_Switches^}
13055 @tab associative array
13056 @tab language name
13057 @tab string list
13058 @item @code{^Switches^Switches^}
13059 @tab associative array
13060 @tab file name
13061 @tab string list
13062 @end multitable
13063
13064 @noindent
13065 In addition, package @code{Compiler} has a single string attribute
13066 @code{Local_Configuration_Pragmas} and package @code{Builder} has a single
13067 string attribute @code{Global_Configuration_Pragmas}.
13068
13069 @noindent
13070 Each simple attribute has a default value: the empty string (for string-valued
13071 attributes) and the empty list (for string list-valued attributes).
13072
13073 An attribute declaration defines a new value for an attribute.
13074
13075 Examples of simple attribute declarations:
13076
13077 @smallexample @c projectfile
13078    for Object_Dir use "objects";
13079    for Source_Dirs use ("units", "test/drivers");
13080 @end smallexample
13081
13082 @noindent
13083 The syntax of a @dfn{simple attribute declaration} is similar to that of an
13084 attribute definition clause in Ada.
13085
13086 Attributes references may be appear in expressions.
13087 The general form for such a reference is @code{<entity>'<attribute>}:
13088 Associative array attributes are functions. Associative
13089 array attribute references must have an argument that is a string literal.
13090
13091 Examples are:
13092
13093 @smallexample @c projectfile
13094   project'Object_Dir
13095   Naming'Dot_Replacement
13096   Imported_Project'Source_Dirs
13097   Imported_Project.Naming'Casing
13098   Builder'^Default_Switches^Default_Switches^("Ada")
13099 @end smallexample
13100
13101 @noindent
13102 The prefix of an attribute may be:
13103 @itemize @bullet
13104 @item @code{project} for an attribute of the current project
13105 @item The name of an existing package of the current project
13106 @item The name of an imported project
13107 @item The name of a parent project that is extended by the current project
13108 @item An expanded name whose prefix is imported/parent project name,
13109 and whose selector is a package name
13110 @end itemize
13111
13112 @noindent
13113 Example:
13114 @smallexample @c projectfile
13115 @group
13116    project Prj is
13117      for Source_Dirs use project'Source_Dirs & "units";
13118      for Source_Dirs use project'Source_Dirs & "test/drivers"
13119    end Prj;
13120 @end group
13121 @end smallexample
13122
13123 @noindent
13124 In the first attribute declaration, initially the attribute @code{Source_Dirs}
13125 has the default value: an empty string list. After this declaration,
13126 @code{Source_Dirs} is a string list of one element: @code{"units"}.
13127 After the second attribute declaration @code{Source_Dirs} is a string list of
13128 two elements: @code{"units"} and @code{"test/drivers"}.
13129
13130 Note: this example is for illustration only. In practice,
13131 the project file would contain only one attribute declaration:
13132
13133 @smallexample @c projectfile
13134    for Source_Dirs use ("units", "test/drivers");
13135 @end smallexample
13136
13137 @node Associative Array Attributes
13138 @subsection Associative Array Attributes
13139
13140 @noindent
13141 Some attributes are defined as @emph{associative arrays}. An associative
13142 array may be regarded as a function that takes a string as a parameter
13143 and delivers a string or string list value as its result.
13144
13145 Here are some examples of single associative array attribute associations:
13146
13147 @smallexample @c projectfile
13148    for Body ("main") use "Main.ada";
13149    for ^Switches^Switches^ ("main.ada")
13150        use ("^-v^-v^",
13151             "^-gnatv^-gnatv^");
13152    for ^Switches^Switches^ ("main.ada")
13153             use Builder'^Switches^Switches^ ("main.ada")
13154               & "^-g^-g^";
13155 @end smallexample
13156
13157 @noindent
13158 Like untyped variables and simple attributes, associative array attributes
13159 may be declared several times. Each declaration supplies a new value for the
13160 attribute, and replaces the previous setting.
13161
13162 @noindent
13163 An associative array attribute may be declared as a full associative array
13164 declaration, with the value of the same attribute in an imported or extended
13165 project.
13166
13167 @smallexample @c projectfile
13168    package Builder is
13169       for Default_Switches use Default.Builder'Default_Switches;
13170    end Builder;
13171 @end smallexample
13172
13173 @noindent
13174 In this example, @code{Default} must be either a project imported by the
13175 current project, or the project that the current project extends. If the
13176 attribute is in a package (in this case, in package @code{Builder}), the same
13177 package needs to be specified.
13178
13179 @noindent
13180 A full associative array declaration replaces any other declaration for the
13181 attribute, including other full associative array declaration. Single
13182 associative array associations may be declare after a full associative
13183 declaration, modifying the value for a single association of the attribute.
13184
13185 @node case Constructions
13186 @subsection @code{case} Constructions
13187
13188 @noindent
13189 A @code{case} construction is used in a project file to effect conditional
13190 behavior.
13191 Here is a typical example:
13192
13193 @smallexample @c projectfile
13194 @group
13195 project MyProj is
13196    type OS_Type is ("GNU/Linux", "Unix", "NT", "VMS");
13197
13198    OS : OS_Type := external ("OS", "GNU/Linux");
13199 @end group
13200
13201 @group
13202    package Compiler is
13203      case OS is
13204        when "GNU/Linux" | "Unix" =>
13205          for ^Default_Switches^Default_Switches^ ("Ada")
13206              use ("^-gnath^-gnath^");
13207        when "NT" =>
13208          for ^Default_Switches^Default_Switches^ ("Ada")
13209              use ("^-gnatP^-gnatP^");
13210        when others =>
13211      end case;
13212    end Compiler;
13213 end MyProj;
13214 @end group
13215 @end smallexample
13216
13217 @noindent
13218 The syntax of a @code{case} construction is based on the Ada case statement
13219 (although there is no @code{null} construction for empty alternatives).
13220
13221 The case expression must be a typed string variable.
13222 Each alternative comprises the reserved word @code{when}, either a list of
13223 literal strings separated by the @code{"|"} character or the reserved word
13224 @code{others},  and the @code{"=>"} token.
13225 Each literal string must belong to the string type that is the type of the
13226 case variable.
13227 An @code{others} alternative, if present, must occur last.
13228
13229 After each @code{=>}, there are zero or more constructions.  The only
13230 constructions allowed in a case construction are other case constructions,
13231 attribute declarations and variable declarations. String type declarations and
13232 package declarations are not allowed. Variable declarations are restricted to
13233 variables that have already been declared before the case construction.
13234
13235 The value of the case variable is often given by an external reference
13236 (@pxref{External References in Project Files}).
13237
13238 @c ****************************************
13239 @c * Objects and Sources in Project Files *
13240 @c ****************************************
13241
13242 @node Objects and Sources in Project Files
13243 @section Objects and Sources in Project Files
13244
13245 @menu
13246 * Object Directory::
13247 * Exec Directory::
13248 * Source Directories::
13249 * Source File Names::
13250 @end menu
13251
13252 @noindent
13253 Each project has exactly one object directory and one or more source
13254 directories. The source directories must contain at least one source file,
13255 unless  the project file explicitly specifies that no source files are present
13256 (@pxref{Source File Names}).
13257
13258 @node Object Directory
13259 @subsection Object Directory
13260
13261 @noindent
13262 The object directory for a project is the directory containing the compiler's
13263 output (such as @file{ALI} files and object files) for the project's immediate
13264 sources.
13265
13266 The object directory is given by the value of the attribute @code{Object_Dir}
13267 in the project file.
13268
13269 @smallexample @c projectfile
13270    for Object_Dir use "objects";
13271 @end smallexample
13272
13273 @noindent
13274 The attribute @code{Object_Dir} has a string value, the path name of the object
13275 directory. The path name may be absolute or relative to the directory of the
13276 project file. This directory must already exist, and be readable and writable.
13277
13278 By default, when the attribute @code{Object_Dir} is not given an explicit value
13279 or when its value is the empty string, the object directory is the same as the
13280 directory containing the project file.
13281
13282 @node Exec Directory
13283 @subsection Exec Directory
13284
13285 @noindent
13286 The exec directory for a project is the directory containing the executables
13287 for the project's main subprograms.
13288
13289 The exec directory is given by the value of the attribute @code{Exec_Dir}
13290 in the project file.
13291
13292 @smallexample @c projectfile
13293    for Exec_Dir use "executables";
13294 @end smallexample
13295
13296 @noindent
13297 The attribute @code{Exec_Dir} has a string value, the path name of the exec
13298 directory. The path name may be absolute or relative to the directory of the
13299 project file. This directory must already exist, and be writable.
13300
13301 By default, when the attribute @code{Exec_Dir} is not given an explicit value
13302 or when its value is the empty string, the exec directory is the same as the
13303 object directory of the project file.
13304
13305 @node Source Directories
13306 @subsection Source Directories
13307
13308 @noindent
13309 The source directories of a project are specified by the project file
13310 attribute @code{Source_Dirs}.
13311
13312 This attribute's value is a string list. If the attribute is not given an
13313 explicit value, then there is only one source directory, the one where the
13314 project file resides.
13315
13316 A @code{Source_Dirs} attribute that is explicitly defined to be the empty list,
13317 as in
13318
13319 @smallexample @c projectfile
13320     for Source_Dirs use ();
13321 @end smallexample
13322
13323 @noindent
13324 indicates that the project contains no source files.
13325
13326 Otherwise, each string in the string list designates one or more
13327 source directories.
13328
13329 @smallexample @c projectfile
13330    for Source_Dirs use ("sources", "test/drivers");
13331 @end smallexample
13332
13333 @noindent
13334 If a string in the list ends with @code{"/**"},  then the directory whose path
13335 name precedes the two asterisks, as well as all its subdirectories
13336 (recursively), are source directories.
13337
13338 @smallexample @c projectfile
13339    for Source_Dirs use ("/system/sources/**");
13340 @end smallexample
13341
13342 @noindent
13343 Here the directory @code{/system/sources} and all of its subdirectories
13344 (recursively) are source directories.
13345
13346 To specify that the source directories are the directory of the project file
13347 and all of its subdirectories, you can declare @code{Source_Dirs} as follows:
13348 @smallexample @c projectfile
13349    for Source_Dirs use ("./**");
13350 @end smallexample
13351
13352 @noindent
13353 Each of the source directories must exist and be readable.
13354
13355 @node Source File Names
13356 @subsection Source File Names
13357
13358 @noindent
13359 In a project that contains source files, their names may be specified by the
13360 attributes @code{Source_Files} (a string list) or @code{Source_List_File}
13361 (a string). Source file names never include any directory information.
13362
13363 If the attribute @code{Source_Files} is given an explicit value, then each
13364 element of the list is a source file name.
13365
13366 @smallexample @c projectfile
13367    for Source_Files use ("main.adb");
13368    for Source_Files use ("main.adb", "pack1.ads", "pack2.adb");
13369 @end smallexample
13370
13371 @noindent
13372 If the attribute @code{Source_Files} is not given an explicit value,
13373 but the attribute @code{Source_List_File} is given a string value,
13374 then the source file names are contained in the text file whose path name
13375 (absolute or relative to the directory of the project file) is the
13376 value of the attribute @code{Source_List_File}.
13377
13378 Each line in the file that is not empty or is not a comment
13379 contains a source file name.
13380
13381 @smallexample @c projectfile
13382    for Source_List_File use "source_list.txt";
13383 @end smallexample
13384
13385 @noindent
13386 By default, if neither the attribute @code{Source_Files} nor the attribute
13387 @code{Source_List_File} is given an explicit value, then each file in the
13388 source directories that conforms to the project's naming scheme
13389 (@pxref{Naming Schemes}) is an immediate source of the project.
13390
13391 A warning is issued if both attributes @code{Source_Files} and
13392 @code{Source_List_File} are given explicit values. In this case, the attribute
13393 @code{Source_Files} prevails.
13394
13395 Each source file name must be the name of one existing source file
13396 in one of the source directories.
13397
13398 A @code{Source_Files} attribute whose value is an empty list
13399 indicates that there are no source files in the project.
13400
13401 If the order of the source directories is known statically, that is if
13402 @code{"/**"} is not used in the string list @code{Source_Dirs}, then there may
13403 be several files with the same source file name. In this case, only the file
13404 in the first directory is considered as an immediate source of the project
13405 file. If the order of the source directories is not known statically, it is
13406 an error to have several files with the same source file name.
13407
13408 Projects can be specified to have no Ada source
13409 files: the value of @code{Source_Dirs} or @code{Source_Files} may be an empty
13410 list, or the @code{"Ada"} may be absent from @code{Languages}:
13411
13412 @smallexample @c projectfile
13413    for Source_Dirs use ();
13414    for Source_Files use ();
13415    for Languages use ("C", "C++");
13416 @end smallexample
13417
13418 @noindent
13419 Otherwise, a project must contain at least one immediate source.
13420
13421 Projects with no source files are useful as template packages
13422 (@pxref{Packages in Project Files}) for other projects; in particular to
13423 define a package @code{Naming} (@pxref{Naming Schemes}).
13424
13425 @c ****************************
13426 @c * Importing Projects *
13427 @c ****************************
13428
13429 @node  Importing Projects
13430 @section Importing Projects
13431 @cindex @code{ADA_PROJECT_PATH}
13432 @cindex @code{GPR_PROJECT_PATH}
13433
13434 @noindent
13435 An immediate source of a project P may depend on source files that
13436 are neither immediate sources of P nor in the predefined library.
13437 To get this effect, P must @emph{import} the projects that contain the needed
13438 source files.
13439
13440 @smallexample @c projectfile
13441 @group
13442   with "project1", "utilities.gpr";
13443   with "/namings/apex.gpr";
13444   project Main is
13445     @dots{}
13446 @end group
13447 @end smallexample
13448
13449 @noindent
13450 As can be seen in this example, the syntax for importing projects is similar
13451 to the syntax for importing compilation units in Ada. However, project files
13452 use literal strings instead of names, and the @code{with} clause identifies
13453 project files rather than packages.
13454
13455 Each literal string is the file name or path name (absolute or relative) of a
13456 project file. If a string corresponds to a file name, with no path or a
13457 relative path, then its location is determined by the @emph{project path}. The
13458 latter can be queried using @code{gnatls -v}. It contains:
13459
13460 @itemize @bullet
13461 @item
13462 In first position, the directory containing the current project file.
13463 @item
13464 In last position, the default project directory. This default project directory
13465 is part of the GNAT installation and is the standard place to install project
13466 files giving access to standard support libraries.
13467 @ifclear vms
13468 @ref{Installing a library}
13469 @end ifclear
13470
13471 @item
13472 In between, all the directories referenced in the
13473 ^environment variables^logical names^ @env{GPR_PROJECT_PATH}
13474 and @env{ADA_PROJECT_PATH} if they exist, and in that order.
13475 @end itemize
13476
13477 @noindent
13478 If a relative pathname is used, as in
13479
13480 @smallexample @c projectfile
13481   with "tests/proj";
13482 @end smallexample
13483
13484 @noindent
13485 then the full path for the project is constructed by concatenating this
13486 relative path to those in the project path, in order, until a matching file is
13487 found. Any symbolic link will be fully resolved in the directory of the
13488 importing project file before the imported project file is examined.
13489
13490 If the @code{with}'ed project file name does not have an extension,
13491 the default is @file{^.gpr^.GPR^}. If a file with this extension is not found,
13492 then the file name as specified in the @code{with} clause (no extension) will
13493 be used. In the above example, if a file @code{project1.gpr} is found, then it
13494 will be used; otherwise, if a file @code{^project1^PROJECT1^} exists
13495 then it will be used; if neither file exists, this is an error.
13496
13497 A warning is issued if the name of the project file does not match the
13498 name of the project; this check is case insensitive.
13499
13500 Any source file that is an immediate source of the imported project can be
13501 used by the immediate sources of the importing project, transitively. Thus
13502 if @code{A} imports @code{B}, and @code{B} imports @code{C}, the immediate
13503 sources of @code{A} may depend on the immediate sources of @code{C}, even if
13504 @code{A} does not import @code{C} explicitly. However, this is not recommended,
13505 because if and when @code{B} ceases to import @code{C}, some sources in
13506 @code{A} will no longer compile.
13507
13508 A side effect of this capability is that normally cyclic dependencies are not
13509 permitted: if @code{A} imports @code{B} (directly or indirectly) then @code{B}
13510 is not allowed to import @code{A}. However, there are cases when cyclic
13511 dependencies would be beneficial. For these cases, another form of import
13512 between projects exists, the @code{limited with}: a project @code{A} that
13513 imports a project @code{B} with a straight @code{with} may also be imported,
13514 directly or indirectly, by @code{B} on the condition that imports from @code{B}
13515 to @code{A} include at least one @code{limited with}.
13516
13517 @smallexample @c 0projectfile
13518 with "../b/b.gpr";
13519 with "../c/c.gpr";
13520 project A is
13521 end A;
13522
13523 limited with "../a/a.gpr";
13524 project B is
13525 end B;
13526
13527 with "../d/d.gpr";
13528 project C is
13529 end C;
13530
13531 limited with "../a/a.gpr";
13532 project D is
13533 end D;
13534 @end smallexample
13535
13536 @noindent
13537 In the above legal example, there are two project cycles:
13538 @itemize @bullet
13539 @item A-> B-> A
13540 @item A -> C -> D -> A
13541 @end itemize
13542
13543 @noindent
13544 In each of these cycle there is one @code{limited with}: import of @code{A}
13545 from @code{B} and import of @code{A} from @code{D}.
13546
13547 The difference between straight @code{with} and @code{limited with} is that
13548 the name of a project imported with a @code{limited with} cannot be used in the
13549 project that imports it. In particular, its packages cannot be renamed and
13550 its variables cannot be referred to.
13551
13552 An exception to the above rules for @code{limited with} is that for the main
13553 project specified to @command{gnatmake} or to the @command{GNAT} driver a
13554 @code{limited with} is equivalent to a straight @code{with}. For example,
13555 in the example above, projects @code{B} and @code{D} could not be main
13556 projects for @command{gnatmake} or to the @command{GNAT} driver, because they
13557 each have a @code{limited with} that is the only one in a cycle of importing
13558 projects.
13559
13560 @c *********************
13561 @c * Project Extension *
13562 @c *********************
13563
13564 @node Project Extension
13565 @section Project Extension
13566
13567 @noindent
13568 During development of a large system, it is sometimes necessary to use
13569 modified versions of some of the source files, without changing the original
13570 sources. This can be achieved through the @emph{project extension} facility.
13571
13572 @smallexample @c projectfile
13573    project Modified_Utilities extends "/baseline/utilities.gpr" is @dots{}
13574 @end smallexample
13575
13576 @noindent
13577 A project extension declaration introduces an extending project
13578 (the @emph{child}) and a project being extended (the @emph{parent}).
13579
13580 By default, a child project inherits all the sources of its parent.
13581 However, inherited sources can be overridden: a unit in a parent is hidden
13582 by a unit of the same name in the child.
13583
13584 Inherited sources are considered to be sources (but not immediate sources)
13585 of the child project; see @ref{Project File Syntax}.
13586
13587 An inherited source file retains any switches specified in the parent project.
13588
13589 For example if the project @code{Utilities} contains the spec and the
13590 body of an Ada package @code{Util_IO}, then the project
13591 @code{Modified_Utilities} can contain a new body for package @code{Util_IO}.
13592 The original body of @code{Util_IO} will not be considered in program builds.
13593 However, the package spec will still be found in the project
13594 @code{Utilities}.
13595
13596 A child project can have only one parent, except when it is qualified as
13597 abstract. But it may import any number of other projects.
13598
13599 A project is not allowed to import directly or indirectly at the same time a
13600 child project and any of its ancestors.
13601
13602 @c *******************************
13603 @c * Project Hierarchy Extension *
13604 @c *******************************
13605
13606 @node Project Hierarchy Extension
13607 @section Project Hierarchy Extension
13608
13609 @noindent
13610 When extending a large system spanning multiple projects, it is often
13611 inconvenient to extend every project in the hierarchy that is impacted by a
13612 small change introduced. In such cases, it is possible to create a virtual
13613 extension of entire hierarchy using @code{extends all} relationship.
13614
13615 When the project is extended using @code{extends all} inheritance, all projects
13616 that are imported by it, both directly and indirectly, are considered virtually
13617 extended. That is, the Project Manager creates "virtual projects"
13618 that extend every project in the hierarchy; all these virtual projects have
13619 no sources of their own and have as object directory the object directory of
13620 the root of "extending all" project.
13621
13622 It is possible to explicitly extend one or more projects in the hierarchy
13623 in order to modify the sources. These extending projects must be imported by
13624 the "extending all" project, which will replace the corresponding virtual
13625 projects with the explicit ones.
13626
13627 When building such a project hierarchy extension, the Project Manager will
13628 ensure that both modified sources and sources in virtual extending projects
13629 that depend on them, are recompiled.
13630
13631 By means of example, consider the following hierarchy of projects.
13632
13633 @enumerate
13634 @item
13635 project A, containing package P1
13636 @item
13637 project B importing A and containing package P2 which depends on P1
13638 @item
13639 project C importing B and containing package P3 which depends on P2
13640 @end enumerate
13641
13642 @noindent
13643 We want to modify packages P1 and P3.
13644
13645 This project hierarchy will need to be extended as follows:
13646
13647 @enumerate
13648 @item
13649 Create project A1 that extends A, placing modified P1 there:
13650
13651 @smallexample @c 0projectfile
13652 project A1 extends "(@dots{})/A" is
13653 end A1;
13654 @end smallexample
13655
13656 @item
13657 Create project C1 that "extends all" C and imports A1, placing modified
13658 P3 there:
13659
13660 @smallexample @c 0projectfile
13661 with "(@dots{})/A1";
13662 project C1 extends all "(@dots{})/C" is
13663 end C1;
13664 @end smallexample
13665 @end enumerate
13666
13667 When you build project C1, your entire modified project space will be
13668 recompiled, including the virtual project B1 that has been impacted by the
13669 "extending all" inheritance of project C.
13670
13671 Note that if a Library Project in the hierarchy is virtually extended,
13672 the virtual project that extends the Library Project is not a Library Project.
13673
13674 @c ****************************************
13675 @c * External References in Project Files *
13676 @c ****************************************
13677
13678 @node  External References in Project Files
13679 @section External References in Project Files
13680
13681 @noindent
13682 A project file may contain references to external variables; such references
13683 are called @emph{external references}.
13684
13685 An external variable is either defined as part of the environment (an
13686 environment variable in Unix, for example) or else specified on the command
13687 line via the @option{^-X^/EXTERNAL_REFERENCE=^@emph{vbl}=@emph{value}} switch.
13688 If both, then the command line value is used.
13689
13690 The value of an external reference is obtained by means of the built-in
13691 function @code{external}, which returns a string value.
13692 This function has two forms:
13693 @itemize @bullet
13694 @item @code{external (external_variable_name)}
13695 @item @code{external (external_variable_name, default_value)}
13696 @end itemize
13697
13698 @noindent
13699 Each parameter must be a string literal.  For example:
13700
13701 @smallexample @c projectfile
13702    external ("USER")
13703    external ("OS", "GNU/Linux")
13704 @end smallexample
13705
13706 @noindent
13707 In the form with one parameter, the function returns the value of
13708 the external variable given as parameter. If this name is not present in the
13709 environment, the function returns an empty string.
13710
13711 In the form with two string parameters, the second argument is
13712 the value returned when the variable given as the first argument is not
13713 present in the environment. In the example above, if @code{"OS"} is not
13714 the name of ^an environment variable^a logical name^ and is not passed on
13715 the command line, then the returned value is @code{"GNU/Linux"}.
13716
13717 An external reference may be part of a string expression or of a string
13718 list expression, and can therefore appear in a variable declaration or
13719 an attribute declaration.
13720
13721 @smallexample @c projectfile
13722 @group
13723    type Mode_Type is ("Debug", "Release");
13724    Mode : Mode_Type := external ("MODE");
13725    case Mode is
13726      when "Debug" =>
13727         @dots{}
13728 @end group
13729 @end smallexample
13730
13731 @c *****************************
13732 @c * Packages in Project Files *
13733 @c *****************************
13734
13735 @node  Packages in Project Files
13736 @section Packages in Project Files
13737
13738 @noindent
13739 A @emph{package} defines the settings for project-aware tools within a
13740 project.
13741 For each such tool one can declare a package; the names for these
13742 packages are preset (@pxref{Packages}).
13743 A package may contain variable declarations, attribute declarations, and case
13744 constructions.
13745
13746 @smallexample @c projectfile
13747 @group
13748    project Proj is
13749       package Builder is  -- used by gnatmake
13750          for ^Default_Switches^Default_Switches^ ("Ada")
13751              use ("^-v^-v^",
13752                   "^-g^-g^");
13753       end Builder;
13754    end Proj;
13755 @end group
13756 @end smallexample
13757
13758 @noindent
13759 The syntax of package declarations mimics that of package in Ada.
13760
13761 Most of the packages have an attribute
13762 @code{^Default_Switches^Default_Switches^}.
13763 This attribute is an associative array, and its value is a string list.
13764 The index of the associative array is the name of a programming language (case
13765 insensitive). This attribute indicates the ^switch^switch^
13766 or ^switches^switches^ to be used
13767 with the corresponding tool.
13768
13769 Some packages also have another attribute, @code{^Switches^Switches^},
13770 an associative array whose value is a string list.
13771 The index is the name of a source file.
13772 This attribute indicates the ^switch^switch^
13773 or ^switches^switches^ to be used by the corresponding
13774 tool when dealing with this specific file.
13775
13776 Further information on these ^switch^switch^-related attributes is found in
13777 @ref{^Switches^Switches^ and Project Files}.
13778
13779 A package may be declared as a @emph{renaming} of another package; e.g., from
13780 the project file for an imported project.
13781
13782 @smallexample @c projectfile
13783 @group
13784   with "/global/apex.gpr";
13785   project Example is
13786     package Naming renames Apex.Naming;
13787     @dots{}
13788   end Example;
13789 @end group
13790 @end smallexample
13791
13792 @noindent
13793 Packages that are renamed in other project files often come from project files
13794 that have no sources: they are just used as templates. Any modification in the
13795 template will be reflected automatically in all the project files that rename
13796 a package from the template.
13797
13798 In addition to the tool-oriented packages, you can also declare a package
13799 named @code{Naming} to establish specialized source file naming conventions
13800 (@pxref{Naming Schemes}).
13801
13802 @c ************************************
13803 @c * Variables from Imported Projects *
13804 @c ************************************
13805
13806 @node Variables from Imported Projects
13807 @section Variables from Imported Projects
13808
13809 @noindent
13810 An attribute or variable defined in an imported or parent project can
13811 be used in expressions in the importing / extending project.
13812 Such an attribute or variable is denoted by an expanded name whose prefix
13813 is either the name of the project or the expanded name of a package within
13814 a project.
13815
13816 @smallexample @c projectfile
13817 @group
13818   with "imported";
13819   project Main extends "base" is
13820      Var1 := Imported.Var;
13821      Var2 := Base.Var & ".new";
13822 @end group
13823
13824 @group
13825      package Builder is
13826         for ^Default_Switches^Default_Switches^ ("Ada")
13827             use Imported.Builder'Ada_^Switches^Switches^ &
13828                 "^-gnatg^-gnatg^" &
13829                 "^-v^-v^";
13830      end Builder;
13831 @end group
13832
13833 @group
13834      package Compiler is
13835         for ^Default_Switches^Default_Switches^ ("Ada")
13836             use Base.Compiler'Ada_^Switches^Switches^;
13837      end Compiler;
13838   end Main;
13839 @end group
13840 @end smallexample
13841
13842 @noindent
13843 In this example:
13844
13845 @itemize @bullet
13846 @item
13847 The value of @code{Var1} is a copy of the variable @code{Var} defined
13848 in the project file @file{"imported.gpr"}
13849 @item
13850 the value of @code{Var2} is a copy of the value of variable @code{Var}
13851 defined in the project file @file{base.gpr}, concatenated with @code{".new"}
13852 @item
13853 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
13854 @code{Builder} is a string list that includes in its value a copy of the value
13855 of @code{Ada_^Switches^Switches^} defined in the @code{Builder} package
13856 in project file @file{imported.gpr} plus two new elements:
13857 @option{"^-gnatg^-gnatg^"}
13858 and @option{"^-v^-v^"};
13859 @item
13860 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
13861 @code{Compiler} is a copy of the variable @code{Ada_^Switches^Switches^}
13862 defined in the @code{Compiler} package in project file @file{base.gpr},
13863 the project being extended.
13864 @end itemize
13865
13866 @c ******************
13867 @c * Naming Schemes *
13868 @c ******************
13869
13870 @node  Naming Schemes
13871 @section Naming Schemes
13872
13873 @noindent
13874 Sometimes an Ada software system is ported from a foreign compilation
13875 environment to GNAT, and the file names do not use the default GNAT
13876 conventions. Instead of changing all the file names (which for a variety
13877 of reasons might not be possible), you can define the relevant file
13878 naming scheme in the @code{Naming} package in your project file.
13879
13880 @noindent
13881 Note that the use of pragmas described in
13882 @ref{Alternative File Naming Schemes} by mean of a configuration
13883 pragmas file is not supported when using project files. You must use
13884 the features described in this paragraph. You can however use specify
13885 other configuration pragmas (@pxref{Specifying Configuration Pragmas}).
13886
13887 @ifclear vms
13888 For example, the following
13889 package models the Apex file naming rules:
13890
13891 @smallexample @c projectfile
13892 @group
13893   package Naming is
13894     for Casing               use "lowercase";
13895     for Dot_Replacement      use ".";
13896     for Spec_Suffix ("Ada")  use ".1.ada";
13897     for Body_Suffix ("Ada")  use ".2.ada";
13898   end Naming;
13899 @end group
13900 @end smallexample
13901 @end ifclear
13902
13903 @ifset vms
13904 For example, the following package models the HP Ada file naming rules:
13905
13906 @smallexample @c projectfile
13907 @group
13908   package Naming is
13909     for Casing               use "lowercase";
13910     for Dot_Replacement      use "__";
13911     for Spec_Suffix ("Ada")  use "_.^ada^ada^";
13912     for Body_Suffix ("Ada")  use ".^ada^ada^";
13913   end Naming;
13914 @end group
13915 @end smallexample
13916
13917 @noindent
13918 (Note that @code{Casing} is @code{"lowercase"} because GNAT gets the file
13919 names in lower case)
13920 @end ifset
13921
13922 @noindent
13923 You can define the following attributes in package @code{Naming}:
13924
13925 @table @code
13926
13927 @item @code{Casing}
13928 This must be a string with one of the three values @code{"lowercase"},
13929 @code{"uppercase"} or @code{"mixedcase"}; these strings are case insensitive.
13930
13931 @noindent
13932 If @code{Casing} is not specified, then the default is @code{"lowercase"}.
13933
13934 @item @code{Dot_Replacement}
13935 This must be a string whose value satisfies the following conditions:
13936
13937 @itemize @bullet
13938 @item It must not be empty
13939 @item It cannot start or end with an alphanumeric character
13940 @item It cannot be a single underscore
13941 @item It cannot start with an underscore followed by an alphanumeric
13942 @item It cannot contain a dot @code{'.'} except if the entire string
13943 is @code{"."}
13944 @end itemize
13945
13946 @noindent
13947 If @code{Dot_Replacement} is not specified, then the default is @code{"-"}.
13948
13949 @item @code{Spec_Suffix}
13950 This is an associative array (indexed by the programming language name, case
13951 insensitive) whose value is a string that must satisfy the following
13952 conditions:
13953
13954 @itemize @bullet
13955 @item It must not be empty
13956 @item It must include at least one dot
13957 @end itemize
13958 @noindent
13959 If @code{Spec_Suffix ("Ada")} is not specified, then the default is
13960 @code{"^.ads^.ADS^"}.
13961
13962 @item @code{Body_Suffix}
13963 This is an associative array (indexed by the programming language name, case
13964 insensitive) whose value is a string that must satisfy the following
13965 conditions:
13966
13967 @itemize @bullet
13968 @item It must not be empty
13969 @item It must include at least one dot
13970 @item It cannot be the same as @code{Spec_Suffix ("Ada")}
13971 @end itemize
13972 @noindent
13973 If @code{Body_Suffix ("Ada")} and @code{Spec_Suffix ("Ada")} end with the
13974 same string, then a file name that ends with the longest of these two suffixes
13975 will be a body if the longest suffix is @code{Body_Suffix ("Ada")} or a spec
13976 if the longest suffix is @code{Spec_Suffix ("Ada")}.
13977
13978 If the suffix does not start with a '.', a file with a name exactly equal
13979 to the suffix will also be part of the project (for instance if you define
13980 the suffix as @code{Makefile}, a file called @file{Makefile} will be part
13981 of the project. This is not interesting in general when using projects to
13982 compile. However, it might become useful when a project is also used to
13983 find the list of source files in an editor, like the GNAT Programming System
13984 (GPS).
13985
13986 If @code{Body_Suffix ("Ada")} is not specified, then the default is
13987 @code{"^.adb^.ADB^"}.
13988
13989 @item @code{Separate_Suffix}
13990 This must be a string whose value satisfies the same conditions as
13991 @code{Body_Suffix}. The same "longest suffix" rules apply.
13992
13993 @noindent
13994 If @code{Separate_Suffix ("Ada")} is not specified, then it defaults to same
13995 value as @code{Body_Suffix ("Ada")}.
13996
13997 @item @code{Spec}
13998 @noindent
13999 You can use the associative array attribute @code{Spec}  to define
14000 the source file name for an individual Ada compilation unit's spec. The array
14001 index must be a string literal that identifies the Ada unit (case insensitive).
14002 The value of this attribute must be a string that identifies the file that
14003 contains this unit's spec (case sensitive or insensitive depending on the
14004 operating system).
14005
14006 @smallexample @c projectfile
14007    for Spec ("MyPack.MyChild") use "mypack.mychild.spec";
14008 @end smallexample
14009
14010 When the source file contains several units, you can indicate at what
14011 position the unit occurs in the file, with the following. The first unit
14012 in the file has index 1
14013
14014 @smallexample @c projectfile
14015   for Body ("top") use "foo.a" at 1;
14016   for Body ("foo") use "foo.a" at 2;
14017 @end smallexample
14018
14019 @item @code{Body}
14020
14021 You can use the associative array attribute @code{Body} to
14022 define the source file name for an individual Ada compilation unit's body
14023 (possibly a subunit).  The array index must be a string literal that identifies
14024 the Ada unit (case insensitive).  The value of this attribute must be a string
14025 that identifies the file that contains this unit's body or subunit (case
14026 sensitive or insensitive depending on the operating system).
14027
14028 @smallexample @c projectfile
14029    for Body ("MyPack.MyChild") use "mypack.mychild.body";
14030 @end smallexample
14031 @end table
14032
14033 @c ********************
14034 @c * Library Projects *
14035 @c ********************
14036
14037 @node Library Projects
14038 @section Library Projects
14039
14040 @noindent
14041 @emph{Library projects} are projects whose object code is placed in a library.
14042 (Note that this facility is not yet supported on all platforms).
14043
14044 @code{gnatmake} or @code{gprbuild} will collect all object files into a
14045 single archive, which might either be a shared or a static library. This
14046 library can later on be linked with multiple executables, potentially
14047 reducing their sizes.
14048
14049 If your project file specifies languages other than Ada, but you are still
14050 using @code{gnatmake} to compile and link, the latter will not try to
14051 compile your sources other than Ada (you should use @code{gprbuild} if that
14052 is your intent). However, @code{gnatmake} will automatically link all object
14053 files found in the object directory, whether or not they were compiled from
14054 an Ada source file. This specific behavior only applies when multiple
14055 languages are specified.
14056
14057 To create a library project, you need to define in its project file
14058 two project-level attributes: @code{Library_Name} and @code{Library_Dir}.
14059 Additionally, you may define other library-related attributes such as
14060 @code{Library_Kind}, @code{Library_Version}, @code{Library_Interface},
14061 @code{Library_Auto_Init}, @code{Library_Options} and @code{Library_GCC}.
14062
14063 The @code{Library_Name} attribute has a string value. There is no restriction
14064 on the name of a library. It is the responsibility of the developer to
14065 choose a name that will be accepted by the platform. It is recommended to
14066 choose names that could be Ada identifiers; such names are almost guaranteed
14067 to be acceptable on all platforms.
14068
14069 The @code{Library_Dir} attribute has a string value that designates the path
14070 (absolute or relative) of the directory where the library will reside.
14071 It must designate an existing directory, and this directory must be writable,
14072 different from the project's object directory and from any source directory
14073 in the project tree.
14074
14075 If both @code{Library_Name} and @code{Library_Dir} are specified and
14076 are legal, then the project file defines a library project.  The optional
14077 library-related attributes are checked only for such project files.
14078
14079 The @code{Library_Kind} attribute has a string value that must be one of the
14080 following (case insensitive): @code{"static"}, @code{"dynamic"} or
14081 @code{"relocatable"} (which is a synonym for @code{"dynamic"}). If this
14082 attribute is not specified, the library is a static library, that is
14083 an archive of object files that can be potentially linked into a
14084 static executable. Otherwise, the library may be dynamic or
14085 relocatable, that is a library that is loaded only at the start of execution.
14086
14087 If you need to build both a static and a dynamic library, you should use two
14088 different object directories, since in some cases some extra code needs to
14089 be generated for the latter. For such cases, it is recommended to either use
14090 two different project files, or a single one which uses external variables
14091 to indicate what kind of library should be build.
14092
14093 The @code{Library_ALI_Dir} attribute may be specified to indicate the
14094 directory where the ALI files of the library will be copied. When it is
14095 not specified, the ALI files are copied to the directory specified in
14096 attribute @code{Library_Dir}. The directory specified by @code{Library_ALI_Dir}
14097 must be writable and different from the project's object directory and from
14098 any source directory in the project tree.
14099
14100 The @code{Library_Version} attribute has a string value whose interpretation
14101 is platform dependent. It has no effect on VMS and Windows. On Unix, it is
14102 used only for dynamic/relocatable libraries as the internal name of the
14103 library (the @code{"soname"}). If the library file name (built from the
14104 @code{Library_Name}) is different from the @code{Library_Version}, then the
14105 library file will be a symbolic link to the actual file whose name will be
14106 @code{Library_Version}.
14107
14108 Example (on Unix):
14109
14110 @smallexample @c projectfile
14111 @group
14112 project Plib is
14113
14114    Version := "1";
14115
14116    for Library_Dir use "lib_dir";
14117    for Library_Name use "dummy";
14118    for Library_Kind use "relocatable";
14119    for Library_Version use "libdummy.so." & Version;
14120
14121 end Plib;
14122 @end group
14123 @end smallexample
14124
14125 @noindent
14126 Directory @file{lib_dir} will contain the internal library file whose name
14127 will be @file{libdummy.so.1}, and @file{libdummy.so} will be a symbolic link to
14128 @file{libdummy.so.1}.
14129
14130 When @command{gnatmake} detects that a project file
14131 is a library project file, it will check all immediate sources of the project
14132 and rebuild the library if any of the sources have been recompiled.
14133
14134 Standard project files can import library project files. In such cases,
14135 the libraries will only be rebuilt if some of its sources are recompiled
14136 because they are in the closure of some other source in an importing project.
14137 Sources of the library project files that are not in such a closure will
14138 not be checked, unless the full library is checked, because one of its sources
14139 needs to be recompiled.
14140
14141 For instance, assume the project file @code{A} imports the library project file
14142 @code{L}. The immediate sources of A are @file{a1.adb}, @file{a2.ads} and
14143 @file{a2.adb}. The immediate sources of L are @file{l1.ads}, @file{l1.adb},
14144 @file{l2.ads}, @file{l2.adb}.
14145
14146 If @file{l1.adb} has been modified, then the library associated with @code{L}
14147 will be rebuilt when compiling all the immediate sources of @code{A} only
14148 if @file{a1.ads}, @file{a2.ads} or @file{a2.adb} includes a statement
14149 @code{"with L1;"}.
14150
14151 To be sure that all the sources in the library associated with @code{L} are
14152 up to date, and that all the sources of project @code{A} are also up to date,
14153 the following two commands needs to be used:
14154
14155 @smallexample
14156 gnatmake -Pl.gpr
14157 gnatmake -Pa.gpr
14158 @end smallexample
14159
14160 When a library is built or rebuilt, an attempt is made first to delete all
14161 files in the library directory.
14162 All @file{ALI} files will also be copied from the object directory to the
14163 library directory. To build executables, @command{gnatmake} will use the
14164 library rather than the individual object files.
14165
14166 @ifclear vms
14167 It is also possible to create library project files for third-party libraries
14168 that are precompiled and cannot be compiled locally thanks to the
14169 @code{externally_built} attribute. (See @ref{Installing a library}).
14170 @end ifclear
14171
14172 @c *******************************
14173 @c * Stand-alone Library Projects *
14174 @c *******************************
14175
14176 @node Stand-alone Library Projects
14177 @section Stand-alone Library Projects
14178
14179 @noindent
14180 A Stand-alone Library is a library that contains the necessary code to
14181 elaborate the Ada units that are included in the library. A Stand-alone
14182 Library is suitable to be used in an executable when the main is not
14183 in Ada. However, Stand-alone Libraries may also be used with an Ada main
14184 subprogram.
14185
14186 A Stand-alone Library Project is a Library Project where the library is
14187 a Stand-alone Library.
14188
14189 To be a Stand-alone Library Project, in addition to the two attributes
14190 that make a project a Library Project (@code{Library_Name} and
14191 @code{Library_Dir}, see @ref{Library Projects}), the attribute
14192 @code{Library_Interface} must be defined.
14193
14194 @smallexample @c projectfile
14195 @group
14196    for Library_Dir use "lib_dir";
14197    for Library_Name use "dummy";
14198    for Library_Interface use ("int1", "int1.child");
14199 @end group
14200 @end smallexample
14201
14202 Attribute @code{Library_Interface} has a nonempty string list value,
14203 each string in the list designating a unit contained in an immediate source
14204 of the project file.
14205
14206 When a Stand-alone Library is built, first the binder is invoked to build
14207 a package whose name depends on the library name
14208 (^b~dummy.ads/b^B$DUMMY.ADS/B^ in the example above).
14209 This binder-generated package includes initialization and
14210 finalization procedures whose
14211 names depend on the library name (dummyinit and dummyfinal in the example
14212 above). The object corresponding to this package is included in the library.
14213
14214 A dynamic or relocatable Stand-alone Library is automatically initialized
14215 if automatic initialization of Stand-alone Libraries is supported on the
14216 platform and if attribute @code{Library_Auto_Init} is not specified or
14217 is specified with the value "true". A static Stand-alone Library is never
14218 automatically initialized.
14219
14220 Single string attribute @code{Library_Auto_Init} may be specified with only
14221 two possible values: "false" or "true" (case-insensitive). Specifying
14222 "false" for attribute @code{Library_Auto_Init} will prevent automatic
14223 initialization of dynamic or relocatable libraries.
14224
14225 When a non-automatically initialized Stand-alone Library is used
14226 in an executable, its initialization procedure must be called before
14227 any service of the library is used.
14228 When the main subprogram is in Ada, it may mean that the initialization
14229 procedure has to be called during elaboration of another package.
14230
14231 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
14232 (those that are listed in attribute @code{Library_Interface}) are copied to
14233 the Library Directory. As a consequence, only the Interface Units may be
14234 imported from Ada units outside of the library. If other units are imported,
14235 the binding phase will fail.
14236
14237 When a Stand-Alone Library is bound, the switches that are specified in
14238 the attribute @code{Default_Switches ("Ada")} in package @code{Binder} are
14239 used in the call to @command{gnatbind}.
14240
14241 The string list attribute @code{Library_Options} may be used to specified
14242 additional switches to the call to @command{gcc} to link the library.
14243
14244 The attribute @code{Library_Src_Dir}, may be specified for a
14245 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
14246 single string value. Its value must be the path (absolute or relative to the
14247 project directory) of an existing directory. This directory cannot be the
14248 object directory or one of the source directories, but it can be the same as
14249 the library directory. The sources of the Interface
14250 Units of the library, necessary to an Ada client of the library, will be
14251 copied to the designated directory, called Interface Copy directory.
14252 These sources includes the specs of the Interface Units, but they may also
14253 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
14254 are used, or when there is a generic units in the spec. Before the sources
14255 are copied to the Interface Copy directory, an attempt is made to delete all
14256 files in the Interface Copy directory.
14257
14258 @c *************************************
14259 @c * Switches Related to Project Files *
14260 @c *************************************
14261 @node Switches Related to Project Files
14262 @section Switches Related to Project Files
14263
14264 @noindent
14265 The following switches are used by GNAT tools that support project files:
14266
14267 @table @option
14268
14269 @item ^-P^/PROJECT_FILE=^@var{project}
14270 @cindex @option{^-P^/PROJECT_FILE^} (any project-aware tool)
14271 Indicates the name of a project file. This project file will be parsed with
14272 the verbosity indicated by @option{^-vP^MESSAGE_PROJECT_FILES=^@emph{x}},
14273 if any, and using the external references indicated
14274 by @option{^-X^/EXTERNAL_REFERENCE^} switches, if any.
14275 @ifclear vms
14276 There may zero, one or more spaces between @option{-P} and @var{project}.
14277 @end ifclear
14278
14279 @noindent
14280 There must be only one @option{^-P^/PROJECT_FILE^} switch on the command line.
14281
14282 @noindent
14283 Since the Project Manager parses the project file only after all the switches
14284 on the command line are checked, the order of the switches
14285 @option{^-P^/PROJECT_FILE^},
14286 @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}}
14287 or @option{^-X^/EXTERNAL_REFERENCE^} is not significant.
14288
14289 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
14290 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (any project-aware tool)
14291 Indicates that external variable @var{name} has the value @var{value}.
14292 The Project Manager will use this value for occurrences of
14293 @code{external(name)} when parsing the project file.
14294
14295 @ifclear vms
14296 @noindent
14297 If @var{name} or @var{value} includes a space, then @var{name=value} should be
14298 put between quotes.
14299 @smallexample
14300   -XOS=NT
14301   -X"user=John Doe"
14302 @end smallexample
14303 @end ifclear
14304
14305 @noindent
14306 Several @option{^-X^/EXTERNAL_REFERENCE^} switches can be used simultaneously.
14307 If several @option{^-X^/EXTERNAL_REFERENCE^} switches specify the same
14308 @var{name}, only the last one is used.
14309
14310 @noindent
14311 An external variable specified with a @option{^-X^/EXTERNAL_REFERENCE^} switch
14312 takes precedence over the value of the same name in the environment.
14313
14314 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
14315 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (any project-aware tool)
14316 Indicates the verbosity of the parsing of GNAT project files.
14317
14318 @ifclear vms
14319 @option{-vP0} means Default;
14320 @option{-vP1} means Medium;
14321 @option{-vP2} means High.
14322 @end ifclear
14323
14324 @ifset vms
14325 There are three possible options for this qualifier: DEFAULT, MEDIUM and
14326 HIGH.
14327 @end ifset
14328
14329 @noindent
14330 The default is ^Default^DEFAULT^: no output for syntactically correct
14331 project files.
14332 @noindent
14333 If several @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}} switches are present,
14334 only the last one is used.
14335
14336 @item ^-aP^/ADD_PROJECT_SEARCH_DIR=^<dir>
14337 @cindex @option{^-aP^/ADD_PROJECT_SEARCH_DIR=^} (any project-aware tool)
14338 Add directory <dir> at the beginning of the project search path, in order,
14339 after the current working directory.
14340
14341 @ifclear vms
14342 @item -eL
14343 @cindex @option{-eL} (any project-aware tool)
14344 Follow all symbolic links when processing project files.
14345 @end ifclear
14346
14347 @item ^--subdirs^/SUBDIRS^=<subdir>
14348 @cindex @option{^--subdirs^/SUBDIRS^=} (gnatmake and gnatclean)
14349 This switch is recognized by gnatmake and gnatclean. It indicate that the real
14350 directories (except the source directories) are the subdirectories <subdir>
14351 of the directories specified in the project files. This applies in particular
14352 to object directories, library directories and exec directories. If the
14353 subdirectories do not exist, they are created automatically.
14354
14355 @end table
14356
14357 @c **********************************
14358 @c * Tools Supporting Project Files *
14359 @c **********************************
14360
14361 @node  Tools Supporting Project Files
14362 @section Tools Supporting Project Files
14363
14364 @menu
14365 * gnatmake and Project Files::
14366 * The GNAT Driver and Project Files::
14367 @end menu
14368
14369 @node gnatmake and Project Files
14370 @subsection gnatmake and Project Files
14371
14372 @noindent
14373 This section covers several topics related to @command{gnatmake} and
14374 project files: defining ^switches^switches^ for @command{gnatmake}
14375 and for the tools that it invokes; specifying configuration pragmas;
14376 the use of the @code{Main} attribute; building and rebuilding library project
14377 files.
14378
14379 @menu
14380 * ^Switches^Switches^ and Project Files::
14381 * Specifying Configuration Pragmas::
14382 * Project Files and Main Subprograms::
14383 * Library Project Files::
14384 @end menu
14385
14386 @node ^Switches^Switches^ and Project Files
14387 @subsubsection ^Switches^Switches^ and Project Files
14388
14389 @ifset vms
14390 It is not currently possible to specify VMS style qualifiers in the project
14391 files; only Unix style ^switches^switches^ may be specified.
14392 @end ifset
14393
14394 @noindent
14395 For each of the packages @code{Builder}, @code{Compiler}, @code{Binder}, and
14396 @code{Linker}, you can specify a @code{^Default_Switches^Default_Switches^}
14397 attribute, a @code{^Switches^Switches^} attribute, or both;
14398 as their names imply, these ^switch^switch^-related
14399 attributes affect the ^switches^switches^ that are used for each of these GNAT
14400 components when
14401 @command{gnatmake} is invoked.  As will be explained below, these
14402 component-specific ^switches^switches^ precede
14403 the ^switches^switches^ provided on the @command{gnatmake} command line.
14404
14405 The @code{^Default_Switches^Default_Switches^} attribute is an associative
14406 array indexed by language name (case insensitive) whose value is a string list.
14407 For example:
14408
14409 @smallexample @c projectfile
14410 @group
14411 package Compiler is
14412   for ^Default_Switches^Default_Switches^ ("Ada")
14413       use ("^-gnaty^-gnaty^",
14414            "^-v^-v^");
14415 end Compiler;
14416 @end group
14417 @end smallexample
14418
14419 @noindent
14420 The @code{^Switches^Switches^} attribute is also an associative array,
14421 indexed by a file name (which may or may not be case sensitive, depending
14422 on the operating system) whose value is a string list.  For example:
14423
14424 @smallexample @c projectfile
14425 @group
14426 package Builder is
14427    for ^Switches^Switches^ ("main1.adb")
14428        use ("^-O2^-O2^");
14429    for ^Switches^Switches^ ("main2.adb")
14430        use ("^-g^-g^");
14431 end Builder;
14432 @end group
14433 @end smallexample
14434
14435 @noindent
14436 For the @code{Builder} package, the file names must designate source files
14437 for main subprograms.  For the @code{Binder} and @code{Linker} packages, the
14438 file names must designate @file{ALI} or source files for main subprograms.
14439 In each case just the file name without an explicit extension is acceptable.
14440
14441 For each tool used in a program build (@command{gnatmake}, the compiler, the
14442 binder, and the linker), the corresponding package @dfn{contributes} a set of
14443 ^switches^switches^ for each file on which the tool is invoked, based on the
14444 ^switch^switch^-related attributes defined in the package.
14445 In particular, the ^switches^switches^
14446 that each of these packages contributes for a given file @var{f} comprise:
14447
14448 @itemize @bullet
14449 @item
14450 the value of attribute @code{^Switches^Switches^ (@var{f})},
14451 if it is specified in the package for the given file,
14452 @item
14453 otherwise, the value of @code{^Default_Switches^Default_Switches^ ("Ada")},
14454 if it is specified in the package.
14455 @end itemize
14456
14457 @noindent
14458 If neither of these attributes is defined in the package, then the package does
14459 not contribute any ^switches^switches^ for the given file.
14460
14461 When @command{gnatmake} is invoked on a file, the ^switches^switches^ comprise
14462 two sets, in the following order: those contributed for the file
14463 by the @code{Builder} package;
14464 and the switches passed on the command line.
14465
14466 When @command{gnatmake} invokes a tool (compiler, binder, linker) on a file,
14467 the ^switches^switches^ passed to the tool comprise three sets,
14468 in the following order:
14469
14470 @enumerate
14471 @item
14472 the applicable ^switches^switches^ contributed for the file
14473 by the @code{Builder} package in the project file supplied on the command line;
14474
14475 @item
14476 those contributed for the file by the package (in the relevant project file --
14477 see below) corresponding to the tool; and
14478
14479 @item
14480 the applicable switches passed on the command line.
14481 @end enumerate
14482
14483 @noindent
14484 The term @emph{applicable ^switches^switches^} reflects the fact that
14485 @command{gnatmake} ^switches^switches^ may or may not be passed to individual
14486 tools, depending on the individual ^switch^switch^.
14487
14488 @command{gnatmake} may invoke the compiler on source files from different
14489 projects. The Project Manager will use the appropriate project file to
14490 determine the @code{Compiler} package for each source file being compiled.
14491 Likewise for the @code{Binder} and @code{Linker} packages.
14492
14493 As an example, consider the following package in a project file:
14494
14495 @smallexample @c projectfile
14496 @group
14497 project Proj1 is
14498    package Compiler is
14499       for ^Default_Switches^Default_Switches^ ("Ada")
14500           use ("^-g^-g^");
14501       for ^Switches^Switches^ ("a.adb")
14502           use ("^-O1^-O1^");
14503       for ^Switches^Switches^ ("b.adb")
14504           use ("^-O2^-O2^",
14505                "^-gnaty^-gnaty^");
14506    end Compiler;
14507 end Proj1;
14508 @end group
14509 @end smallexample
14510
14511 @noindent
14512 If @command{gnatmake} is invoked with this project file, and it needs to
14513 compile, say, the files @file{a.adb}, @file{b.adb}, and @file{c.adb}, then
14514 @file{a.adb} will be compiled with the ^switch^switch^
14515 @option{^-O1^-O1^},
14516 @file{b.adb} with ^switches^switches^
14517 @option{^-O2^-O2^}
14518 and @option{^-gnaty^-gnaty^},
14519 and @file{c.adb} with @option{^-g^-g^}.
14520
14521 The following example illustrates the ordering of the ^switches^switches^
14522 contributed by different packages:
14523
14524 @smallexample @c projectfile
14525 @group
14526 project Proj2 is
14527    package Builder is
14528       for ^Switches^Switches^ ("main.adb")
14529           use ("^-g^-g^",
14530                "^-O1^-)1^",
14531                "^-f^-f^");
14532    end Builder;
14533 @end group
14534
14535 @group
14536    package Compiler is
14537       for ^Switches^Switches^ ("main.adb")
14538           use ("^-O2^-O2^");
14539    end Compiler;
14540 end Proj2;
14541 @end group
14542 @end smallexample
14543
14544 @noindent
14545 If you issue the command:
14546
14547 @smallexample
14548     gnatmake ^-Pproj2^/PROJECT_FILE=PROJ2^ -O0 main
14549 @end smallexample
14550
14551 @noindent
14552 then the compiler will be invoked on @file{main.adb} with the following
14553 sequence of ^switches^switches^
14554
14555 @smallexample
14556    ^-g -O1 -O2 -O0^-g -O1 -O2 -O0^
14557 @end smallexample
14558
14559 with the last @option{^-O^-O^}
14560 ^switch^switch^ having precedence over the earlier ones;
14561 several other ^switches^switches^
14562 (such as @option{^-c^-c^}) are added implicitly.
14563
14564 The ^switches^switches^
14565 @option{^-g^-g^}
14566 and @option{^-O1^-O1^} are contributed by package
14567 @code{Builder},  @option{^-O2^-O2^} is contributed
14568 by the package @code{Compiler}
14569 and @option{^-O0^-O0^} comes from the command line.
14570
14571 The @option{^-g^-g^}
14572 ^switch^switch^ will also be passed in the invocation of
14573 @command{Gnatlink.}
14574
14575 A final example illustrates switch contributions from packages in different
14576 project files:
14577
14578 @smallexample @c projectfile
14579 @group
14580 project Proj3 is
14581    for Source_Files use ("pack.ads", "pack.adb");
14582    package Compiler is
14583       for ^Default_Switches^Default_Switches^ ("Ada")
14584           use ("^-gnata^-gnata^");
14585    end Compiler;
14586 end Proj3;
14587 @end group
14588
14589 @group
14590 with "Proj3";
14591 project Proj4 is
14592    for Source_Files use ("foo_main.adb", "bar_main.adb");
14593    package Builder is
14594       for ^Switches^Switches^ ("foo_main.adb")
14595           use ("^-s^-s^",
14596                "^-g^-g^");
14597    end Builder;
14598 end Proj4;
14599 @end group
14600
14601 @group
14602 -- Ada source file:
14603 with Pack;
14604 procedure Foo_Main is
14605    @dots{}
14606 end Foo_Main;
14607 @end group
14608 @end smallexample
14609
14610 If the command is
14611 @smallexample
14612 gnatmake ^-PProj4^/PROJECT_FILE=PROJ4^ foo_main.adb -cargs -gnato
14613 @end smallexample
14614
14615 @noindent
14616 then the ^switches^switches^ passed to the compiler for @file{foo_main.adb} are
14617 @option{^-g^-g^} (contributed by the package @code{Proj4.Builder}) and
14618 @option{^-gnato^-gnato^} (passed on the command line).
14619 When the imported package @code{Pack} is compiled, the ^switches^switches^ used
14620 are @option{^-g^-g^} from @code{Proj4.Builder},
14621 @option{^-gnata^-gnata^} (contributed from package @code{Proj3.Compiler},
14622 and @option{^-gnato^-gnato^} from the command line.
14623
14624 @noindent
14625 When using @command{gnatmake} with project files, some ^switches^switches^ or
14626 arguments may be expressed as relative paths. As the working directory where
14627 compilation occurs may change, these relative paths are converted to absolute
14628 paths. For the ^switches^switches^ found in a project file, the relative paths
14629 are relative to the project file directory, for the switches on the command
14630 line, they are relative to the directory where @command{gnatmake} is invoked.
14631 The ^switches^switches^ for which this occurs are:
14632 ^-I^-I^,
14633 ^-A^-A^,
14634 ^-L^-L^,
14635 ^-aO^-aO^,
14636 ^-aL^-aL^,
14637 ^-aI^-aI^, as well as all arguments that are not switches (arguments to
14638 ^switch^switch^
14639 ^-o^-o^, object files specified in package @code{Linker} or after
14640 -largs on the command line). The exception to this rule is the ^switch^switch^
14641 ^--RTS=^--RTS=^ for which a relative path argument is never converted.
14642
14643 @node Specifying Configuration Pragmas
14644 @subsubsection Specifying Configuration Pragmas
14645
14646 When using @command{gnatmake} with project files, if there exists a file
14647 @file{gnat.adc} that contains configuration pragmas, this file will be
14648 ignored.
14649
14650 Configuration pragmas can be defined by means of the following attributes in
14651 project files: @code{Global_Configuration_Pragmas} in package @code{Builder}
14652 and @code{Local_Configuration_Pragmas} in package @code{Compiler}.
14653
14654 Both these attributes are single string attributes. Their values is the path
14655 name of a file containing configuration pragmas. If a path name is relative,
14656 then it is relative to the project directory of the project file where the
14657 attribute is defined.
14658
14659 When compiling a source, the configuration pragmas used are, in order,
14660 those listed in the file designated by attribute
14661 @code{Global_Configuration_Pragmas} in package @code{Builder} of the main
14662 project file, if it is specified, and those listed in the file designated by
14663 attribute @code{Local_Configuration_Pragmas} in package @code{Compiler} of
14664 the project file of the source, if it exists.
14665
14666 @node Project Files and Main Subprograms
14667 @subsubsection Project Files and Main Subprograms
14668
14669 @noindent
14670 When using a project file, you can invoke @command{gnatmake}
14671 with one or several main subprograms, by specifying their source files on the
14672 command line.
14673
14674 @smallexample
14675     gnatmake ^-P^/PROJECT_FILE=^prj main1 main2 main3
14676 @end smallexample
14677
14678 @noindent
14679 Each of these needs to be a source file of the same project, except
14680 when the switch ^-u^/UNIQUE^ is used.
14681
14682 @noindent
14683 When ^-u^/UNIQUE^ is not used, all the mains need to be sources of the
14684 same project, one of the project in the tree rooted at the project specified
14685 on the command line. The package @code{Builder} of this common project, the
14686 "main project" is the one that is considered by @command{gnatmake}.
14687
14688 @noindent
14689 When ^-u^/UNIQUE^ is used, the specified source files may be in projects
14690 imported directly or indirectly by the project specified on the command line.
14691 Note that if such a source file is not part of the project specified on the
14692 command line, the ^switches^switches^ found in package @code{Builder} of the
14693 project specified on the command line, if any, that are transmitted
14694 to the compiler will still be used, not those found in the project file of
14695 the source file.
14696
14697 @noindent
14698 When using a project file, you can also invoke @command{gnatmake} without
14699 explicitly specifying any main, and the effect depends on whether you have
14700 defined the @code{Main} attribute.  This attribute has a string list value,
14701 where each element in the list is the name of a source file (the file
14702 extension is optional) that contains a unit that can be a main subprogram.
14703
14704 If the @code{Main} attribute is defined in a project file as a non-empty
14705 string list and the switch @option{^-u^/UNIQUE^} is not used on the command
14706 line, then invoking @command{gnatmake} with this project file but without any
14707 main on the command line is equivalent to invoking @command{gnatmake} with all
14708 the file names in the @code{Main} attribute on the command line.
14709
14710 Example:
14711 @smallexample @c projectfile
14712 @group
14713    project Prj is
14714       for Main use ("main1", "main2", "main3");
14715    end Prj;
14716 @end group
14717 @end smallexample
14718
14719 @noindent
14720 With this project file, @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^"}
14721 is equivalent to
14722 @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^ main1 main2 main3"}.
14723
14724 When the project attribute @code{Main} is not specified, or is specified
14725 as an empty string list, or when the switch @option{-u} is used on the command
14726 line, then invoking @command{gnatmake} with no main on the command line will
14727 result in all immediate sources of the project file being checked, and
14728 potentially recompiled. Depending on the presence of the switch @option{-u},
14729 sources from other project files on which the immediate sources of the main
14730 project file depend are also checked and potentially recompiled. In other
14731 words, the @option{-u} switch is applied to all of the immediate sources of the
14732 main project file.
14733
14734 When no main is specified on the command line and attribute @code{Main} exists
14735 and includes several mains, or when several mains are specified on the
14736 command line, the default ^switches^switches^ in package @code{Builder} will
14737 be used for all mains, even if there are specific ^switches^switches^
14738 specified for one or several mains.
14739
14740 But the ^switches^switches^ from package @code{Binder} or @code{Linker} will be
14741 the specific ^switches^switches^ for each main, if they are specified.
14742
14743 @node Library Project Files
14744 @subsubsection Library Project Files
14745
14746 @noindent
14747 When @command{gnatmake} is invoked with a main project file that is a library
14748 project file, it is not allowed to specify one or more mains on the command
14749 line.
14750
14751 @noindent
14752 When a library project file is specified, switches ^-b^/ACTION=BIND^ and
14753 ^-l^/ACTION=LINK^ have special meanings.
14754
14755 @itemize @bullet
14756 @item ^-b^/ACTION=BIND^ is only allowed for stand-alone libraries. It indicates
14757 to @command{gnatmake} that @command{gnatbind} should be invoked for the
14758 library.
14759
14760 @item ^-l^/ACTION=LINK^ may be used for all library projects. It indicates
14761 to @command{gnatmake} that the binder generated file should be compiled
14762 (in the case of a stand-alone library) and that the library should be built.
14763
14764 @end itemize
14765
14766 @node The GNAT Driver and Project Files
14767 @subsection The GNAT Driver and Project Files
14768
14769 @noindent
14770 A number of GNAT tools, other than @command{^gnatmake^gnatmake^}
14771 can benefit from project files:
14772 @command{^gnatbind^gnatbind^},
14773 @command{^gnatcheck^gnatcheck^}),
14774 @command{^gnatclean^gnatclean^}),
14775 @command{^gnatelim^gnatelim^},
14776 @command{^gnatfind^gnatfind^},
14777 @command{^gnatlink^gnatlink^},
14778 @command{^gnatls^gnatls^},
14779 @command{^gnatmetric^gnatmetric^},
14780 @command{^gnatpp^gnatpp^},
14781 @command{^gnatstub^gnatstub^},
14782 and @command{^gnatxref^gnatxref^}. However, none of these tools can be invoked
14783 directly with a project file switch (@option{^-P^/PROJECT_FILE=^}).
14784 They must be invoked through the @command{gnat} driver.
14785
14786 The @command{gnat} driver is a wrapper that accepts a number of commands and
14787 calls the corresponding tool. It was designed initially for VMS platforms (to
14788 convert VMS qualifiers to Unix-style switches), but it is now available on all
14789 GNAT platforms.
14790
14791 On non-VMS platforms, the @command{gnat} driver accepts the following commands
14792 (case insensitive):
14793
14794 @itemize @bullet
14795 @item
14796 BIND to invoke @command{^gnatbind^gnatbind^}
14797 @item
14798 CHOP to invoke @command{^gnatchop^gnatchop^}
14799 @item
14800 CLEAN to invoke @command{^gnatclean^gnatclean^}
14801 @item
14802 COMP or COMPILE to invoke the compiler
14803 @item
14804 ELIM to invoke @command{^gnatelim^gnatelim^}
14805 @item
14806 FIND to invoke @command{^gnatfind^gnatfind^}
14807 @item
14808 KR or KRUNCH to invoke @command{^gnatkr^gnatkr^}
14809 @item
14810 LINK to invoke @command{^gnatlink^gnatlink^}
14811 @item
14812 LS or LIST to invoke @command{^gnatls^gnatls^}
14813 @item
14814 MAKE to invoke @command{^gnatmake^gnatmake^}
14815 @item
14816 NAME to invoke @command{^gnatname^gnatname^}
14817 @item
14818 PREP or PREPROCESS to invoke @command{^gnatprep^gnatprep^}
14819 @item
14820 PP or PRETTY to invoke @command{^gnatpp^gnatpp^}
14821 @item
14822 METRIC to invoke @command{^gnatmetric^gnatmetric^}
14823 @item
14824 STUB to invoke @command{^gnatstub^gnatstub^}
14825 @item
14826 XREF to invoke @command{^gnatxref^gnatxref^}
14827 @end itemize
14828
14829 @noindent
14830 (note that the compiler is invoked using the command
14831 @command{^gnatmake -f -u -c^gnatmake -f -u -c^}).
14832
14833 @noindent
14834 On non-VMS platforms, between @command{gnat} and the command, two
14835 special switches may be used:
14836
14837 @itemize @bullet
14838 @item
14839 @command{-v} to display the invocation of the tool.
14840 @item
14841 @command{-dn} to prevent the @command{gnat} driver from removing
14842 the temporary files it has created. These temporary files are
14843 configuration files and temporary file list files.
14844 @end itemize
14845
14846 @noindent
14847 The command may be followed by switches and arguments for the invoked
14848 tool.
14849
14850 @smallexample
14851   gnat bind -C main.ali
14852   gnat ls -a main
14853   gnat chop foo.txt
14854 @end smallexample
14855
14856 @noindent
14857 Switches may also be put in text files, one switch per line, and the text
14858 files may be specified with their path name preceded by '@@'.
14859
14860 @smallexample
14861    gnat bind @@args.txt main.ali
14862 @end smallexample
14863
14864 @noindent
14865 In addition, for commands BIND, COMP or COMPILE, FIND, ELIM, LS or LIST, LINK,
14866 METRIC, PP or PRETTY, STUB and XREF, the project file related switches
14867 (@option{^-P^/PROJECT_FILE^},
14868 @option{^-X^/EXTERNAL_REFERENCE^} and
14869 @option{^-vP^/MESSAGES_PROJECT_FILE=^x}) may be used in addition to
14870 the switches of the invoking tool.
14871
14872 @noindent
14873 When GNAT PP or GNAT PRETTY is used with a project file, but with no source
14874 specified on the command line, it invokes @command{^gnatpp^gnatpp^} with all
14875 the immediate sources of the specified project file.
14876
14877 @noindent
14878 When GNAT METRIC is used with a project file, but with no source
14879 specified on the command line, it invokes @command{^gnatmetric^gnatmetric^}
14880 with all the immediate sources of the specified project file and with
14881 @option{^-d^/DIRECTORY^} with the parameter pointing to the object directory
14882 of the project.
14883
14884 @noindent
14885 In addition, when GNAT PP, GNAT PRETTY or GNAT METRIC is used with
14886 a project file, no source is specified on the command line and
14887 switch ^-U^/ALL_PROJECTS^ is specified on the command line, then
14888 the underlying tool (^gnatpp^gnatpp^ or
14889 ^gnatmetric^gnatmetric^) is invoked for all sources of all projects,
14890 not only for the immediate sources of the main project.
14891 @ifclear vms
14892 (-U stands for Universal or Union of the project files of the project tree)
14893 @end ifclear
14894
14895 @noindent
14896 For each of the following commands, there is optionally a corresponding
14897 package in the main project.
14898
14899 @itemize @bullet
14900 @item
14901 package @code{Binder} for command BIND (invoking @code{^gnatbind^gnatbind^})
14902
14903 @item
14904 package @code{Check} for command CHECK (invoking
14905 @code{^gnatcheck^gnatcheck^})
14906
14907 @item
14908 package @code{Compiler} for command COMP or COMPILE (invoking the compiler)
14909
14910 @item
14911 package @code{Cross_Reference} for command XREF (invoking
14912 @code{^gnatxref^gnatxref^})
14913
14914 @item
14915 package @code{Eliminate} for command ELIM (invoking
14916 @code{^gnatelim^gnatelim^})
14917
14918 @item
14919 package @code{Finder} for command FIND (invoking @code{^gnatfind^gnatfind^})
14920
14921 @item
14922 package @code{Gnatls} for command LS or LIST (invoking @code{^gnatls^gnatls^})
14923
14924 @item
14925 package @code{Gnatstub} for command STUB
14926 (invoking @code{^gnatstub^gnatstub^})
14927
14928 @item
14929 package @code{Linker} for command LINK (invoking @code{^gnatlink^gnatlink^})
14930
14931 @item
14932 package @code{Check} for command CHECK
14933 (invoking @code{^gnatcheck^gnatcheck^})
14934
14935 @item
14936 package @code{Metrics} for command METRIC
14937 (invoking @code{^gnatmetric^gnatmetric^})
14938
14939 @item
14940 package @code{Pretty_Printer} for command PP or PRETTY
14941 (invoking @code{^gnatpp^gnatpp^})
14942
14943 @end itemize
14944
14945 @noindent
14946 Package @code{Gnatls} has a unique attribute @code{^Switches^Switches^},
14947 a simple variable with a string list value. It contains ^switches^switches^
14948 for the invocation of @code{^gnatls^gnatls^}.
14949
14950 @smallexample @c projectfile
14951 @group
14952 project Proj1 is
14953    package gnatls is
14954       for ^Switches^Switches^
14955           use ("^-a^-a^",
14956                "^-v^-v^");
14957    end gnatls;
14958 end Proj1;
14959 @end group
14960 @end smallexample
14961
14962 @noindent
14963 All other packages have two attribute @code{^Switches^Switches^} and
14964 @code{^Default_Switches^Default_Switches^}.
14965
14966 @noindent
14967 @code{^Switches^Switches^} is an associative array attribute, indexed by the
14968 source file name, that has a string list value: the ^switches^switches^ to be
14969 used when the tool corresponding to the package is invoked for the specific
14970 source file.
14971
14972 @noindent
14973 @code{^Default_Switches^Default_Switches^} is an associative array attribute,
14974 indexed by  the programming language that has a string list value.
14975 @code{^Default_Switches^Default_Switches^ ("Ada")} contains the
14976 ^switches^switches^ for the invocation of the tool corresponding
14977 to the package, except if a specific @code{^Switches^Switches^} attribute
14978 is specified for the source file.
14979
14980 @smallexample @c projectfile
14981 @group
14982 project Proj is
14983
14984    for Source_Dirs use ("./**");
14985
14986    package gnatls is
14987       for ^Switches^Switches^ use
14988           ("^-a^-a^",
14989            "^-v^-v^");
14990    end gnatls;
14991 @end group
14992 @group
14993
14994    package Compiler is
14995       for ^Default_Switches^Default_Switches^ ("Ada")
14996           use ("^-gnatv^-gnatv^",
14997                "^-gnatwa^-gnatwa^");
14998    end Binder;
14999 @end group
15000 @group
15001
15002    package Binder is
15003       for ^Default_Switches^Default_Switches^ ("Ada")
15004           use ("^-C^-C^",
15005                "^-e^-e^");
15006    end Binder;
15007 @end group
15008 @group
15009
15010    package Linker is
15011       for ^Default_Switches^Default_Switches^ ("Ada")
15012           use ("^-C^-C^");
15013       for ^Switches^Switches^ ("main.adb")
15014           use ("^-C^-C^",
15015                "^-v^-v^",
15016                "^-v^-v^");
15017    end Linker;
15018 @end group
15019 @group
15020
15021    package Finder is
15022       for ^Default_Switches^Default_Switches^ ("Ada")
15023            use ("^-a^-a^",
15024                 "^-f^-f^");
15025    end Finder;
15026 @end group
15027 @group
15028
15029    package Cross_Reference is
15030       for ^Default_Switches^Default_Switches^ ("Ada")
15031           use ("^-a^-a^",
15032                "^-f^-f^",
15033                "^-d^-d^",
15034                "^-u^-u^");
15035    end Cross_Reference;
15036 end Proj;
15037 @end group
15038 @end smallexample
15039
15040 @noindent
15041 With the above project file, commands such as
15042
15043 @smallexample
15044    ^gnat comp -Pproj main^GNAT COMP /PROJECT_FILE=PROJ MAIN^
15045    ^gnat ls -Pproj main^GNAT LIST /PROJECT_FILE=PROJ MAIN^
15046    ^gnat xref -Pproj main^GNAT XREF /PROJECT_FILE=PROJ MAIN^
15047    ^gnat bind -Pproj main.ali^GNAT BIND /PROJECT_FILE=PROJ MAIN.ALI^
15048    ^gnat link -Pproj main.ali^GNAT LINK /PROJECT_FILE=PROJ MAIN.ALI^
15049 @end smallexample
15050
15051 @noindent
15052 will set up the environment properly and invoke the tool with the switches
15053 found in the package corresponding to the tool:
15054 @code{^Default_Switches^Default_Switches^ ("Ada")} for all tools,
15055 except @code{^Switches^Switches^ ("main.adb")}
15056 for @code{^gnatlink^gnatlink^}.
15057 It is also possible to invoke some of the tools,
15058 @code{^gnatcheck^gnatcheck^}),
15059 @code{^gnatmetric^gnatmetric^}),
15060 and @code{^gnatpp^gnatpp^})
15061 on a set of project units thanks to the combination of the switches
15062 @option{-P}, @option{-U} and possibly the main unit when one is interested
15063 in its closure. For instance,
15064 @smallexample
15065 gnat metric -Pproj
15066 @end smallexample
15067 will compute the metrics for all the immediate units of project
15068 @code{proj}.
15069 @smallexample
15070 gnat metric -Pproj -U
15071 @end smallexample
15072 will compute the metrics for all the units of the closure of projects
15073 rooted at @code{proj}.
15074 @smallexample
15075 gnat metric -Pproj -U main_unit
15076 @end smallexample
15077 will compute the metrics for the closure of units rooted at
15078 @code{main_unit}. This last possibility relies implicitly
15079 on @command{gnatbind}'s option @option{-R}.
15080
15081 @c **********************
15082 @node An Extended Example
15083 @section An Extended Example
15084
15085 @noindent
15086 Suppose that we have two programs, @var{prog1} and @var{prog2},
15087 whose sources are in corresponding directories. We would like
15088 to build them with a single @command{gnatmake} command, and we want to place
15089 their object files into @file{build} subdirectories of the source directories.
15090 Furthermore, we want to have to have two separate subdirectories
15091 in @file{build}  -- @file{release} and @file{debug} -- which will contain
15092 the object files compiled with different set of compilation flags.
15093
15094 In other words, we have the following structure:
15095
15096 @smallexample
15097 @group
15098    main
15099      |- prog1
15100      |    |- build
15101      |         | debug
15102      |         | release
15103      |- prog2
15104           |- build
15105                | debug
15106                | release
15107 @end group
15108 @end smallexample
15109
15110 @noindent
15111 Here are the project files that we must place in a directory @file{main}
15112 to maintain this structure:
15113
15114 @enumerate
15115
15116 @item We create a @code{Common} project with a package @code{Compiler} that
15117 specifies the compilation ^switches^switches^:
15118
15119 @smallexample
15120 File "common.gpr":
15121 @group
15122 @b{project} Common @b{is}
15123
15124    @b{for} Source_Dirs @b{use} (); -- No source files
15125 @end group
15126
15127 @group
15128    @b{type} Build_Type @b{is} ("release", "debug");
15129    Build : Build_Type := External ("BUILD", "debug");
15130 @end group
15131 @group
15132    @b{package} Compiler @b{is}
15133       @b{case} Build @b{is}
15134          @b{when} "release" =>
15135            @b{for} ^Default_Switches^Default_Switches^ ("Ada")
15136                    @b{use} ("^-O2^-O2^");
15137          @b{when} "debug"   =>
15138            @b{for} ^Default_Switches^Default_Switches^ ("Ada")
15139                    @b{use} ("^-g^-g^");
15140       @b{end case};
15141    @b{end} Compiler;
15142
15143 @b{end} Common;
15144 @end group
15145 @end smallexample
15146
15147 @item We create separate projects for the two programs:
15148
15149 @smallexample
15150 @group
15151 File "prog1.gpr":
15152
15153 @b{with} "common";
15154 @b{project} Prog1 @b{is}
15155
15156     @b{for} Source_Dirs @b{use} ("prog1");
15157     @b{for} Object_Dir  @b{use} "prog1/build/" & Common.Build;
15158
15159     @b{package} Compiler @b{renames} Common.Compiler;
15160
15161 @b{end} Prog1;
15162 @end group
15163 @end smallexample
15164
15165 @smallexample
15166 @group
15167 File "prog2.gpr":
15168
15169 @b{with} "common";
15170 @b{project} Prog2 @b{is}
15171
15172     @b{for} Source_Dirs @b{use} ("prog2");
15173     @b{for} Object_Dir  @b{use} "prog2/build/" & Common.Build;
15174
15175     @b{package} Compiler @b{renames} Common.Compiler;
15176
15177 @end group
15178 @b{end} Prog2;
15179 @end smallexample
15180
15181 @item We create a wrapping project @code{Main}:
15182
15183 @smallexample
15184 @group
15185 File "main.gpr":
15186
15187 @b{with} "common";
15188 @b{with} "prog1";
15189 @b{with} "prog2";
15190 @b{project} Main @b{is}
15191
15192    @b{package} Compiler @b{renames} Common.Compiler;
15193
15194 @b{end} Main;
15195 @end group
15196 @end smallexample
15197
15198 @item Finally we need to create a dummy procedure that @code{with}s (either
15199 explicitly or implicitly) all the sources of our two programs.
15200
15201 @end enumerate
15202
15203 @noindent
15204 Now we can build the programs using the command
15205
15206 @smallexample
15207    gnatmake ^-P^/PROJECT_FILE=^main dummy
15208 @end smallexample
15209
15210 @noindent
15211 for the Debug mode, or
15212
15213 @ifclear vms
15214 @smallexample
15215    gnatmake -Pmain -XBUILD=release
15216 @end smallexample
15217 @end ifclear
15218
15219 @ifset vms
15220 @smallexample
15221    GNAT MAKE /PROJECT_FILE=main /EXTERNAL_REFERENCE=BUILD=release
15222 @end smallexample
15223 @end ifset
15224
15225 @noindent
15226 for the Release mode.
15227
15228 @c ********************************
15229 @c * Project File Complete Syntax *
15230 @c ********************************
15231
15232 @node Project File Complete Syntax
15233 @section Project File Complete Syntax
15234
15235 @smallexample
15236 project ::=
15237   context_clause project_declaration
15238
15239 context_clause ::=
15240   @{with_clause@}
15241
15242 with_clause ::=
15243   @b{with} path_name @{ , path_name @} ;
15244
15245 path_name ::=
15246    string_literal
15247
15248 project_declaration ::=
15249   simple_project_declaration | project_extension
15250
15251 simple_project_declaration ::=
15252   @b{project} <project_>simple_name @b{is}
15253     @{declarative_item@}
15254   @b{end} <project_>simple_name;
15255
15256 project_extension ::=
15257   @b{project} <project_>simple_name  @b{extends} path_name @b{is}
15258     @{declarative_item@}
15259   @b{end} <project_>simple_name;
15260
15261 declarative_item ::=
15262   package_declaration |
15263   typed_string_declaration |
15264   other_declarative_item
15265
15266 package_declaration ::=
15267   package_spec | package_renaming
15268
15269 package_spec ::=
15270   @b{package} package_identifier @b{is}
15271     @{simple_declarative_item@}
15272   @b{end} package_identifier ;
15273
15274 package_identifier ::=
15275   @code{Naming} | @code{Builder} | @code{Compiler} | @code{Binder} |
15276   @code{Linker} | @code{Finder}  | @code{Cross_Reference} |
15277   @code{^gnatls^gnatls^} | @code{IDE}     | @code{Pretty_Printer}
15278
15279 package_renaming ::==
15280   @b{package} package_identifier @b{renames}
15281        <project_>simple_name.package_identifier ;
15282
15283 typed_string_declaration ::=
15284   @b{type} <typed_string_>_simple_name @b{is}
15285    ( string_literal @{, string_literal@} );
15286
15287 other_declarative_item ::=
15288   attribute_declaration |
15289   typed_variable_declaration |
15290   variable_declaration |
15291   case_construction
15292
15293 attribute_declaration ::=
15294   full_associative_array_declaration |
15295   @b{for} attribute_designator @b{use} expression ;
15296
15297 full_associative_array_declaration ::=
15298   @b{for} <associative_array_attribute_>simple_name @b{use}
15299   <project_>simple_name [ . <package_>simple_Name ] ' <attribute_>simple_name ;
15300
15301 attribute_designator ::=
15302   <simple_attribute_>simple_name |
15303   <associative_array_attribute_>simple_name ( string_literal )
15304
15305 typed_variable_declaration ::=
15306   <typed_variable_>simple_name : <typed_string_>name :=  string_expression ;
15307
15308 variable_declaration ::=
15309   <variable_>simple_name := expression;
15310
15311 expression ::=
15312   term @{& term@}
15313
15314 term ::=
15315   literal_string |
15316   string_list |
15317   <variable_>name |
15318   external_value |
15319   attribute_reference
15320
15321 string_literal ::=
15322   (same as Ada)
15323
15324 string_list ::=
15325   ( <string_>expression @{ , <string_>expression @} )
15326
15327 external_value ::=
15328   @b{external} ( string_literal [, string_literal] )
15329
15330 attribute_reference ::=
15331   attribute_prefix ' <simple_attribute_>simple_name [ ( literal_string ) ]
15332
15333 attribute_prefix ::=
15334   @b{project} |
15335   <project_>simple_name | package_identifier |
15336   <project_>simple_name . package_identifier
15337
15338 case_construction ::=
15339   @b{case} <typed_variable_>name @b{is}
15340     @{case_item@}
15341   @b{end case} ;
15342
15343 case_item ::=
15344   @b{when} discrete_choice_list =>
15345       @{case_construction | attribute_declaration@}
15346
15347 discrete_choice_list ::=
15348   string_literal @{| string_literal@} |
15349   @b{others}
15350
15351 name ::=
15352   simple_name @{. simple_name@}
15353
15354 simple_name ::=
15355   identifier (same as Ada)
15356
15357 @end smallexample
15358
15359 @node The Cross-Referencing Tools gnatxref and gnatfind
15360 @chapter  The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
15361 @findex gnatxref
15362 @findex gnatfind
15363
15364 @noindent
15365 The compiler generates cross-referencing information (unless
15366 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
15367 This information indicates where in the source each entity is declared and
15368 referenced. Note that entities in package Standard are not included, but
15369 entities in all other predefined units are included in the output.
15370
15371 Before using any of these two tools, you need to compile successfully your
15372 application, so that GNAT gets a chance to generate the cross-referencing
15373 information.
15374
15375 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
15376 information to provide the user with the capability to easily locate the
15377 declaration and references to an entity. These tools are quite similar,
15378 the difference being that @code{gnatfind} is intended for locating
15379 definitions and/or references to a specified entity or entities, whereas
15380 @code{gnatxref} is oriented to generating a full report of all
15381 cross-references.
15382
15383 To use these tools, you must not compile your application using the
15384 @option{-gnatx} switch on the @command{gnatmake} command line
15385 (@pxref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
15386 information will not be generated.
15387
15388 Note: to invoke @code{gnatxref} or @code{gnatfind} with a project file,
15389 use the @code{gnat} driver (see @ref{The GNAT Driver and Project Files}).
15390
15391 @menu
15392 * Switches for gnatxref::
15393 * Switches for gnatfind::
15394 * Project Files for gnatxref and gnatfind::
15395 * Regular Expressions in gnatfind and gnatxref::
15396 * Examples of gnatxref Usage::
15397 * Examples of gnatfind Usage::
15398 @end menu
15399
15400 @node Switches for gnatxref
15401 @section @code{gnatxref} Switches
15402
15403 @noindent
15404 The command invocation for @code{gnatxref} is:
15405 @smallexample
15406 $ gnatxref @ovar{switches} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
15407 @end smallexample
15408
15409 @noindent
15410 where
15411
15412 @table @var
15413 @item sourcefile1
15414 @itemx sourcefile2
15415 identifies the source files for which a report is to be generated. The
15416 ``with''ed units will be processed too. You must provide at least one file.
15417
15418 These file names are considered to be regular expressions, so for instance
15419 specifying @file{source*.adb} is the same as giving every file in the current
15420 directory whose name starts with @file{source} and whose extension is
15421 @file{adb}.
15422
15423 You shouldn't specify any directory name, just base names. @command{gnatxref}
15424 and @command{gnatfind} will be able to locate these files by themselves using
15425 the source path. If you specify directories, no result is produced.
15426
15427 @end table
15428
15429 @noindent
15430 The switches can be:
15431 @table @option
15432 @c !sort!
15433 @item --version
15434 @cindex @option{--version} @command{gnatxref}
15435 Display Copyright and version, then exit disregarding all other options.
15436
15437 @item --help
15438 @cindex @option{--help} @command{gnatxref}
15439 If @option{--version} was not used, display usage, then exit disregarding
15440 all other options.
15441
15442 @item ^-a^/ALL_FILES^
15443 @cindex @option{^-a^/ALL_FILES^} (@command{gnatxref})
15444 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
15445 the read-only files found in the library search path. Otherwise, these files
15446 will be ignored. This option can be used to protect Gnat sources or your own
15447 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
15448 much faster, and their output much smaller. Read-only here refers to access
15449 or permissions status in the file system for the current user.
15450
15451 @item -aIDIR
15452 @cindex @option{-aIDIR} (@command{gnatxref})
15453 When looking for source files also look in directory DIR. The order in which
15454 source file search is undertaken is the same as for @command{gnatmake}.
15455
15456 @item -aODIR
15457 @cindex @option{-aODIR} (@command{gnatxref})
15458 When searching for library and object files, look in directory
15459 DIR. The order in which library files are searched is the same as for
15460 @command{gnatmake}.
15461
15462 @item -nostdinc
15463 @cindex @option{-nostdinc} (@command{gnatxref})
15464 Do not look for sources in the system default directory.
15465
15466 @item -nostdlib
15467 @cindex @option{-nostdlib} (@command{gnatxref})
15468 Do not look for library files in the system default directory.
15469
15470 @item --RTS=@var{rts-path}
15471 @cindex @option{--RTS} (@command{gnatxref})
15472 Specifies the default location of the runtime library. Same meaning as the
15473 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
15474
15475 @item ^-d^/DERIVED_TYPES^
15476 @cindex @option{^-d^/DERIVED_TYPES^} (@command{gnatxref})
15477 If this switch is set @code{gnatxref} will output the parent type
15478 reference for each matching derived types.
15479
15480 @item ^-f^/FULL_PATHNAME^
15481 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatxref})
15482 If this switch is set, the output file names will be preceded by their
15483 directory (if the file was found in the search path). If this switch is
15484 not set, the directory will not be printed.
15485
15486 @item ^-g^/IGNORE_LOCALS^
15487 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatxref})
15488 If this switch is set, information is output only for library-level
15489 entities, ignoring local entities. The use of this switch may accelerate
15490 @code{gnatfind} and @code{gnatxref}.
15491
15492 @item -IDIR
15493 @cindex @option{-IDIR} (@command{gnatxref})
15494 Equivalent to @samp{-aODIR -aIDIR}.
15495
15496 @item -pFILE
15497 @cindex @option{-pFILE} (@command{gnatxref})
15498 Specify a project file to use @xref{Project Files}.
15499 If you need to use the @file{.gpr}
15500 project files, you should use gnatxref through the GNAT driver
15501 (@command{gnat xref -Pproject}).
15502
15503 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
15504 project file in the current directory.
15505
15506 If a project file is either specified or found by the tools, then the content
15507 of the source directory and object directory lines are added as if they
15508 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^}
15509 and @samp{^-aO^OBJECT_SEARCH^}.
15510 @item ^-u^/UNUSED^
15511 Output only unused symbols. This may be really useful if you give your
15512 main compilation unit on the command line, as @code{gnatxref} will then
15513 display every unused entity and 'with'ed package.
15514
15515 @ifclear vms
15516 @item -v
15517 Instead of producing the default output, @code{gnatxref} will generate a
15518 @file{tags} file that can be used by vi. For examples how to use this
15519 feature, see @ref{Examples of gnatxref Usage}. The tags file is output
15520 to the standard output, thus you will have to redirect it to a file.
15521 @end ifclear
15522
15523 @end table
15524
15525 @noindent
15526 All these switches may be in any order on the command line, and may even
15527 appear after the file names. They need not be separated by spaces, thus
15528 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
15529 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
15530
15531 @node Switches for gnatfind
15532 @section @code{gnatfind} Switches
15533
15534 @noindent
15535 The command line for @code{gnatfind} is:
15536
15537 @smallexample
15538 $ gnatfind @ovar{switches} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
15539       @r{[}@var{file1} @var{file2} @dots{}]
15540 @end smallexample
15541
15542 @noindent
15543 where
15544
15545 @table @var
15546 @item pattern
15547 An entity will be output only if it matches the regular expression found
15548 in @var{pattern}, see @ref{Regular Expressions in gnatfind and gnatxref}.
15549
15550 Omitting the pattern is equivalent to specifying @samp{*}, which
15551 will match any entity. Note that if you do not provide a pattern, you
15552 have to provide both a sourcefile and a line.
15553
15554 Entity names are given in Latin-1, with uppercase/lowercase equivalence
15555 for matching purposes. At the current time there is no support for
15556 8-bit codes other than Latin-1, or for wide characters in identifiers.
15557
15558 @item sourcefile
15559 @code{gnatfind} will look for references, bodies or declarations
15560 of symbols referenced in @file{@var{sourcefile}}, at line @var{line}
15561 and column @var{column}. See @ref{Examples of gnatfind Usage}
15562 for syntax examples.
15563
15564 @item line
15565 is a decimal integer identifying the line number containing
15566 the reference to the entity (or entities) to be located.
15567
15568 @item column
15569 is a decimal integer identifying the exact location on the
15570 line of the first character of the identifier for the
15571 entity reference. Columns are numbered from 1.
15572
15573 @item file1 file2 @dots{}
15574 The search will be restricted to these source files. If none are given, then
15575 the search will be done for every library file in the search path.
15576 These file must appear only after the pattern or sourcefile.
15577
15578 These file names are considered to be regular expressions, so for instance
15579 specifying @file{source*.adb} is the same as giving every file in the current
15580 directory whose name starts with @file{source} and whose extension is
15581 @file{adb}.
15582
15583 The location of the spec of the entity will always be displayed, even if it
15584 isn't in one of @file{@var{file1}}, @file{@var{file2}},@enddots{}  The
15585 occurrences of the entity in the separate units of the ones given on the
15586 command line will also be displayed.
15587
15588 Note that if you specify at least one file in this part, @code{gnatfind} may
15589 sometimes not be able to find the body of the subprograms.
15590
15591 @end table
15592
15593 @noindent
15594 At least one of 'sourcefile' or 'pattern' has to be present on
15595 the command line.
15596
15597 The following switches are available:
15598 @table @option
15599 @c !sort!
15600
15601 @cindex @option{--version} @command{gnatfind}
15602 Display Copyright and version, then exit disregarding all other options.
15603
15604 @item --help
15605 @cindex @option{--help} @command{gnatfind}
15606 If @option{--version} was not used, display usage, then exit disregarding
15607 all other options.
15608
15609 @item ^-a^/ALL_FILES^
15610 @cindex @option{^-a^/ALL_FILES^} (@command{gnatfind})
15611 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
15612 the read-only files found in the library search path. Otherwise, these files
15613 will be ignored. This option can be used to protect Gnat sources or your own
15614 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
15615 much faster, and their output much smaller. Read-only here refers to access
15616 or permission status in the file system for the current user.
15617
15618 @item -aIDIR
15619 @cindex @option{-aIDIR} (@command{gnatfind})
15620 When looking for source files also look in directory DIR. The order in which
15621 source file search is undertaken is the same as for @command{gnatmake}.
15622
15623 @item -aODIR
15624 @cindex @option{-aODIR} (@command{gnatfind})
15625 When searching for library and object files, look in directory
15626 DIR. The order in which library files are searched is the same as for
15627 @command{gnatmake}.
15628
15629 @item -nostdinc
15630 @cindex @option{-nostdinc} (@command{gnatfind})
15631 Do not look for sources in the system default directory.
15632
15633 @item -nostdlib
15634 @cindex @option{-nostdlib} (@command{gnatfind})
15635 Do not look for library files in the system default directory.
15636
15637 @item --ext=@var{extension}
15638 @cindex @option{--ext} (@command{gnatfind})
15639 Specify an alternate ali file extension. The default is @code{ali} and other
15640 extensions (e.g. @code{sli} for SPARK library files) may be specified via this
15641 switch. Note that if this switch overrides the default, which means that only
15642 the new extension will be considered.
15643
15644 @item --RTS=@var{rts-path}
15645 @cindex @option{--RTS} (@command{gnatfind})
15646 Specifies the default location of the runtime library. Same meaning as the
15647 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
15648
15649 @item ^-d^/DERIVED_TYPE_INFORMATION^
15650 @cindex @option{^-d^/DERIVED_TYPE_INFORMATION^} (@code{gnatfind})
15651 If this switch is set, then @code{gnatfind} will output the parent type
15652 reference for each matching derived types.
15653
15654 @item ^-e^/EXPRESSIONS^
15655 @cindex @option{^-e^/EXPRESSIONS^} (@command{gnatfind})
15656 By default, @code{gnatfind} accept the simple regular expression set for
15657 @samp{pattern}. If this switch is set, then the pattern will be
15658 considered as full Unix-style regular expression.
15659
15660 @item ^-f^/FULL_PATHNAME^
15661 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatfind})
15662 If this switch is set, the output file names will be preceded by their
15663 directory (if the file was found in the search path). If this switch is
15664 not set, the directory will not be printed.
15665
15666 @item ^-g^/IGNORE_LOCALS^
15667 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatfind})
15668 If this switch is set, information is output only for library-level
15669 entities, ignoring local entities. The use of this switch may accelerate
15670 @code{gnatfind} and @code{gnatxref}.
15671
15672 @item -IDIR
15673 @cindex @option{-IDIR} (@command{gnatfind})
15674 Equivalent to @samp{-aODIR -aIDIR}.
15675
15676 @item -pFILE
15677 @cindex @option{-pFILE} (@command{gnatfind})
15678 Specify a project file (@pxref{Project Files}) to use.
15679 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
15680 project file in the current directory.
15681
15682 If a project file is either specified or found by the tools, then the content
15683 of the source directory and object directory lines are added as if they
15684 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and
15685 @samp{^-aO^/OBJECT_SEARCH^}.
15686
15687 @item ^-r^/REFERENCES^
15688 @cindex @option{^-r^/REFERENCES^} (@command{gnatfind})
15689 By default, @code{gnatfind} will output only the information about the
15690 declaration, body or type completion of the entities. If this switch is
15691 set, the @code{gnatfind} will locate every reference to the entities in
15692 the files specified on the command line (or in every file in the search
15693 path if no file is given on the command line).
15694
15695 @item ^-s^/PRINT_LINES^
15696 @cindex @option{^-s^/PRINT_LINES^} (@command{gnatfind})
15697 If this switch is set, then @code{gnatfind} will output the content
15698 of the Ada source file lines were the entity was found.
15699
15700 @item ^-t^/TYPE_HIERARCHY^
15701 @cindex @option{^-t^/TYPE_HIERARCHY^} (@command{gnatfind})
15702 If this switch is set, then @code{gnatfind} will output the type hierarchy for
15703 the specified type. It act like -d option but recursively from parent
15704 type to parent type. When this switch is set it is not possible to
15705 specify more than one file.
15706
15707 @end table
15708
15709 @noindent
15710 All these switches may be in any order on the command line, and may even
15711 appear after the file names. They need not be separated by spaces, thus
15712 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
15713 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
15714
15715 As stated previously, gnatfind will search in every directory in the
15716 search path. You can force it to look only in the current directory if
15717 you specify @code{*} at the end of the command line.
15718
15719 @node Project Files for gnatxref and gnatfind
15720 @section Project Files for @command{gnatxref} and @command{gnatfind}
15721
15722 @noindent
15723 Project files allow a programmer to specify how to compile its
15724 application, where to find sources, etc.  These files are used
15725 @ifclear vms
15726 primarily by GPS, but they can also be used
15727 @end ifclear
15728 by the two tools
15729 @code{gnatxref} and @code{gnatfind}.
15730
15731 A project file name must end with @file{.gpr}. If a single one is
15732 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
15733 extract the information from it. If multiple project files are found, none of
15734 them is read, and you have to use the @samp{-p} switch to specify the one
15735 you want to use.
15736
15737 The following lines can be included, even though most of them have default
15738 values which can be used in most cases.
15739 The lines can be entered in any order in the file.
15740 Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
15741 each line. If you have multiple instances, only the last one is taken into
15742 account.
15743
15744 @table @code
15745 @item src_dir=DIR
15746 [default: @code{"^./^[]^"}]
15747 specifies a directory where to look for source files. Multiple @code{src_dir}
15748 lines can be specified and they will be searched in the order they
15749 are specified.
15750
15751 @item obj_dir=DIR
15752 [default: @code{"^./^[]^"}]
15753 specifies a directory where to look for object and library files. Multiple
15754 @code{obj_dir} lines can be specified, and they will be searched in the order
15755 they are specified
15756
15757 @item comp_opt=SWITCHES
15758 [default: @code{""}]
15759 creates a variable which can be referred to subsequently by using
15760 the @code{$@{comp_opt@}} notation. This is intended to store the default
15761 switches given to @command{gnatmake} and @command{gcc}.
15762
15763 @item bind_opt=SWITCHES
15764 [default: @code{""}]
15765 creates a variable which can be referred to subsequently by using
15766 the @samp{$@{bind_opt@}} notation. This is intended to store the default
15767 switches given to @command{gnatbind}.
15768
15769 @item link_opt=SWITCHES
15770 [default: @code{""}]
15771 creates a variable which can be referred to subsequently by using
15772 the @samp{$@{link_opt@}} notation. This is intended to store the default
15773 switches given to @command{gnatlink}.
15774
15775 @item main=EXECUTABLE
15776 [default: @code{""}]
15777 specifies the name of the executable for the application. This variable can
15778 be referred to in the following lines by using the @samp{$@{main@}} notation.
15779
15780 @ifset vms
15781 @item comp_cmd=COMMAND
15782 [default: @code{"GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"}]
15783 @end ifset
15784 @ifclear vms
15785 @item comp_cmd=COMMAND
15786 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
15787 @end ifclear
15788 specifies the command used to compile a single file in the application.
15789
15790 @ifset vms
15791 @item make_cmd=COMMAND
15792 [default: @code{"GNAT MAKE $@{main@}
15793 /SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@}
15794 /DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@}
15795 /BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"}]
15796 @end ifset
15797 @ifclear vms
15798 @item make_cmd=COMMAND
15799 [default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
15800 -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
15801 -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
15802 @end ifclear
15803 specifies the command used to recompile the whole application.
15804
15805 @item run_cmd=COMMAND
15806 [default: @code{"$@{main@}"}]
15807 specifies the command used to run the application.
15808
15809 @item debug_cmd=COMMAND
15810 [default: @code{"gdb $@{main@}"}]
15811 specifies the command used to debug the application
15812
15813 @end table
15814
15815 @noindent
15816 @command{gnatxref} and @command{gnatfind} only take into account the
15817 @code{src_dir} and @code{obj_dir} lines, and ignore the others.
15818
15819 @node Regular Expressions in gnatfind and gnatxref
15820 @section  Regular Expressions in @code{gnatfind} and @code{gnatxref}
15821
15822 @noindent
15823 As specified in the section about @command{gnatfind}, the pattern can be a
15824 regular expression. Actually, there are to set of regular expressions
15825 which are recognized by the program:
15826
15827 @table @code
15828 @item globbing patterns
15829 These are the most usual regular expression. They are the same that you
15830 generally used in a Unix shell command line, or in a DOS session.
15831
15832 Here is a more formal grammar:
15833 @smallexample
15834 @group
15835 @iftex
15836 @leftskip=.5cm
15837 @end iftex
15838 regexp ::= term
15839 term   ::= elmt            -- matches elmt
15840 term   ::= elmt elmt       -- concatenation (elmt then elmt)
15841 term   ::= *               -- any string of 0 or more characters
15842 term   ::= ?               -- matches any character
15843 term   ::= [char @{char@}]   -- matches any character listed
15844 term   ::= [char - char]   -- matches any character in range
15845 @end group
15846 @end smallexample
15847
15848 @item full regular expression
15849 The second set of regular expressions is much more powerful. This is the
15850 type of regular expressions recognized by utilities such a @file{grep}.
15851
15852 The following is the form of a regular expression, expressed in Ada
15853 reference manual style BNF is as follows
15854
15855 @smallexample
15856 @iftex
15857 @leftskip=.5cm
15858 @end iftex
15859 @group
15860 regexp ::= term @{| term@}   -- alternation (term or term @dots{})
15861
15862 term ::= item @{item@}       -- concatenation (item then item)
15863
15864 item ::= elmt              -- match elmt
15865 item ::= elmt *            -- zero or more elmt's
15866 item ::= elmt +            -- one or more elmt's
15867 item ::= elmt ?            -- matches elmt or nothing
15868 @end group
15869 @group
15870 elmt ::= nschar            -- matches given character
15871 elmt ::= [nschar @{nschar@}]   -- matches any character listed
15872 elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed
15873 elmt ::= [char - char]     -- matches chars in given range
15874 elmt ::= \ char            -- matches given character
15875 elmt ::= .                 -- matches any single character
15876 elmt ::= ( regexp )        -- parens used for grouping
15877
15878 char ::= any character, including special characters
15879 nschar ::= any character except ()[].*+?^^^
15880 @end group
15881 @end smallexample
15882
15883 Following are a few examples:
15884
15885 @table @samp
15886 @item abcde|fghi
15887 will match any of the two strings @samp{abcde} and @samp{fghi},
15888
15889 @item abc*d
15890 will match any string like @samp{abd}, @samp{abcd}, @samp{abccd},
15891 @samp{abcccd}, and so on,
15892
15893 @item [a-z]+
15894 will match any string which has only lowercase characters in it (and at
15895 least one character.
15896
15897 @end table
15898 @end table
15899
15900 @node Examples of gnatxref Usage
15901 @section Examples of @code{gnatxref} Usage
15902
15903 @subsection General Usage
15904
15905 @noindent
15906 For the following examples, we will consider the following units:
15907
15908 @smallexample @c ada
15909 @group
15910 @cartouche
15911 main.ads:
15912 1: with Bar;
15913 2: package Main is
15914 3:     procedure Foo (B : in Integer);
15915 4:     C : Integer;
15916 5: private
15917 6:     D : Integer;
15918 7: end Main;
15919
15920 main.adb:
15921 1: package body Main is
15922 2:     procedure Foo (B : in Integer) is
15923 3:     begin
15924 4:        C := B;
15925 5:        D := B;
15926 6:        Bar.Print (B);
15927 7:        Bar.Print (C);
15928 8:     end Foo;
15929 9: end Main;
15930
15931 bar.ads:
15932 1: package Bar is
15933 2:     procedure Print (B : Integer);
15934 3: end bar;
15935 @end cartouche
15936 @end group
15937 @end smallexample
15938
15939 @table @code
15940
15941 @noindent
15942 The first thing to do is to recompile your application (for instance, in
15943 that case just by doing a @samp{gnatmake main}, so that GNAT generates
15944 the cross-referencing information.
15945 You can then issue any of the following commands:
15946
15947 @item gnatxref main.adb
15948 @code{gnatxref} generates cross-reference information for main.adb
15949 and every unit 'with'ed by main.adb.
15950
15951 The output would be:
15952 @smallexample
15953 @iftex
15954 @leftskip=0cm
15955 @end iftex
15956 B                                                      Type: Integer
15957   Decl: bar.ads           2:22
15958 B                                                      Type: Integer
15959   Decl: main.ads          3:20
15960   Body: main.adb          2:20
15961   Ref:  main.adb          4:13     5:13     6:19
15962 Bar                                                    Type: Unit
15963   Decl: bar.ads           1:9
15964   Ref:  main.adb          6:8      7:8
15965        main.ads           1:6
15966 C                                                      Type: Integer
15967   Decl: main.ads          4:5
15968   Modi: main.adb          4:8
15969   Ref:  main.adb          7:19
15970 D                                                      Type: Integer
15971   Decl: main.ads          6:5
15972   Modi: main.adb          5:8
15973 Foo                                                    Type: Unit
15974   Decl: main.ads          3:15
15975   Body: main.adb          2:15
15976 Main                                                    Type: Unit
15977   Decl: main.ads          2:9
15978   Body: main.adb          1:14
15979 Print                                                   Type: Unit
15980   Decl: bar.ads           2:15
15981   Ref:  main.adb          6:12     7:12
15982 @end smallexample
15983
15984 @noindent
15985 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
15986 its body is in main.adb, line 1, column 14 and is not referenced any where.
15987
15988 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
15989 it referenced in main.adb, line 6 column 12 and line 7 column 12.
15990
15991 @item gnatxref package1.adb package2.ads
15992 @code{gnatxref} will generates cross-reference information for
15993 package1.adb, package2.ads and any other package 'with'ed by any
15994 of these.
15995
15996 @end table
15997
15998 @ifclear vms
15999 @subsection Using gnatxref with vi
16000
16001 @code{gnatxref} can generate a tags file output, which can be used
16002 directly from @command{vi}. Note that the standard version of @command{vi}
16003 will not work properly with overloaded symbols. Consider using another
16004 free implementation of @command{vi}, such as @command{vim}.
16005
16006 @smallexample
16007 $ gnatxref -v gnatfind.adb > tags
16008 @end smallexample
16009
16010 @noindent
16011 will generate the tags file for @code{gnatfind} itself (if the sources
16012 are in the search path!).
16013
16014 From @command{vi}, you can then use the command @samp{:tag @var{entity}}
16015 (replacing @var{entity} by whatever you are looking for), and vi will
16016 display a new file with the corresponding declaration of entity.
16017 @end ifclear
16018
16019 @node Examples of gnatfind Usage
16020 @section Examples of @code{gnatfind} Usage
16021
16022 @table @code
16023
16024 @item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb
16025 Find declarations for all entities xyz referenced at least once in
16026 main.adb. The references are search in every library file in the search
16027 path.
16028
16029 The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
16030 switch is set)
16031
16032 The output will look like:
16033 @smallexample
16034 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
16035 ^directory/^[directory]^main.adb:24:10: xyz <= body
16036 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
16037 @end smallexample
16038
16039 @noindent
16040 that is to say, one of the entities xyz found in main.adb is declared at
16041 line 12 of main.ads (and its body is in main.adb), and another one is
16042 declared at line 45 of foo.ads
16043
16044 @item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb
16045 This is the same command as the previous one, instead @code{gnatfind} will
16046 display the content of the Ada source file lines.
16047
16048 The output will look like:
16049
16050 @smallexample
16051 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
16052    procedure xyz;
16053 ^directory/^[directory]^main.adb:24:10: xyz <= body
16054    procedure xyz is
16055 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
16056    xyz : Integer;
16057 @end smallexample
16058
16059 @noindent
16060 This can make it easier to find exactly the location your are looking
16061 for.
16062
16063 @item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb
16064 Find references to all entities containing an x that are
16065 referenced on line 123 of main.ads.
16066 The references will be searched only in main.ads and foo.adb.
16067
16068 @item gnatfind main.ads:123
16069 Find declarations and bodies for all entities that are referenced on
16070 line 123 of main.ads.
16071
16072 This is the same as @code{gnatfind "*":main.adb:123}.
16073
16074 @item gnatfind ^mydir/^[mydir]^main.adb:123:45
16075 Find the declaration for the entity referenced at column 45 in
16076 line 123 of file main.adb in directory mydir. Note that it
16077 is usual to omit the identifier name when the column is given,
16078 since the column position identifies a unique reference.
16079
16080 The column has to be the beginning of the identifier, and should not
16081 point to any character in the middle of the identifier.
16082
16083 @end table
16084
16085 @c *********************************
16086 @node The GNAT Pretty-Printer gnatpp
16087 @chapter The GNAT Pretty-Printer @command{gnatpp}
16088 @findex gnatpp
16089 @cindex Pretty-Printer
16090
16091 @noindent
16092 ^The @command{gnatpp} tool^GNAT PRETTY^ is an ASIS-based utility
16093 for source reformatting / pretty-printing.
16094 It takes an Ada source file as input and generates a reformatted
16095 version as output.
16096 You can specify various style directives via switches; e.g.,
16097 identifier case conventions, rules of indentation, and comment layout.
16098
16099 To produce a reformatted file, @command{gnatpp} generates and uses the ASIS
16100 tree for the input source and thus requires the input to be syntactically and
16101 semantically legal.
16102 If this condition is not met, @command{gnatpp} will terminate with an
16103 error message; no output file will be generated.
16104
16105 If the source files presented to @command{gnatpp} contain
16106 preprocessing directives, then the output file will
16107 correspond to the generated source after all
16108 preprocessing is carried out. There is no way
16109 using @command{gnatpp} to obtain pretty printed files that
16110 include the preprocessing directives.
16111
16112 If the compilation unit
16113 contained in the input source depends semantically upon units located
16114 outside the current directory, you have to provide the source search path
16115 when invoking @command{gnatpp}, if these units are contained in files with
16116 names that do not follow the GNAT file naming rules, you have to provide
16117 the configuration file describing the corresponding naming scheme;
16118 see the description of the @command{gnatpp}
16119 switches below. Another possibility is to use a project file and to
16120 call @command{gnatpp} through the @command{gnat} driver
16121
16122 The @command{gnatpp} command has the form
16123
16124 @smallexample
16125 $ gnatpp @ovar{switches} @var{filename}
16126 @end smallexample
16127
16128 @noindent
16129 where
16130 @itemize @bullet
16131 @item
16132 @var{switches} is an optional sequence of switches defining such properties as
16133 the formatting rules, the source search path, and the destination for the
16134 output source file
16135
16136 @item
16137 @var{filename} is the name (including the extension) of the source file to
16138 reformat; ``wildcards'' or several file names on the same gnatpp command are
16139 allowed.  The file name may contain path information; it does not have to
16140 follow the GNAT file naming rules
16141 @end itemize
16142
16143 @menu
16144 * Switches for gnatpp::
16145 * Formatting Rules::
16146 @end menu
16147
16148 @node Switches for gnatpp
16149 @section Switches for @command{gnatpp}
16150
16151 @noindent
16152 The following subsections describe the various switches accepted by
16153 @command{gnatpp}, organized by category.
16154
16155 @ifclear vms
16156 You specify a switch by supplying a name and generally also a value.
16157 In many cases the values for a switch with a given name are incompatible with
16158 each other
16159 (for example the switch that controls the casing of a reserved word may have
16160 exactly one value: upper case, lower case, or
16161 mixed case) and thus exactly one such switch can be in effect for an
16162 invocation of @command{gnatpp}.
16163 If more than one is supplied, the last one is used.
16164 However, some values for the same switch are mutually compatible.
16165 You may supply several such switches to @command{gnatpp}, but then
16166 each must be specified in full, with both the name and the value.
16167 Abbreviated forms (the name appearing once, followed by each value) are
16168 not permitted.
16169 For example, to set
16170 the alignment of the assignment delimiter both in declarations and in
16171 assignment statements, you must write @option{-A2A3}
16172 (or @option{-A2 -A3}), but not @option{-A23}.
16173 @end ifclear
16174
16175 @ifset vms
16176 In many cases the set of options for a given qualifier are incompatible with
16177 each other (for example the qualifier that controls the casing of a reserved
16178 word may have exactly one option, which specifies either upper case, lower
16179 case, or mixed case), and thus exactly one such option can be in effect for
16180 an invocation of @command{gnatpp}.
16181 If more than one is supplied, the last one is used.
16182 However, some qualifiers have options that are mutually compatible,
16183 and then you may then supply several such options when invoking
16184 @command{gnatpp}.
16185 @end ifset
16186
16187 In most cases, it is obvious whether or not the
16188 ^values for a switch with a given name^options for a given qualifier^
16189 are compatible with each other.
16190 When the semantics might not be evident, the summaries below explicitly
16191 indicate the effect.
16192
16193 @menu
16194 * Alignment Control::
16195 * Casing Control::
16196 * Construct Layout Control::
16197 * General Text Layout Control::
16198 * Other Formatting Options::
16199 * Setting the Source Search Path::
16200 * Output File Control::
16201 * Other gnatpp Switches::
16202 @end menu
16203
16204 @node Alignment Control
16205 @subsection Alignment Control
16206 @cindex Alignment control in @command{gnatpp}
16207
16208 @noindent
16209 Programs can be easier to read if certain constructs are vertically aligned.
16210 By default all alignments are set ON.
16211 Through the @option{^-A0^/ALIGN=OFF^} switch you may reset the default to
16212 OFF, and then use one or more of the other
16213 ^@option{-A@var{n}} switches^@option{/ALIGN} options^
16214 to activate alignment for specific constructs.
16215
16216 @table @option
16217 @cindex @option{^-A@var{n}^/ALIGN^} (@command{gnatpp})
16218
16219 @ifset vms
16220 @item /ALIGN=ON
16221 Set all alignments to ON
16222 @end ifset
16223
16224 @item ^-A0^/ALIGN=OFF^
16225 Set all alignments to OFF
16226
16227 @item ^-A1^/ALIGN=COLONS^
16228 Align @code{:} in declarations
16229
16230 @item ^-A2^/ALIGN=DECLARATIONS^
16231 Align @code{:=} in initializations in declarations
16232
16233 @item ^-A3^/ALIGN=STATEMENTS^
16234 Align @code{:=} in assignment statements
16235
16236 @item ^-A4^/ALIGN=ARROWS^
16237 Align @code{=>} in associations
16238
16239 @item ^-A5^/ALIGN=COMPONENT_CLAUSES^
16240 Align @code{at} keywords in the component clauses in record
16241 representation clauses
16242 @end table
16243
16244 @noindent
16245 The @option{^-A^/ALIGN^} switches are mutually compatible; any combination
16246 is allowed.
16247
16248 @node Casing Control
16249 @subsection Casing Control
16250 @cindex Casing control in @command{gnatpp}
16251
16252 @noindent
16253 @command{gnatpp} allows you to specify the casing for reserved words,
16254 pragma names, attribute designators and identifiers.
16255 For identifiers you may define a
16256 general rule for name casing but also override this rule
16257 via a set of dictionary files.
16258
16259 Three types of casing are supported: lower case, upper case, and mixed case.
16260 Lower and upper case are self-explanatory (but since some letters in
16261 Latin1 and other GNAT-supported character sets
16262 exist only in lower-case form, an upper case conversion will have no
16263 effect on them.)
16264 ``Mixed case'' means that the first letter, and also each letter immediately
16265 following an underscore, are converted to their uppercase forms;
16266 all the other letters are converted to their lowercase forms.
16267
16268 @table @option
16269 @cindex @option{^-a@var{x}^/ATTRIBUTE^} (@command{gnatpp})
16270 @item ^-aL^/ATTRIBUTE_CASING=LOWER_CASE^
16271 Attribute designators are lower case
16272
16273 @item ^-aU^/ATTRIBUTE_CASING=UPPER_CASE^
16274 Attribute designators are upper case
16275
16276 @item ^-aM^/ATTRIBUTE_CASING=MIXED_CASE^
16277 Attribute designators are mixed case (this is the default)
16278
16279 @cindex @option{^-k@var{x}^/KEYWORD_CASING^} (@command{gnatpp})
16280 @item ^-kL^/KEYWORD_CASING=LOWER_CASE^
16281 Keywords (technically, these are known in Ada as @emph{reserved words}) are
16282 lower case (this is the default)
16283
16284 @item ^-kU^/KEYWORD_CASING=UPPER_CASE^
16285 Keywords are upper case
16286
16287 @cindex @option{^-n@var{x}^/NAME_CASING^} (@command{gnatpp})
16288 @item ^-nD^/NAME_CASING=AS_DECLARED^
16289 Name casing for defining occurrences are as they appear in the source file
16290 (this is the default)
16291
16292 @item ^-nU^/NAME_CASING=UPPER_CASE^
16293 Names are in upper case
16294
16295 @item ^-nL^/NAME_CASING=LOWER_CASE^
16296 Names are in lower case
16297
16298 @item ^-nM^/NAME_CASING=MIXED_CASE^
16299 Names are in mixed case
16300
16301 @cindex @option{^-p@var{x}^/PRAGMA_CASING^} (@command{gnatpp})
16302 @item ^-pL^/PRAGMA_CASING=LOWER_CASE^
16303 Pragma names are lower case
16304
16305 @item ^-pU^/PRAGMA_CASING=UPPER_CASE^
16306 Pragma names are upper case
16307
16308 @item ^-pM^/PRAGMA_CASING=MIXED_CASE^
16309 Pragma names are mixed case (this is the default)
16310
16311 @item ^-D@var{file}^/DICTIONARY=@var{file}^
16312 @cindex @option{^-D^/DICTIONARY^} (@command{gnatpp})
16313 Use @var{file} as a @emph{dictionary file} that defines
16314 the casing for a set of specified names,
16315 thereby overriding the effect on these names by
16316 any explicit or implicit
16317 ^-n^/NAME_CASING^ switch.
16318 To supply more than one dictionary file,
16319 use ^several @option{-D} switches^a list of files as options^.
16320
16321 @noindent
16322 @option{gnatpp} implicitly uses a @emph{default dictionary file}
16323 to define the casing for the Ada predefined names and
16324 the names declared in the GNAT libraries.
16325
16326 @item ^-D-^/SPECIFIC_CASING^
16327 @cindex @option{^-D-^/SPECIFIC_CASING^} (@command{gnatpp})
16328 Do not use the default dictionary file;
16329 instead, use the casing
16330 defined by a @option{^-n^/NAME_CASING^} switch and any explicit
16331 dictionary file(s)
16332 @end table
16333
16334 @noindent
16335 The structure of a dictionary file, and details on the conventions
16336 used in the default dictionary file, are defined in @ref{Name Casing}.
16337
16338 The @option{^-D-^/SPECIFIC_CASING^} and
16339 @option{^-D@var{file}^/DICTIONARY=@var{file}^} switches are mutually
16340 compatible.
16341
16342 @node Construct Layout Control
16343 @subsection Construct Layout Control
16344 @cindex Layout control in @command{gnatpp}
16345
16346 @noindent
16347 This group of @command{gnatpp} switches controls the layout of comments and
16348 complex syntactic constructs.  See @ref{Formatting Comments} for details
16349 on their effect.
16350
16351 @table @option
16352 @cindex @option{^-c@var{n}^/COMMENTS_LAYOUT^} (@command{gnatpp})
16353 @item ^-c0^/COMMENTS_LAYOUT=UNTOUCHED^
16354 All the comments remain unchanged
16355
16356 @item ^-c1^/COMMENTS_LAYOUT=DEFAULT^
16357 GNAT-style comment line indentation (this is the default).
16358
16359 @item ^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^
16360 Reference-manual comment line indentation.
16361
16362 @item ^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^
16363 GNAT-style comment beginning
16364
16365 @item ^-c4^/COMMENTS_LAYOUT=REFORMAT^
16366 Reformat comment blocks
16367
16368 @item ^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^
16369 Keep unchanged special form comments
16370
16371 Reformat comment blocks
16372
16373 @cindex @option{^-l@var{n}^/CONSTRUCT_LAYOUT^} (@command{gnatpp})
16374 @item ^-l1^/CONSTRUCT_LAYOUT=GNAT^
16375 GNAT-style layout (this is the default)
16376
16377 @item ^-l2^/CONSTRUCT_LAYOUT=COMPACT^
16378 Compact layout
16379
16380 @item ^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^
16381 Uncompact layout
16382
16383 @cindex @option{^-N^/NOTABS^} (@command{gnatpp})
16384 @item ^-N^/NOTABS^
16385 All the VT characters are removed from the comment text. All the HT characters
16386 are expanded with the sequences of space characters to get to the next tab
16387 stops.
16388
16389 @cindex @option{^--no-separate-is^/NO_SEPARATE_IS^} (@command{gnatpp})
16390 @item ^--no-separate-is^/NO_SEPARATE_IS^
16391 Do not place the keyword @code{is} on a separate line in a subprogram body in
16392 case if the spec occupies more then one line.
16393
16394 @cindex @option{^--separate-label^/SEPARATE_LABEL^} (@command{gnatpp})
16395 @item ^--separate-label^/SEPARATE_LABEL^
16396 Place statement label(s) on a separate line, with the following statement
16397 on the next line.
16398
16399 @cindex @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} (@command{gnatpp})
16400 @item ^--separate-loop-then^/SEPARATE_LOOP_THEN^
16401 Place the keyword @code{loop} in FOR and WHILE loop statements and the
16402 keyword @code{then} in IF statements on a separate line.
16403
16404 @cindex @option{^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^} (@command{gnatpp})
16405 @item ^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^
16406 Do not place the keyword @code{loop} in FOR and WHILE loop statements and the
16407 keyword @code{then} in IF statements on a separate line. This option is
16408 incompatible with @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} option.
16409
16410 @cindex @option{^--use-on-new-line^/USE_ON_NEW_LINE^} (@command{gnatpp})
16411 @item ^--use-on-new-line^/USE_ON_NEW_LINE^
16412 Start each USE clause in a context clause from a separate line.
16413
16414 @cindex @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^} (@command{gnatpp})
16415 @item ^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^
16416 Use a separate line for a loop or block statement name, but do not use an extra
16417 indentation level for the statement itself.
16418
16419 @end table
16420
16421 @ifclear vms
16422 @noindent
16423 The @option{-c1} and @option{-c2} switches are incompatible.
16424 The @option{-c3} and @option{-c4} switches are compatible with each other and
16425 also with @option{-c1} and @option{-c2}. The @option{-c0} switch disables all
16426 the other comment formatting switches.
16427
16428 The @option{-l1}, @option{-l2}, and @option{-l3} switches are incompatible.
16429 @end ifclear
16430
16431 @ifset vms
16432 @noindent
16433 For the @option{/COMMENTS_LAYOUT} qualifier:
16434 @itemize @bullet
16435 @item
16436 The @option{DEFAULT} and @option{STANDARD_INDENT} options are incompatible.
16437 @item
16438 The @option{GNAT_BEGINNING} and @option{REFORMAT} options are compatible with
16439 each other and also with @option{DEFAULT} and @option{STANDARD_INDENT}.
16440 @end itemize
16441
16442 @noindent
16443 The @option{GNAT}, @option{COMPACT}, and @option{UNCOMPACT} options for the
16444 @option{/CONSTRUCT_LAYOUT} qualifier are incompatible.
16445 @end ifset
16446
16447 @node General Text Layout Control
16448 @subsection General Text Layout Control
16449
16450 @noindent
16451 These switches allow control over line length and indentation.
16452
16453 @table @option
16454 @item ^-M@var{nnn}^/LINE_LENGTH_MAX=@var{nnn}^
16455 @cindex @option{^-M^/LINE_LENGTH^} (@command{gnatpp})
16456 Maximum line length, @var{nnn} from 32@dots{}256, the default value is 79
16457
16458 @item ^-i@var{nnn}^/INDENTATION_LEVEL=@var{nnn}^
16459 @cindex @option{^-i^/INDENTATION_LEVEL^} (@command{gnatpp})
16460 Indentation level, @var{nnn} from 1@dots{}9, the default value is 3
16461
16462 @item ^-cl@var{nnn}^/CONTINUATION_INDENT=@var{nnn}^
16463 @cindex @option{^-cl^/CONTINUATION_INDENT^} (@command{gnatpp})
16464 Indentation level for continuation lines (relative to the line being
16465 continued), @var{nnn} from 1@dots{}9.
16466 The default
16467 value is one less then the (normal) indentation level, unless the
16468 indentation is set to 1 (in which case the default value for continuation
16469 line indentation is also 1)
16470 @end table
16471
16472 @node Other Formatting Options
16473 @subsection Other Formatting Options
16474
16475 @noindent
16476 These switches control the inclusion of missing end/exit labels, and
16477 the indentation level in @b{case} statements.
16478
16479 @table @option
16480 @item ^-e^/NO_MISSED_LABELS^
16481 @cindex @option{^-e^/NO_MISSED_LABELS^} (@command{gnatpp})
16482 Do not insert missing end/exit labels. An end label is the name of
16483 a construct that may optionally be repeated at the end of the
16484 construct's declaration;
16485 e.g., the names of packages, subprograms, and tasks.
16486 An exit label is the name of a loop that may appear as target
16487 of an exit statement within the loop.
16488 By default, @command{gnatpp} inserts these end/exit labels when
16489 they are absent from the original source. This option suppresses such
16490 insertion, so that the formatted source reflects the original.
16491
16492 @item ^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^
16493 @cindex @option{^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^} (@command{gnatpp})
16494 Insert a Form Feed character after a pragma Page.
16495
16496 @item ^-T@var{nnn}^/MAX_INDENT=@var{nnn}^
16497 @cindex @option{^-T^/MAX_INDENT^} (@command{gnatpp})
16498 Do not use an additional indentation level for @b{case} alternatives
16499 and variants if there are @var{nnn} or more (the default
16500 value is 10).
16501 If @var{nnn} is 0, an additional indentation level is
16502 used for @b{case} alternatives and variants regardless of their number.
16503 @end table
16504
16505 @node Setting the Source Search Path
16506 @subsection Setting the Source Search Path
16507
16508 @noindent
16509 To define the search path for the input source file, @command{gnatpp}
16510 uses the same switches as the GNAT compiler, with the same effects.
16511
16512 @table @option
16513 @item ^-I^/SEARCH=^@var{dir}
16514 @cindex @option{^-I^/SEARCH^} (@code{gnatpp})
16515 The same as the corresponding gcc switch
16516
16517 @item ^-I-^/NOCURRENT_DIRECTORY^
16518 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatpp})
16519 The same as the corresponding gcc switch
16520
16521 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE^=@var{path}
16522 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@code{gnatpp})
16523 The same as the corresponding gcc switch
16524
16525 @item ^--RTS^/RUNTIME_SYSTEM^=@var{path}
16526 @cindex @option{^--RTS^/RUNTIME_SYSTEM^} (@code{gnatpp})
16527 The same as the corresponding gcc switch
16528
16529 @end table
16530
16531 @node Output File Control
16532 @subsection Output File Control
16533
16534 @noindent
16535 By default the output is sent to the file whose name is obtained by appending
16536 the ^@file{.pp}^@file{$PP}^ suffix to the name of the input file
16537 (if the file with this name already exists, it is unconditionally overwritten).
16538 Thus if the input file is @file{^my_ada_proc.adb^MY_ADA_PROC.ADB^} then
16539 @command{gnatpp} will produce @file{^my_ada_proc.adb.pp^MY_ADA_PROC.ADB$PP^}
16540 as output file.
16541 The output may be redirected by the following switches:
16542
16543 @table @option
16544 @item ^-pipe^/STANDARD_OUTPUT^
16545 @cindex @option{^-pipe^/STANDARD_OUTPUT^} (@code{gnatpp})
16546 Send the output to @code{Standard_Output}
16547
16548 @item ^-o @var{output_file}^/OUTPUT=@var{output_file}^
16549 @cindex @option{^-o^/OUTPUT^} (@code{gnatpp})
16550 Write the output into @var{output_file}.
16551 If @var{output_file} already exists, @command{gnatpp} terminates without
16552 reading or processing the input file.
16553
16554 @item ^-of ^/FORCED_OUTPUT=^@var{output_file}
16555 @cindex @option{^-of^/FORCED_OUTPUT^} (@code{gnatpp})
16556 Write the output into @var{output_file}, overwriting the existing file
16557 (if one is present).
16558
16559 @item ^-r^/REPLACE^
16560 @cindex @option{^-r^/REPLACE^} (@code{gnatpp})
16561 Replace the input source file with the reformatted output, and copy the
16562 original input source into the file whose name is obtained by appending the
16563 ^@file{.npp}^@file{$NPP}^ suffix to the name of the input file.
16564 If a file with this name already exists, @command{gnatpp} terminates without
16565 reading or processing the input file.
16566
16567 @item ^-rf^/OVERRIDING_REPLACE^
16568 @cindex @option{^-rf^/OVERRIDING_REPLACE^} (@code{gnatpp})
16569 Like @option{^-r^/REPLACE^} except that if the file with the specified name
16570 already exists, it is overwritten.
16571
16572 @item ^-rnb^/REPLACE_NO_BACKUP^
16573 @cindex @option{^-rnb^/REPLACE_NO_BACKUP^} (@code{gnatpp})
16574 Replace the input source file with the reformatted output without
16575 creating any backup copy of the input source.
16576
16577 @item ^--eol=@var{xxx}^/END_OF_LINE=@var{xxx}^
16578 @cindex @option{^--eol^/END_OF_LINE^} (@code{gnatpp})
16579 Specifies the format of the reformatted output file. The @var{xxx}
16580 ^string specified with the switch^option^ may be either
16581 @itemize @bullet
16582 @item ``@option{^dos^DOS^}'' MS DOS style, lines end with CR LF characters
16583 @item ``@option{^crlf^CRLF^}''
16584 the same as @option{^crlf^CRLF^}
16585 @item ``@option{^unix^UNIX^}'' UNIX style, lines end with LF character
16586 @item ``@option{^lf^LF^}''
16587 the same as @option{^unix^UNIX^}
16588 @end itemize
16589
16590 @item ^-W^/RESULT_ENCODING=^@var{e}
16591 @cindex @option{^-W^/RESULT_ENCODING=^} (@command{gnatpp})
16592 Specify the wide character encoding method used to write the code in the
16593 result file
16594 @var{e} is one of the following:
16595
16596 @itemize @bullet
16597
16598 @item ^h^HEX^
16599 Hex encoding
16600
16601 @item ^u^UPPER^
16602 Upper half encoding
16603
16604 @item ^s^SHIFT_JIS^
16605 Shift/JIS encoding
16606
16607 @item ^e^EUC^
16608 EUC encoding
16609
16610 @item ^8^UTF8^
16611 UTF-8 encoding
16612
16613 @item ^b^BRACKETS^
16614 Brackets encoding (default value)
16615 @end itemize
16616
16617 @end table
16618
16619 @noindent
16620 Options @option{^-pipe^/STANDARD_OUTPUT^},
16621 @option{^-o^/OUTPUT^} and
16622 @option{^-of^/FORCED_OUTPUT^} are allowed only if the call to gnatpp
16623 contains only one file to reformat.
16624 Option
16625 @option{^--eol^/END_OF_LINE^}
16626 and
16627 @option{^-W^/RESULT_ENCODING^}
16628 cannot be used together
16629 with @option{^-pipe^/STANDARD_OUTPUT^} option.
16630
16631 @node Other gnatpp Switches
16632 @subsection Other @code{gnatpp} Switches
16633
16634 @noindent
16635 The additional @command{gnatpp} switches are defined in this subsection.
16636
16637 @table @option
16638 @item ^-files @var{filename}^/FILES=@var{output_file}^
16639 @cindex @option{^-files^/FILES^} (@code{gnatpp})
16640 Take the argument source files from the specified file. This file should be an
16641 ordinary textual file containing file names separated by spaces or
16642 line breaks. You can use this switch more then once in the same call to
16643 @command{gnatpp}. You also can combine this switch with explicit list of
16644 files.
16645
16646 @item ^-v^/VERBOSE^
16647 @cindex @option{^-v^/VERBOSE^} (@code{gnatpp})
16648 Verbose mode;
16649 @command{gnatpp} generates version information and then
16650 a trace of the actions it takes to produce or obtain the ASIS tree.
16651
16652 @item ^-w^/WARNINGS^
16653 @cindex @option{^-w^/WARNINGS^} (@code{gnatpp})
16654 Warning mode;
16655 @command{gnatpp} generates a warning whenever it cannot provide
16656 a required layout in the result source.
16657 @end table
16658
16659 @node Formatting Rules
16660 @section Formatting Rules
16661
16662 @noindent
16663 The following subsections show how @command{gnatpp} treats ``white space'',
16664 comments, program layout, and name casing.
16665 They provide the detailed descriptions of the switches shown above.
16666
16667 @menu
16668 * White Space and Empty Lines::
16669 * Formatting Comments::
16670 * Construct Layout::
16671 * Name Casing::
16672 @end menu
16673
16674 @node White Space and Empty Lines
16675 @subsection White Space and Empty Lines
16676
16677 @noindent
16678 @command{gnatpp} does not have an option to control space characters.
16679 It will add or remove spaces according to the style illustrated by the
16680 examples in the @cite{Ada Reference Manual}.
16681
16682 The only format effectors
16683 (see @cite{Ada Reference Manual}, paragraph 2.1(13))
16684 that will appear in the output file are platform-specific line breaks,
16685 and also format effectors within (but not at the end of) comments.
16686 In particular, each horizontal tab character that is not inside
16687 a comment will be treated as a space and thus will appear in the
16688 output file as zero or more spaces depending on
16689 the reformatting of the line in which it appears.
16690 The only exception is a Form Feed character, which is inserted after a
16691 pragma @code{Page} when @option{-ff} is set.
16692
16693 The output file will contain no lines with trailing ``white space'' (spaces,
16694 format effectors).
16695
16696 Empty lines in the original source are preserved
16697 only if they separate declarations or statements.
16698 In such contexts, a
16699 sequence of two or more empty lines is replaced by exactly one empty line.
16700 Note that a blank line will be removed if it separates two ``comment blocks''
16701 (a comment block is a sequence of whole-line comments).
16702 In order to preserve a visual separation between comment blocks, use an
16703 ``empty comment'' (a line comprising only hyphens) rather than an empty line.
16704 Likewise, if for some reason you wish to have a sequence of empty lines,
16705 use a sequence of empty comments instead.
16706
16707 @node Formatting Comments
16708 @subsection Formatting Comments
16709
16710 @noindent
16711 Comments in Ada code are of two kinds:
16712 @itemize @bullet
16713 @item
16714 a @emph{whole-line comment}, which appears by itself (possibly preceded by
16715 ``white space'') on a line
16716
16717 @item
16718 an @emph{end-of-line comment}, which follows some other Ada lexical element
16719 on the same line.
16720 @end itemize
16721
16722 @noindent
16723 The indentation of a whole-line comment is that of either
16724 the preceding or following line in
16725 the formatted source, depending on switch settings as will be described below.
16726
16727 For an end-of-line comment, @command{gnatpp} leaves the same number of spaces
16728 between the end of the preceding Ada lexical element and the beginning
16729 of the comment as appear in the original source,
16730 unless either the comment has to be split to
16731 satisfy the line length limitation, or else the next line contains a
16732 whole line comment that is considered a continuation of this end-of-line
16733 comment (because it starts at the same position).
16734 In the latter two
16735 cases, the start of the end-of-line comment is moved right to the nearest
16736 multiple of the indentation level.
16737 This may result in a ``line overflow'' (the right-shifted comment extending
16738 beyond the maximum line length), in which case the comment is split as
16739 described below.
16740
16741 There is a difference between @option{^-c1^/COMMENTS_LAYOUT=DEFAULT^}
16742 (GNAT-style comment line indentation)
16743 and @option{^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^}
16744 (reference-manual comment line indentation).
16745 With reference-manual style, a whole-line comment is indented as if it
16746 were a declaration or statement at the same place
16747 (i.e., according to the indentation of the preceding line(s)).
16748 With GNAT style, a whole-line comment that is immediately followed by an
16749 @b{if} or @b{case} statement alternative, a record variant, or the reserved
16750 word @b{begin}, is indented based on the construct that follows it.
16751
16752 For example:
16753 @smallexample @c ada
16754 @cartouche
16755 if A then
16756     null;
16757        -- some comment
16758 else
16759    null;
16760 end if;
16761 @end cartouche
16762 @end smallexample
16763
16764 @noindent
16765 Reference-manual indentation produces:
16766
16767 @smallexample @c ada
16768 @cartouche
16769 if A then
16770    null;
16771    --  some comment
16772 else
16773    null;
16774 end if;
16775 @end cartouche
16776 @end smallexample
16777
16778 @noindent
16779 while GNAT-style indentation produces:
16780
16781 @smallexample @c ada
16782 @cartouche
16783 if A then
16784    null;
16785 --  some comment
16786 else
16787    null;
16788 end if;
16789 @end cartouche
16790 @end smallexample
16791
16792 @noindent
16793 The @option{^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^} switch
16794 (GNAT style comment beginning) has the following
16795 effect:
16796
16797 @itemize @bullet
16798 @item
16799 For each whole-line comment that does not end with two hyphens,
16800 @command{gnatpp} inserts spaces if necessary after the starting two hyphens
16801 to ensure that there are at least two spaces between these hyphens and the
16802 first non-blank character of the comment.
16803 @end itemize
16804
16805 @noindent
16806 For an end-of-line comment, if in the original source the next line is a
16807 whole-line comment that starts at the same position
16808 as the end-of-line comment,
16809 then the whole-line comment (and all whole-line comments
16810 that follow it and that start at the same position)
16811 will start at this position in the output file.
16812
16813 @noindent
16814 That is, if in the original source we have:
16815
16816 @smallexample @c ada
16817 @cartouche
16818 begin
16819 A := B + C;            --  B must be in the range Low1..High1
16820                        --  C must be in the range Low2..High2
16821              --B+C will be in the range Low1+Low2..High1+High2
16822 X := X + 1;
16823 @end cartouche
16824 @end smallexample
16825
16826 @noindent
16827 Then in the formatted source we get
16828
16829 @smallexample @c ada
16830 @cartouche
16831 begin
16832    A := B + C;            --  B must be in the range Low1..High1
16833                           --  C must be in the range Low2..High2
16834    --  B+C will be in the range Low1+Low2..High1+High2
16835    X := X + 1;
16836 @end cartouche
16837 @end smallexample
16838
16839 @noindent
16840 A comment that exceeds the line length limit will be split.
16841 Unless switch
16842 @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} (reformat comment blocks) is set and
16843 the line belongs to a reformattable block, splitting the line generates a
16844 @command{gnatpp} warning.
16845 The @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} switch specifies that whole-line
16846 comments may be reformatted in typical
16847 word processor style (that is, moving words between lines and putting as
16848 many words in a line as possible).
16849
16850 @noindent
16851 The @option{^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^} switch specifies, that comments
16852 that has a special format (that is, a character that is neither a letter nor digit
16853 not white space nor line break immediately following the leading @code{--} of
16854 the comment) should be without any change moved from the argument source
16855 into reformatted source. This switch allows to preserve comments that are used
16856 as a special marks in the code (e.g.@: SPARK annotation).
16857
16858 @node Construct Layout
16859 @subsection Construct Layout
16860
16861 @noindent
16862 In several cases the suggested layout in the Ada Reference Manual includes
16863 an extra level of indentation that many programmers prefer to avoid. The
16864 affected cases include:
16865
16866 @itemize @bullet
16867
16868 @item Record type declaration (RM 3.8)
16869
16870 @item Record representation clause (RM 13.5.1)
16871
16872 @item Loop statement in case if a loop has a statement identifier (RM 5.6)
16873
16874 @item Block statement in case if a block has a statement identifier (RM 5.6)
16875 @end itemize
16876
16877 @noindent
16878 In compact mode (when GNAT style layout or compact layout is set),
16879 the pretty printer uses one level of indentation instead
16880 of two. This is achieved in the record definition and record representation
16881 clause cases by putting the @code{record} keyword on the same line as the
16882 start of the declaration or representation clause, and in the block and loop
16883 case by putting the block or loop header on the same line as the statement
16884 identifier.
16885
16886 @noindent
16887 The difference between GNAT style @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^}
16888 and compact @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^}
16889 layout on the one hand, and uncompact layout
16890 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} on the other hand,
16891 can be illustrated by the following examples:
16892
16893 @iftex
16894 @cartouche
16895 @multitable @columnfractions .5 .5
16896 @item @i{GNAT style, compact layout} @tab @i{Uncompact layout}
16897
16898 @item
16899 @smallexample @c ada
16900 type q is record
16901    a : integer;
16902    b : integer;
16903 end record;
16904 @end smallexample
16905 @tab
16906 @smallexample @c ada
16907 type q is
16908    record
16909       a : integer;
16910       b : integer;
16911    end record;
16912 @end smallexample
16913
16914 @item
16915 @smallexample @c ada
16916 for q use record
16917    a at 0 range  0 .. 31;
16918    b at 4 range  0 .. 31;
16919 end record;
16920 @end smallexample
16921 @tab
16922 @smallexample @c ada
16923 for q use
16924    record
16925       a at 0 range  0 .. 31;
16926       b at 4 range  0 .. 31;
16927    end record;
16928 @end smallexample
16929
16930 @item
16931 @smallexample @c ada
16932 Block : declare
16933    A : Integer := 3;
16934 begin
16935    Proc (A, A);
16936 end Block;
16937 @end smallexample
16938 @tab
16939 @smallexample @c ada
16940 Block :
16941    declare
16942       A : Integer := 3;
16943    begin
16944       Proc (A, A);
16945    end Block;
16946 @end smallexample
16947
16948 @item
16949 @smallexample @c ada
16950 Clear : for J in 1 .. 10 loop
16951    A (J) := 0;
16952 end loop Clear;
16953 @end smallexample
16954 @tab
16955 @smallexample @c ada
16956 Clear :
16957    for J in 1 .. 10 loop
16958       A (J) := 0;
16959    end loop Clear;
16960 @end smallexample
16961 @end multitable
16962 @end cartouche
16963 @end iftex
16964
16965 @ifnottex
16966 @smallexample
16967 @cartouche
16968 GNAT style, compact layout              Uncompact layout
16969
16970 type q is record                        type q is
16971    a : integer;                            record
16972    b : integer;                               a : integer;
16973 end record;                                   b : integer;
16974                                            end record;
16975
16976 for q use record                        for q use
16977    a at 0 range  0 .. 31;                  record
16978    b at 4 range  0 .. 31;                     a at 0 range  0 .. 31;
16979 end record;                                   b at 4 range  0 .. 31;
16980                                            end record;
16981
16982 Block : declare                         Block :
16983    A : Integer := 3;                       declare
16984 begin                                         A : Integer := 3;
16985    Proc (A, A);                            begin
16986 end Block;                                    Proc (A, A);
16987                                            end Block;
16988
16989 Clear : for J in 1 .. 10 loop           Clear :
16990    A (J) := 0;                             for J in 1 .. 10 loop
16991 end loop Clear;                               A (J) := 0;
16992                                            end loop Clear;
16993 @end cartouche
16994 @end smallexample
16995 @end ifnottex
16996
16997 @noindent
16998 A further difference between GNAT style layout and compact layout is that
16999 GNAT style layout inserts empty lines as separation for
17000 compound statements, return statements and bodies.
17001
17002 Note that the layout specified by
17003 @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^}
17004 for named block and loop statements overrides the layout defined by these
17005 constructs by @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^},
17006 @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^} or
17007 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} option.
17008
17009 @node Name Casing
17010 @subsection Name Casing
17011
17012 @noindent
17013 @command{gnatpp} always converts the usage occurrence of a (simple) name to
17014 the same casing as the corresponding defining identifier.
17015
17016 You control the casing for defining occurrences via the
17017 @option{^-n^/NAME_CASING^} switch.
17018 @ifclear vms
17019 With @option{-nD} (``as declared'', which is the default),
17020 @end ifclear
17021 @ifset vms
17022 With @option{/NAME_CASING=AS_DECLARED}, which is the default,
17023 @end ifset
17024 defining occurrences appear exactly as in the source file
17025 where they are declared.
17026 The other ^values for this switch^options for this qualifier^ ---
17027 @option{^-nU^UPPER_CASE^},
17028 @option{^-nL^LOWER_CASE^},
17029 @option{^-nM^MIXED_CASE^} ---
17030 result in
17031 ^upper, lower, or mixed case, respectively^the corresponding casing^.
17032 If @command{gnatpp} changes the casing of a defining
17033 occurrence, it analogously changes the casing of all the
17034 usage occurrences of this name.
17035
17036 If the defining occurrence of a name is not in the source compilation unit
17037 currently being processed by @command{gnatpp}, the casing of each reference to
17038 this name is changed according to the value of the @option{^-n^/NAME_CASING^}
17039 switch (subject to the dictionary file mechanism described below).
17040 Thus @command{gnatpp} acts as though the @option{^-n^/NAME_CASING^} switch
17041 had affected the
17042 casing for the defining occurrence of the name.
17043
17044 Some names may need to be spelled with casing conventions that are not
17045 covered by the upper-, lower-, and mixed-case transformations.
17046 You can arrange correct casing by placing such names in a
17047 @emph{dictionary file},
17048 and then supplying a @option{^-D^/DICTIONARY^} switch.
17049 The casing of names from dictionary files overrides
17050 any @option{^-n^/NAME_CASING^} switch.
17051
17052 To handle the casing of Ada predefined names and the names from GNAT libraries,
17053 @command{gnatpp} assumes a default dictionary file.
17054 The name of each predefined entity is spelled with the same casing as is used
17055 for the entity in the @cite{Ada Reference Manual}.
17056 The name of each entity in the GNAT libraries is spelled with the same casing
17057 as is used in the declaration of that entity.
17058
17059 The @w{@option{^-D-^/SPECIFIC_CASING^}} switch suppresses the use of the
17060 default dictionary file.
17061 Instead, the casing for predefined and GNAT-defined names will be established
17062 by the @option{^-n^/NAME_CASING^} switch or explicit dictionary files.
17063 For example, by default the names @code{Ada.Text_IO} and @code{GNAT.OS_Lib}
17064 will appear as just shown,
17065 even in the presence of a @option{^-nU^/NAME_CASING=UPPER_CASE^} switch.
17066 To ensure that even such names are rendered in uppercase,
17067 additionally supply the @w{@option{^-D-^/SPECIFIC_CASING^}} switch
17068 (or else, less conveniently, place these names in upper case in a dictionary
17069 file).
17070
17071 A dictionary file is
17072 a plain text file; each line in this file can be either a blank line
17073 (containing only space characters and ASCII.HT characters), an Ada comment
17074 line, or the specification of exactly one @emph{casing schema}.
17075
17076 A casing schema is a string that has the following syntax:
17077
17078 @smallexample
17079 @cartouche
17080   @var{casing_schema} ::= @var{identifier} | *@var{simple_identifier}*
17081
17082   @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
17083 @end cartouche
17084 @end smallexample
17085
17086 @noindent
17087 (See @cite{Ada Reference Manual}, Section 2.3) for the definition of the
17088 @var{identifier} lexical element and the @var{letter_or_digit} category.)
17089
17090 The casing schema string can be followed by white space and/or an Ada-style
17091 comment; any amount of white space is allowed before the string.
17092
17093 If a dictionary file is passed as
17094 @ifclear vms
17095 the value of a @option{-D@var{file}} switch
17096 @end ifclear
17097 @ifset vms
17098 an option to the @option{/DICTIONARY} qualifier
17099 @end ifset
17100 then for every
17101 simple name and every identifier, @command{gnatpp} checks if the dictionary
17102 defines the casing for the name or for some of its parts (the term ``subword''
17103 is used below to denote the part of a name which is delimited by ``_'' or by
17104 the beginning or end of the word and which does not contain any ``_'' inside):
17105
17106 @itemize @bullet
17107 @item
17108 if the whole name is in the dictionary, @command{gnatpp} uses for this name
17109 the casing defined by the dictionary; no subwords are checked for this word
17110
17111 @item
17112 for every subword @command{gnatpp} checks if the dictionary contains the
17113 corresponding string of the form @code{*@var{simple_identifier}*},
17114 and if it does, the casing of this @var{simple_identifier} is used
17115 for this subword
17116
17117 @item
17118 if the whole name does not contain any ``_'' inside, and if for this name
17119 the dictionary contains two entries - one of the form @var{identifier},
17120 and another - of the form *@var{simple_identifier}*, then the first one
17121 is applied to define the casing of this name
17122
17123 @item
17124 if more than one dictionary file is passed as @command{gnatpp} switches, each
17125 dictionary adds new casing exceptions and overrides all the existing casing
17126 exceptions set by the previous dictionaries
17127
17128 @item
17129 when @command{gnatpp} checks if the word or subword is in the dictionary,
17130 this check is not case sensitive
17131 @end itemize
17132
17133 @noindent
17134 For example, suppose we have the following source to reformat:
17135
17136 @smallexample @c ada
17137 @cartouche
17138 procedure test is
17139    name1 : integer := 1;
17140    name4_name3_name2 : integer := 2;
17141    name2_name3_name4 : Boolean;
17142    name1_var : Float;
17143 begin
17144    name2_name3_name4 := name4_name3_name2 > name1;
17145 end;
17146 @end cartouche
17147 @end smallexample
17148
17149 @noindent
17150 And suppose we have two dictionaries:
17151
17152 @smallexample
17153 @cartouche
17154 @i{dict1:}
17155    NAME1
17156    *NaMe3*
17157    *Name1*
17158 @end cartouche
17159
17160 @cartouche
17161 @i{dict2:}
17162   *NAME3*
17163 @end cartouche
17164 @end smallexample
17165
17166 @noindent
17167 If @command{gnatpp} is called with the following switches:
17168
17169 @smallexample
17170 @ifclear vms
17171 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
17172 @end ifclear
17173 @ifset vms
17174 @command{gnatpp test.adb /NAME_CASING=MIXED_CASE /DICTIONARY=(dict1, dict2)}
17175 @end ifset
17176 @end smallexample
17177
17178 @noindent
17179 then we will get the following name casing in the @command{gnatpp} output:
17180
17181 @smallexample @c ada
17182 @cartouche
17183 procedure Test is
17184    NAME1             : Integer := 1;
17185    Name4_NAME3_Name2 : Integer := 2;
17186    Name2_NAME3_Name4 : Boolean;
17187    Name1_Var         : Float;
17188 begin
17189    Name2_NAME3_Name4 := Name4_NAME3_Name2 > NAME1;
17190 end Test;
17191 @end cartouche
17192 @end smallexample
17193
17194 @c *********************************
17195 @node The GNAT Metric Tool gnatmetric
17196 @chapter The GNAT Metric Tool @command{gnatmetric}
17197 @findex gnatmetric
17198 @cindex Metric tool
17199
17200 @noindent
17201 ^The @command{gnatmetric} tool^@command{GNAT METRIC}^ is an ASIS-based utility
17202 for computing various program metrics.
17203 It takes an Ada source file as input and generates a file containing the
17204 metrics data as output. Various switches control which
17205 metrics are computed and output.
17206
17207 @command{gnatmetric} generates and uses the ASIS
17208 tree for the input source and thus requires the input to be syntactically and
17209 semantically legal.
17210 If this condition is not met, @command{gnatmetric} will generate
17211 an error message; no metric information for this file will be
17212 computed and reported.
17213
17214 If the compilation unit contained in the input source depends semantically
17215 upon units in files located outside the current directory, you have to provide
17216 the source search path when invoking @command{gnatmetric}.
17217 If it depends semantically upon units that are contained
17218 in files with names that do not follow the GNAT file naming rules, you have to
17219 provide the configuration file describing the corresponding naming scheme (see
17220 the description of the @command{gnatmetric} switches below.)
17221 Alternatively, you may use a project file and invoke @command{gnatmetric}
17222 through the @command{gnat} driver.
17223
17224 The @command{gnatmetric} command has the form
17225
17226 @smallexample
17227 $ gnatmetric @ovar{switches} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
17228 @end smallexample
17229
17230 @noindent
17231 where
17232 @itemize @bullet
17233 @item
17234 @var{switches} specify the metrics to compute and define the destination for
17235 the output
17236
17237 @item
17238 Each @var{filename} is the name (including the extension) of a source
17239 file to process. ``Wildcards'' are allowed, and
17240 the file name may contain path information.
17241 If no @var{filename} is supplied, then the @var{switches} list must contain
17242 at least one
17243 @option{-files} switch (@pxref{Other gnatmetric Switches}).
17244 Including both a @option{-files} switch and one or more
17245 @var{filename} arguments is permitted.
17246
17247 @item
17248 @samp{-cargs @var{gcc_switches}} is a list of switches for
17249 @command{gcc}. They will be passed on to all compiler invocations made by
17250 @command{gnatmetric} to generate the ASIS trees. Here you can provide
17251 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
17252 and use the @option{-gnatec} switch to set the configuration file.
17253 @end itemize
17254
17255 @menu
17256 * Switches for gnatmetric::
17257 @end menu
17258
17259 @node Switches for gnatmetric
17260 @section Switches for @command{gnatmetric}
17261
17262 @noindent
17263 The following subsections describe the various switches accepted by
17264 @command{gnatmetric}, organized by category.
17265
17266 @menu
17267 * Output Files Control::
17268 * Disable Metrics For Local Units::
17269 * Specifying a set of metrics to compute::
17270 * Other gnatmetric Switches::
17271 * Generate project-wide metrics::
17272 @end menu
17273
17274 @node Output Files Control
17275 @subsection Output File Control
17276 @cindex Output file control in @command{gnatmetric}
17277
17278 @noindent
17279 @command{gnatmetric} has two output formats. It can generate a
17280 textual (human-readable) form, and also XML. By default only textual
17281 output is generated.
17282
17283 When generating the output in textual form, @command{gnatmetric} creates
17284 for each Ada source file a corresponding text file
17285 containing the computed metrics, except for the case when the set of metrics
17286 specified by gnatmetric parameters consists only of metrics that are computed
17287 for the whole set of analyzed sources, but not for each Ada source.
17288 By default, this file is placed in the same directory as where the source
17289 file is located, and its name is obtained
17290 by appending the ^@file{.metrix}^@file{$METRIX}^ suffix to the name of the
17291 input file.
17292
17293 All the output information generated in XML format is placed in a single
17294 file. By default this file is placed in the current directory and has the
17295 name ^@file{metrix.xml}^@file{METRIX$XML}^.
17296
17297 Some of the computed metrics are summed over the units passed to
17298 @command{gnatmetric}; for example, the total number of lines of code.
17299 By default this information is sent to @file{stdout}, but a file
17300 can be specified with the @option{-og} switch.
17301
17302 The following switches control the @command{gnatmetric} output:
17303
17304 @table @option
17305 @cindex @option{^-x^/XML^} (@command{gnatmetric})
17306 @item ^-x^/XML^
17307 Generate the XML output
17308
17309 @cindex @option{^-xs^/XSD^} (@command{gnatmetric})
17310 @item ^-xs^/XSD^
17311 Generate the XML output and the XML schema file that describes the structure
17312 of the XML metric report, this schema is assigned to the XML file. The schema
17313 file has the same name as the XML output file with @file{.xml} suffix replaced
17314 with @file{.xsd}
17315
17316 @cindex @option{^-nt^/NO_TEXT^} (@command{gnatmetric})
17317 @item ^-nt^/NO_TEXT^
17318 Do not generate the output in text form (implies @option{^-x^/XML^})
17319
17320 @cindex @option{^-d^/DIRECTORY^} (@command{gnatmetric})
17321 @item ^-d @var{output_dir}^/DIRECTORY=@var{output_dir}^
17322 Put textual files with detailed metrics into @var{output_dir}
17323
17324 @cindex @option{^-o^/SUFFIX_DETAILS^} (@command{gnatmetric})
17325 @item ^-o @var{file_suffix}^/SUFFIX_DETAILS=@var{file_suffix}^
17326 Use @var{file_suffix}, instead of ^@file{.metrix}^@file{$METRIX}^
17327 in the name of the output file.
17328
17329 @cindex @option{^-og^/GLOBAL_OUTPUT^} (@command{gnatmetric})
17330 @item ^-og @var{file_name}^/GLOBAL_OUTPUT=@var{file_name}^
17331 Put global metrics into @var{file_name}
17332
17333 @cindex @option{^-ox^/XML_OUTPUT^} (@command{gnatmetric})
17334 @item ^-ox @var{file_name}^/XML_OUTPUT=@var{file_name}^
17335 Put the XML output into @var{file_name} (also implies @option{^-x^/XML^})
17336
17337 @cindex @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} (@command{gnatmetric})
17338 @item ^-sfn^/SHORT_SOURCE_FILE_NAME^
17339 Use ``short'' source file names in the output.  (The @command{gnatmetric}
17340 output includes the name(s) of the Ada source file(s) from which the metrics
17341 are computed.  By default each name includes the absolute path. The
17342 @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} switch causes @command{gnatmetric}
17343 to exclude all directory information from the file names that are output.)
17344
17345 @end table
17346
17347 @node Disable Metrics For Local Units
17348 @subsection Disable Metrics For Local Units
17349 @cindex Disable Metrics For Local Units in @command{gnatmetric}
17350
17351 @noindent
17352 @command{gnatmetric} relies on the GNAT compilation model @minus{}
17353 one compilation
17354 unit per one source file. It computes line metrics for the whole source
17355 file, and it also computes syntax
17356 and complexity metrics for the file's outermost unit.
17357
17358 By default, @command{gnatmetric} will also compute all metrics for certain
17359 kinds of locally declared program units:
17360
17361 @itemize @bullet
17362 @item
17363 subprogram (and generic subprogram) bodies;
17364
17365 @item
17366 package (and generic package) specs and bodies;
17367
17368 @item
17369 task object and type specifications and bodies;
17370
17371 @item
17372 protected object and type specifications and bodies.
17373 @end itemize
17374
17375 @noindent
17376 These kinds of entities will be referred to as
17377 @emph{eligible local program units}, or simply @emph{eligible local units},
17378 @cindex Eligible local unit (for @command{gnatmetric})
17379 in the discussion below.
17380
17381 Note that a subprogram declaration, generic instantiation,
17382 or renaming declaration only receives metrics
17383 computation when it appear as the outermost entity
17384 in a source file.
17385
17386 Suppression of metrics computation for eligible local units can be
17387 obtained via the following switch:
17388
17389 @table @option
17390 @cindex @option{^-n@var{x}^/SUPPRESS^} (@command{gnatmetric})
17391 @item ^-nolocal^/SUPPRESS=LOCAL_DETAILS^
17392 Do not compute detailed metrics for eligible local program units
17393
17394 @end table
17395
17396 @node Specifying a set of metrics to compute
17397 @subsection Specifying a set of metrics to compute
17398
17399 @noindent
17400 By default all the metrics are computed and reported. The switches
17401 described in this subsection allow you to control, on an individual
17402 basis, whether metrics are computed and
17403 reported. If at least one positive metric
17404 switch is specified (that is, a switch that defines that a given
17405 metric or set of metrics is to be computed), then only
17406 explicitly specified metrics are reported.
17407
17408 @menu
17409 * Line Metrics Control::
17410 * Syntax Metrics Control::
17411 * Complexity Metrics Control::
17412 * Object-Oriented Metrics Control::
17413 @end menu
17414
17415 @node Line Metrics Control
17416 @subsubsection Line Metrics Control
17417 @cindex Line metrics control in @command{gnatmetric}
17418
17419 @noindent
17420 For any (legal) source file, and for each of its
17421 eligible local program units, @command{gnatmetric} computes the following
17422 metrics:
17423
17424 @itemize @bullet
17425 @item
17426 the total number of lines;
17427
17428 @item
17429 the total number of code lines (i.e., non-blank lines that are not comments)
17430
17431 @item
17432 the number of comment lines
17433
17434 @item
17435 the number of code lines containing end-of-line comments;
17436
17437 @item
17438 the comment percentage: the ratio between the number of lines that contain
17439 comments and the number of all non-blank lines, expressed as a percentage;
17440
17441 @item
17442 the number of empty lines and lines containing only space characters and/or
17443 format effectors (blank lines)
17444
17445 @item
17446 the average number of code lines in subprogram bodies, task bodies, entry
17447 bodies and statement sequences in package bodies (this metric is only computed
17448 across the whole set of the analyzed units)
17449
17450 @end itemize
17451
17452 @noindent
17453 @command{gnatmetric} sums the values of the line metrics for all the
17454 files being processed and then generates the cumulative results. The tool
17455 also computes for all the files being processed the average number of code
17456 lines in bodies.
17457
17458 You can use the following switches to select the specific line metrics
17459 to be computed and reported.
17460
17461 @table @option
17462 @cindex @option{^--lines@var{x}^/LINE_COUNT_METRICS^} (@command{gnatmetric})
17463
17464 @ifclear vms
17465 @cindex @option{--no-lines@var{x}}
17466 @end ifclear
17467
17468 @item ^--lines-all^/LINE_COUNT_METRICS=ALL^
17469 Report all the line metrics
17470
17471 @item ^--no-lines-all^/LINE_COUNT_METRICS=NONE^
17472 Do not report any of line metrics
17473
17474 @item ^--lines^/LINE_COUNT_METRICS=ALL_LINES^
17475 Report the number of all lines
17476
17477 @item ^--no-lines^/LINE_COUNT_METRICS=NOALL_LINES^
17478 Do not report the number of all lines
17479
17480 @item ^--lines-code^/LINE_COUNT_METRICS=CODE_LINES^
17481 Report the number of code lines
17482
17483 @item ^--no-lines-code^/LINE_COUNT_METRICS=NOCODE_LINES^
17484 Do not report the number of code lines
17485
17486 @item ^--lines-comment^/LINE_COUNT_METRICS=COMMENT_LINES^
17487 Report the number of comment lines
17488
17489 @item ^--no-lines-comment^/LINE_COUNT_METRICS=NOCOMMENT_LINES^
17490 Do not report the number of comment lines
17491
17492 @item ^--lines-eol-comment^/LINE_COUNT_METRICS=CODE_COMMENT_LINES^
17493 Report the number of code lines containing
17494 end-of-line comments
17495
17496 @item ^--no-lines-eol-comment^/LINE_COUNT_METRICS=NOCODE_COMMENT_LINES^
17497 Do not report the number of code lines containing
17498 end-of-line comments
17499
17500 @item ^--lines-ratio^/LINE_COUNT_METRICS=COMMENT_PERCENTAGE^
17501 Report the comment percentage in the program text
17502
17503 @item ^--no-lines-ratio^/LINE_COUNT_METRICS=NOCOMMENT_PERCENTAGE^
17504 Do not report the comment percentage in the program text
17505
17506 @item ^--lines-blank^/LINE_COUNT_METRICS=BLANK_LINES^
17507 Report the number of blank lines
17508
17509 @item ^--no-lines-blank^/LINE_COUNT_METRICS=NOBLANK_LINES^
17510 Do not report the number of blank lines
17511
17512 @item ^--lines-average^/LINE_COUNT_METRICS=AVERAGE_BODY_LINES^
17513 Report the average number of code lines in subprogram bodies, task bodies,
17514 entry bodies and statement sequences in package bodies. The metric is computed
17515 and reported for the whole set of processed Ada sources only.
17516
17517 @item ^--no-lines-average^/LINE_COUNT_METRICS=NOAVERAGE_BODY_LINES^
17518 Do not report the average number of code lines in subprogram bodies,
17519 task bodies, entry bodies and statement sequences in package bodies.
17520
17521 @end table
17522
17523 @node Syntax Metrics Control
17524 @subsubsection Syntax Metrics Control
17525 @cindex Syntax metrics control in @command{gnatmetric}
17526
17527 @noindent
17528 @command{gnatmetric} computes various syntactic metrics for the
17529 outermost unit and for each eligible local unit:
17530
17531 @table @emph
17532 @item LSLOC (``Logical Source Lines Of Code'')
17533 The total number of declarations and the total number of statements
17534
17535 @item Maximal static nesting level of inner program units
17536 According to
17537 @cite{Ada Reference Manual}, 10.1(1), ``A program unit is either a
17538 package, a task unit, a protected unit, a
17539 protected entry, a generic unit, or an explicitly declared subprogram other
17540 than an enumeration literal.''
17541
17542 @item Maximal nesting level of composite syntactic constructs
17543 This corresponds to the notion of the
17544 maximum nesting level in the GNAT built-in style checks
17545 (@pxref{Style Checking})
17546 @end table
17547
17548 @noindent
17549 For the outermost unit in the file, @command{gnatmetric} additionally computes
17550 the following metrics:
17551
17552 @table @emph
17553 @item Public subprograms
17554 This metric is computed for package specs. It is the
17555 number of subprograms and generic subprograms declared in the visible
17556 part (including the visible part of nested packages, protected objects, and
17557 protected types).
17558
17559 @item All subprograms
17560 This metric is computed for bodies and subunits. The
17561 metric is equal to a total number of subprogram bodies in the compilation
17562 unit.
17563 Neither generic instantiations nor renamings-as-a-body nor body stubs
17564 are counted. Any subprogram body is counted, independently of its nesting
17565 level and enclosing constructs. Generic bodies and bodies of protected
17566 subprograms are counted in the same way as ``usual'' subprogram bodies.
17567
17568 @item Public types
17569 This metric is computed for package specs and
17570 generic package declarations. It is the total number of types
17571 that can be referenced from outside this compilation unit, plus the
17572 number of types from all the visible parts of all the visible generic
17573 packages. Generic formal types are not counted.  Only types, not subtypes,
17574 are included.
17575
17576 @noindent
17577 Along with the total number of public types, the following
17578 types are counted and reported separately:
17579
17580 @itemize @bullet
17581 @item
17582 Abstract types
17583
17584 @item
17585 Root tagged types (abstract, non-abstract, private, non-private). Type
17586 extensions are @emph{not} counted
17587
17588 @item
17589 Private types (including private extensions)
17590
17591 @item
17592 Task types
17593
17594 @item
17595 Protected types
17596
17597 @end itemize
17598
17599 @item All types
17600 This metric is computed for any compilation unit. It is equal to the total
17601 number of the declarations of different types given in the compilation unit.
17602 The private and the corresponding full type declaration are counted as one
17603 type declaration. Incomplete type declarations and generic formal types
17604 are not counted.
17605 No distinction is made among different kinds of types (abstract,
17606 private etc.); the total number of types is computed and reported.
17607
17608 @end table
17609
17610 @noindent
17611 By default, all the syntax metrics are computed and reported. You can use the
17612 following switches to select specific syntax metrics.
17613
17614 @table @option
17615
17616 @cindex @option{^--syntax@var{x}^/SYNTAX_METRICS^} (@command{gnatmetric})
17617
17618 @ifclear vms
17619 @cindex @option{--no-syntax@var{x}} (@command{gnatmetric})
17620 @end ifclear
17621
17622 @item ^--syntax-all^/SYNTAX_METRICS=ALL^
17623 Report all the syntax metrics
17624
17625 @item ^--no-syntax-all^/SYNTAX_METRICS=NONE^
17626 Do not report any of syntax metrics
17627
17628 @item ^--declarations^/SYNTAX_METRICS=DECLARATIONS^
17629 Report the total number of declarations
17630
17631 @item ^--no-declarations^/SYNTAX_METRICS=NODECLARATIONS^
17632 Do not report the total number of declarations
17633
17634 @item ^--statements^/SYNTAX_METRICS=STATEMENTS^
17635 Report the total number of statements
17636
17637 @item ^--no-statements^/SYNTAX_METRICS=NOSTATEMENTS^
17638 Do not report the total number of statements
17639
17640 @item ^--public-subprograms^/SYNTAX_METRICS=PUBLIC_SUBPROGRAMS^
17641 Report the number of public subprograms in a compilation unit
17642
17643 @item ^--no-public-subprograms^/SYNTAX_METRICS=NOPUBLIC_SUBPROGRAMS^
17644 Do not report the number of public subprograms in a compilation unit
17645
17646 @item ^--all-subprograms^/SYNTAX_METRICS=ALL_SUBPROGRAMS^
17647 Report the number of all the subprograms in a compilation unit
17648
17649 @item ^--no-all-subprograms^/SYNTAX_METRICS=NOALL_SUBPROGRAMS^
17650 Do not report the number of all the subprograms in a compilation unit
17651
17652 @item ^--public-types^/SYNTAX_METRICS=PUBLIC_TYPES^
17653 Report the number of public types in a compilation unit
17654
17655 @item ^--no-public-types^/SYNTAX_METRICS=NOPUBLIC_TYPES^
17656 Do not report the number of public types in a compilation unit
17657
17658 @item ^--all-types^/SYNTAX_METRICS=ALL_TYPES^
17659 Report the number of all the types in a compilation unit
17660
17661 @item ^--no-all-types^/SYNTAX_METRICS=NOALL_TYPES^
17662 Do not report the number of all the types in a compilation unit
17663
17664 @item ^--unit-nesting^/SYNTAX_METRICS=UNIT_NESTING^
17665 Report the maximal program unit nesting level
17666
17667 @item ^--no-unit-nesting^/SYNTAX_METRICS=UNIT_NESTING_OFF^
17668 Do not report the maximal program unit nesting level
17669
17670 @item ^--construct-nesting^/SYNTAX_METRICS=CONSTRUCT_NESTING^
17671 Report the maximal construct nesting level
17672
17673 @item ^--no-construct-nesting^/SYNTAX_METRICS=NOCONSTRUCT_NESTING^
17674 Do not report the maximal construct nesting level
17675
17676 @end table
17677
17678 @node Complexity Metrics Control
17679 @subsubsection Complexity Metrics Control
17680 @cindex Complexity metrics control in @command{gnatmetric}
17681
17682 @noindent
17683 For a program unit that is an executable body (a subprogram body (including
17684 generic bodies), task body, entry body or a package body containing
17685 its own statement sequence) @command{gnatmetric} computes the following
17686 complexity metrics:
17687
17688 @itemize @bullet
17689 @item
17690 McCabe cyclomatic complexity;
17691
17692 @item
17693 McCabe essential complexity;
17694
17695 @item
17696 maximal loop nesting level
17697
17698 @end itemize
17699
17700 @noindent
17701 The McCabe complexity metrics are defined
17702 in @url{http://www.mccabe.com/pdf/nist235r.pdf}
17703
17704 According to McCabe, both control statements and short-circuit control forms
17705 should be taken into account when computing cyclomatic complexity. For each
17706 body, we compute three metric values:
17707
17708 @itemize @bullet
17709 @item
17710 the complexity introduced by control
17711 statements only, without taking into account short-circuit forms,
17712
17713 @item
17714 the complexity introduced by short-circuit control forms only, and
17715
17716 @item
17717 the total
17718 cyclomatic complexity, which is the sum of these two values.
17719 @end itemize
17720
17721 @noindent
17722 When computing cyclomatic and essential complexity, @command{gnatmetric} skips
17723 the code in the exception handlers and in all the nested program units.
17724
17725 By default, all the complexity metrics are computed and reported.
17726 For more fine-grained control you can use
17727 the following switches:
17728
17729 @table @option
17730 @cindex @option{^-complexity@var{x}^/COMPLEXITY_METRICS^} (@command{gnatmetric})
17731
17732 @ifclear vms
17733 @cindex @option{--no-complexity@var{x}}
17734 @end ifclear
17735
17736 @item ^--complexity-all^/COMPLEXITY_METRICS=ALL^
17737 Report all the complexity metrics
17738
17739 @item ^--no-complexity-all^/COMPLEXITY_METRICS=NONE^
17740 Do not report any of complexity metrics
17741
17742 @item ^--complexity-cyclomatic^/COMPLEXITY_METRICS=CYCLOMATIC^
17743 Report the McCabe Cyclomatic Complexity
17744
17745 @item ^--no-complexity-cyclomatic^/COMPLEXITY_METRICS=NOCYCLOMATIC^
17746 Do not report the McCabe Cyclomatic Complexity
17747
17748 @item ^--complexity-essential^/COMPLEXITY_METRICS=ESSENTIAL^
17749 Report the Essential Complexity
17750
17751 @item ^--no-complexity-essential^/COMPLEXITY_METRICS=NOESSENTIAL^
17752 Do not report the Essential Complexity
17753
17754 @item ^--loop-nesting^/COMPLEXITY_METRICS=LOOP_NESTING_ON^
17755 Report maximal loop nesting level
17756
17757 @item ^--no-loop-nesting^/COMPLEXITY_METRICS=NOLOOP_NESTING^
17758 Do not report maximal loop nesting level
17759
17760 @item ^--complexity-average^/COMPLEXITY_METRICS=AVERAGE_COMPLEXITY^
17761 Report the average McCabe Cyclomatic Complexity for all the subprogram bodies,
17762 task bodies, entry bodies and statement sequences in package bodies.
17763 The metric is computed and reported for whole set of processed Ada sources
17764 only.
17765
17766 @item ^--no-complexity-average^/COMPLEXITY_METRICS=NOAVERAGE_COMPLEXITY^
17767 Do not report the average McCabe Cyclomatic Complexity for all the subprogram
17768 bodies, task bodies, entry bodies and statement sequences in package bodies
17769
17770 @cindex @option{^-ne^/NO_EXITS_AS_GOTOS^} (@command{gnatmetric})
17771 @item ^-ne^/NO_EXITS_AS_GOTOS^
17772 Do not consider @code{exit} statements as @code{goto}s when
17773 computing Essential Complexity
17774
17775 @item ^--extra-exit-points^/EXTRA_EXIT_POINTS^
17776 Report the extra exit points for subprogram bodies. As an exit point, this
17777 metric counts @code{return} statements and raise statements in case when the
17778 raised exception is not handled in the same body. In case of a function this
17779 metric subtracts 1 from the number of exit points, because a function body
17780 must contain at least one @code{return} statement.
17781
17782 @item ^--no-extra-exit-points^/NOEXTRA_EXIT_POINTS^
17783 Do not report the extra exit points for subprogram bodies
17784 @end table
17785
17786
17787 @node Object-Oriented Metrics Control
17788 @subsubsection Object-Oriented Metrics Control
17789 @cindex Object-Oriented metrics control in @command{gnatmetric}
17790
17791 @noindent
17792 @cindex Coupling metrics (in in @command{gnatmetric})
17793 Coupling metrics are object-oriented metrics that measure the
17794 dependencies between a given class (or a group of classes) and the
17795 ``external world'' (that is, the other classes in the program). In this
17796 subsection the term ``class'' is used in its
17797 traditional object-oriented programming sense
17798 (an instantiable module that contains data and/or method members).
17799 A @emph{category} (of classes)
17800 is a group of closely related classes that are reused and/or
17801 modified together.
17802
17803 A class @code{K}'s @emph{efferent coupling} is the number of classes
17804 that @code{K} depends upon.
17805 A category's efferent coupling is the number of classes outside the
17806 category that the classes inside the category depend upon.
17807
17808 A class @code{K}'s @emph{afferent coupling} is the number of classes
17809 that depend upon @code{K}.
17810 A category's afferent coupling is the number of classes outside the
17811 category that depend on classes belonging to the category.
17812
17813 Ada's implementation of the object-oriented paradigm does not use the
17814 traditional class notion, so the definition of the coupling
17815 metrics for Ada maps the class and class category notions
17816 onto Ada constructs.
17817
17818 For the coupling metrics, several kinds of modules -- a library package,
17819 a library generic package, and a library generic package instantiation --
17820 that define a tagged type or an interface type are
17821 considered to be a class. A category consists of a library package (or
17822 a library generic package) that defines a tagged or an interface type,
17823 together with all its descendant (generic) packages that define tagged
17824 or interface types. For any package counted as a class,
17825 its body and subunits (if any) are considered
17826 together with its spec when counting the dependencies, and coupling
17827 metrics are reported for spec units only. For dependencies
17828 between classes, the Ada semantic dependencies are considered.
17829 For coupling metrics, only dependencies on units that are considered as
17830 classes, are considered.
17831
17832 When computing coupling metrics, @command{gnatmetric} counts only
17833 dependencies between units that are arguments of the gnatmetric call.
17834 Coupling metrics are program-wide (or project-wide) metrics, so to
17835 get a valid result, you should call @command{gnatmetric} for
17836 the whole set of sources that make up your program. It can be done
17837 by calling @command{gnatmetric} from the GNAT driver with @option{-U}
17838 option (see See @ref{The GNAT Driver and Project Files} for details.
17839
17840 By default, all the coupling metrics are disabled. You can use the following
17841 switches to specify the coupling metrics to be computed and reported:
17842
17843 @table @option
17844
17845 @ifclear vms
17846 @cindex @option{--package@var{x}} (@command{gnatmetric})
17847 @cindex @option{--no-package@var{x}} (@command{gnatmetric})
17848 @cindex @option{--category@var{x}} (@command{gnatmetric})
17849 @cindex @option{--no-category@var{x}} (@command{gnatmetric})
17850 @end ifclear
17851
17852 @ifset vms
17853 @cindex @option{/COUPLING_METRICS} (@command{gnatmetric})
17854 @end ifset
17855
17856 @item ^--coupling-all^/COUPLING_METRICS=ALL^
17857 Report all the coupling metrics
17858
17859 @item ^--no-coupling-all^/COUPLING_METRICS=NONE^
17860 Do not report any of  metrics
17861
17862 @item ^--package-efferent-coupling^/COUPLING_METRICS=PACKAGE_EFFERENT^
17863 Report package efferent coupling
17864
17865 @item ^--no-package-efferent-coupling^/COUPLING_METRICS=NOPACKAGE_EFFERENT^
17866 Do not report package efferent coupling
17867
17868 @item ^--package-afferent-coupling^/COUPLING_METRICS=PACKAGE_AFFERENT^
17869 Report package afferent coupling
17870
17871 @item ^--no-package-afferent-coupling^/COUPLING_METRICS=NOPACKAGE_AFFERENT^
17872 Do not report package afferent coupling
17873
17874 @item ^--category-efferent-coupling^/COUPLING_METRICS=CATEGORY_EFFERENT^
17875 Report category efferent coupling
17876
17877 @item ^--no-category-efferent-coupling^/COUPLING_METRICS=NOCATEGORY_EFFERENT^
17878 Do not report category efferent coupling
17879
17880 @item ^--category-afferent-coupling^/COUPLING_METRICS=CATEGORY_AFFERENT^
17881 Report category afferent coupling
17882
17883 @item ^--no-category-afferent-coupling^/COUPLING_METRICS=NOCATEGORY_AFFERENT^
17884 Do not report category afferent coupling
17885
17886 @end table
17887
17888 @node Other gnatmetric Switches
17889 @subsection Other @code{gnatmetric} Switches
17890
17891 @noindent
17892 Additional @command{gnatmetric} switches are as follows:
17893
17894 @table @option
17895 @item ^-files @var{filename}^/FILES=@var{filename}^
17896 @cindex @option{^-files^/FILES^} (@code{gnatmetric})
17897 Take the argument source files from the specified file. This file should be an
17898 ordinary text file containing file names separated by spaces or
17899 line breaks. You can use this switch more then once in the same call to
17900 @command{gnatmetric}. You also can combine this switch with
17901 an explicit list of files.
17902
17903 @item ^-v^/VERBOSE^
17904 @cindex @option{^-v^/VERBOSE^} (@code{gnatmetric})
17905 Verbose mode;
17906 @command{gnatmetric} generates version information and then
17907 a trace of sources being processed.
17908
17909 @item ^-dv^/DEBUG_OUTPUT^
17910 @cindex @option{^-dv^/DEBUG_OUTPUT^} (@code{gnatmetric})
17911 Debug mode;
17912 @command{gnatmetric} generates various messages useful to understand what
17913 happens during the metrics computation
17914
17915 @item ^-q^/QUIET^
17916 @cindex @option{^-q^/QUIET^} (@code{gnatmetric})
17917 Quiet mode.
17918 @end table
17919
17920 @node Generate project-wide metrics
17921 @subsection Generate project-wide metrics
17922
17923 In order to compute metrics on all units of a given project, you can use
17924 the @command{gnat} driver along with the @option{-P} option:
17925 @smallexample
17926    gnat metric -Pproj
17927 @end smallexample
17928
17929 @noindent
17930 If the project @code{proj} depends upon other projects, you can compute
17931 the metrics on the project closure using the @option{-U} option:
17932 @smallexample
17933    gnat metric -Pproj -U
17934 @end smallexample
17935
17936 @noindent
17937 Finally, if not all the units are relevant to a particular main
17938 program in the project closure, you can generate metrics for the set
17939 of units needed to create a given main program (unit closure) using
17940 the @option{-U} option followed by the name of the main unit:
17941 @smallexample
17942    gnat metric -Pproj -U main
17943 @end smallexample
17944
17945
17946 @c ***********************************
17947 @node File Name Krunching Using gnatkr
17948 @chapter File Name Krunching Using @code{gnatkr}
17949 @findex gnatkr
17950
17951 @noindent
17952 This chapter discusses the method used by the compiler to shorten
17953 the default file names chosen for Ada units so that they do not
17954 exceed the maximum length permitted. It also describes the
17955 @code{gnatkr} utility that can be used to determine the result of
17956 applying this shortening.
17957 @menu
17958 * About gnatkr::
17959 * Using gnatkr::
17960 * Krunching Method::
17961 * Examples of gnatkr Usage::
17962 @end menu
17963
17964 @node About gnatkr
17965 @section About @code{gnatkr}
17966
17967 @noindent
17968 The default file naming rule in GNAT
17969 is that the file name must be derived from
17970 the unit name. The exact default rule is as follows:
17971 @itemize @bullet
17972 @item
17973 Take the unit name and replace all dots by hyphens.
17974 @item
17975 If such a replacement occurs in the
17976 second character position of a name, and the first character is
17977 ^@samp{a}, @samp{g}, @samp{s}, or @samp{i}, ^@samp{A}, @samp{G}, @samp{S}, or @samp{I},^
17978 then replace the dot by the character
17979 ^@samp{~} (tilde)^@samp{$} (dollar sign)^
17980 instead of a minus.
17981 @end itemize
17982 The reason for this exception is to avoid clashes
17983 with the standard names for children of System, Ada, Interfaces,
17984 and GNAT, which use the prefixes
17985 ^@samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},^@samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},^
17986 respectively.
17987
17988 The @option{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}}
17989 switch of the compiler activates a ``krunching''
17990 circuit that limits file names to nn characters (where nn is a decimal
17991 integer). For example, using OpenVMS,
17992 where the maximum file name length is
17993 39, the value of nn is usually set to 39, but if you want to generate
17994 a set of files that would be usable if ported to a system with some
17995 different maximum file length, then a different value can be specified.
17996 The default value of 39 for OpenVMS need not be specified.
17997
17998 The @code{gnatkr} utility can be used to determine the krunched name for
17999 a given file, when krunched to a specified maximum length.
18000
18001 @node Using gnatkr
18002 @section Using @code{gnatkr}
18003
18004 @noindent
18005 The @code{gnatkr} command has the form
18006
18007 @ifclear vms
18008 @smallexample
18009 $ gnatkr @var{name} @ovar{length}
18010 @end smallexample
18011 @end ifclear
18012
18013 @ifset vms
18014 @smallexample
18015 $ gnatkr @var{name} /COUNT=nn
18016 @end smallexample
18017 @end ifset
18018
18019 @noindent
18020 @var{name} is the uncrunched file name, derived from the name of the unit
18021 in the standard manner described in the previous section (i.e., in particular
18022 all dots are replaced by hyphens). The file name may or may not have an
18023 extension (defined as a suffix of the form period followed by arbitrary
18024 characters other than period). If an extension is present then it will
18025 be preserved in the output. For example, when krunching @file{hellofile.ads}
18026 to eight characters, the result will be hellofil.ads.
18027
18028 Note: for compatibility with previous versions of @code{gnatkr} dots may
18029 appear in the name instead of hyphens, but the last dot will always be
18030 taken as the start of an extension. So if @code{gnatkr} is given an argument
18031 such as @file{Hello.World.adb} it will be treated exactly as if the first
18032 period had been a hyphen, and for example krunching to eight characters
18033 gives the result @file{hellworl.adb}.
18034
18035 Note that the result is always all lower case (except on OpenVMS where it is
18036 all upper case). Characters of the other case are folded as required.
18037
18038 @var{length} represents the length of the krunched name. The default
18039 when no argument is given is ^8^39^ characters. A length of zero stands for
18040 unlimited, in other words do not chop except for system files where the
18041 implied crunching length is always eight characters.
18042
18043 @noindent
18044 The output is the krunched name. The output has an extension only if the
18045 original argument was a file name with an extension.
18046
18047 @node Krunching Method
18048 @section Krunching Method
18049
18050 @noindent
18051 The initial file name is determined by the name of the unit that the file
18052 contains. The name is formed by taking the full expanded name of the
18053 unit and replacing the separating dots with hyphens and
18054 using ^lowercase^uppercase^
18055 for all letters, except that a hyphen in the second character position is
18056 replaced by a ^tilde^dollar sign^ if the first character is
18057 ^@samp{a}, @samp{i}, @samp{g}, or @samp{s}^@samp{A}, @samp{I}, @samp{G}, or @samp{S}^.
18058 The extension is @code{.ads} for a
18059 spec and @code{.adb} for a body.
18060 Krunching does not affect the extension, but the file name is shortened to
18061 the specified length by following these rules:
18062
18063 @itemize @bullet
18064 @item
18065 The name is divided into segments separated by hyphens, tildes or
18066 underscores and all hyphens, tildes, and underscores are
18067 eliminated. If this leaves the name short enough, we are done.
18068
18069 @item
18070 If the name is too long, the longest segment is located (left-most
18071 if there are two of equal length), and shortened by dropping
18072 its last character. This is repeated until the name is short enough.
18073
18074 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
18075 to fit the name into 8 characters as required by some operating systems.
18076
18077 @smallexample
18078 our-strings-wide_fixed 22
18079 our strings wide fixed 19
18080 our string  wide fixed 18
18081 our strin   wide fixed 17
18082 our stri    wide fixed 16
18083 our stri    wide fixe  15
18084 our str     wide fixe  14
18085 our str     wid  fixe  13
18086 our str     wid  fix   12
18087 ou  str     wid  fix   11
18088 ou  st      wid  fix   10
18089 ou  st      wi   fix   9
18090 ou  st      wi   fi    8
18091 Final file name: oustwifi.adb
18092 @end smallexample
18093
18094 @item
18095 The file names for all predefined units are always krunched to eight
18096 characters. The krunching of these predefined units uses the following
18097 special prefix replacements:
18098
18099 @table @file
18100 @item ada-
18101 replaced by @file{^a^A^-}
18102
18103 @item gnat-
18104 replaced by @file{^g^G^-}
18105
18106 @item interfaces-
18107 replaced by @file{^i^I^-}
18108
18109 @item system-
18110 replaced by @file{^s^S^-}
18111 @end table
18112
18113 These system files have a hyphen in the second character position. That
18114 is why normal user files replace such a character with a
18115 ^tilde^dollar sign^, to
18116 avoid confusion with system file names.
18117
18118 As an example of this special rule, consider
18119 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
18120
18121 @smallexample
18122 ada-strings-wide_fixed 22
18123 a-  strings wide fixed 18
18124 a-  string  wide fixed 17
18125 a-  strin   wide fixed 16
18126 a-  stri    wide fixed 15
18127 a-  stri    wide fixe  14
18128 a-  str     wide fixe  13
18129 a-  str     wid  fixe  12
18130 a-  str     wid  fix   11
18131 a-  st      wid  fix   10
18132 a-  st      wi   fix   9
18133 a-  st      wi   fi    8
18134 Final file name: a-stwifi.adb
18135 @end smallexample
18136 @end itemize
18137
18138 Of course no file shortening algorithm can guarantee uniqueness over all
18139 possible unit names, and if file name krunching is used then it is your
18140 responsibility to ensure that no name clashes occur. The utility
18141 program @code{gnatkr} is supplied for conveniently determining the
18142 krunched name of a file.
18143
18144 @node Examples of gnatkr Usage
18145 @section Examples of @code{gnatkr} Usage
18146
18147 @smallexample
18148 @iftex
18149 @leftskip=0cm
18150 @end iftex
18151 @ifclear vms
18152 $ gnatkr very_long_unit_name.ads      --> velounna.ads
18153 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
18154 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
18155 $ gnatkr grandparent-parent-child     --> grparchi
18156 @end ifclear
18157 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
18158 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
18159 @end smallexample
18160
18161 @node Preprocessing Using gnatprep
18162 @chapter Preprocessing Using @code{gnatprep}
18163 @findex gnatprep
18164
18165 @noindent
18166 This chapter discusses how to use GNAT's @code{gnatprep} utility for simple
18167 preprocessing.
18168 Although designed for use with GNAT, @code{gnatprep} does not depend on any
18169 special GNAT features.
18170 For further discussion of conditional compilation in general, see
18171 @ref{Conditional Compilation}.
18172
18173 @menu
18174 * Preprocessing Symbols::
18175 * Using gnatprep::
18176 * Switches for gnatprep::
18177 * Form of Definitions File::
18178 * Form of Input Text for gnatprep::
18179 @end menu
18180
18181 @node Preprocessing Symbols
18182 @section Preprocessing Symbols
18183
18184 @noindent
18185 Preprocessing symbols are defined in definition files and referred to in
18186 sources to be preprocessed. A Preprocessing symbol is an identifier, following
18187 normal Ada (case-insensitive) rules for its syntax, with the restriction that
18188 all characters need to be in the ASCII set (no accented letters).
18189
18190 @node Using gnatprep
18191 @section Using @code{gnatprep}
18192
18193 @noindent
18194 To call @code{gnatprep} use
18195
18196 @smallexample
18197 $ gnatprep @ovar{switches} @var{infile} @var{outfile} @ovar{deffile}
18198 @end smallexample
18199
18200 @noindent
18201 where
18202 @table @var
18203 @item switches
18204 is an optional sequence of switches as described in the next section.
18205
18206 @item infile
18207 is the full name of the input file, which is an Ada source
18208 file containing preprocessor directives.
18209
18210 @item outfile
18211 is the full name of the output file, which is an Ada source
18212 in standard Ada form. When used with GNAT, this file name will
18213 normally have an ads or adb suffix.
18214
18215 @item deffile
18216 is the full name of a text file containing definitions of
18217 preprocessing symbols to be referenced by the preprocessor. This argument is
18218 optional, and can be replaced by the use of the @option{-D} switch.
18219
18220 @end table
18221
18222 @node Switches for gnatprep
18223 @section Switches for @code{gnatprep}
18224
18225 @table @option
18226 @c !sort!
18227
18228 @item ^-b^/BLANK_LINES^
18229 @cindex @option{^-b^/BLANK_LINES^} (@command{gnatprep})
18230 Causes both preprocessor lines and the lines deleted by
18231 preprocessing to be replaced by blank lines in the output source file,
18232 preserving line numbers in the output file.
18233
18234 @item ^-c^/COMMENTS^
18235 @cindex @option{^-c^/COMMENTS^} (@command{gnatprep})
18236 Causes both preprocessor lines and the lines deleted
18237 by preprocessing to be retained in the output source as comments marked
18238 with the special string @code{"--! "}. This option will result in line numbers
18239 being preserved in the output file.
18240
18241 @item ^-C^/REPLACE_IN_COMMENTS^
18242 @cindex @option{^-C^/REPLACE_IN_COMMENTS^} (@command{gnatprep})
18243 Causes comments to be scanned. Normally comments are ignored by gnatprep.
18244 If this option is specified, then comments are scanned and any $symbol
18245 substitutions performed as in program text. This is particularly useful
18246 when structured comments are used (e.g., when writing programs in the
18247 SPARK dialect of Ada). Note that this switch is not available when
18248 doing integrated preprocessing (it would be useless in this context
18249 since comments are ignored by the compiler in any case).
18250
18251 @item ^-Dsymbol=value^/ASSOCIATE="symbol=value"^
18252 @cindex @option{^-D^/ASSOCIATE^} (@command{gnatprep})
18253 Defines a new preprocessing symbol, associated with value. If no value is given
18254 on the command line, then symbol is considered to be @code{True}. This switch
18255 can be used in place of a definition file.
18256
18257 @ifset vms
18258 @item /REMOVE
18259 @cindex @option{/REMOVE} (@command{gnatprep})
18260 This is the default setting which causes lines deleted by preprocessing
18261 to be entirely removed from the output file.
18262 @end ifset
18263
18264 @item ^-r^/REFERENCE^
18265 @cindex @option{^-r^/REFERENCE^} (@command{gnatprep})
18266 Causes a @code{Source_Reference} pragma to be generated that
18267 references the original input file, so that error messages will use
18268 the file name of this original file. The use of this switch implies
18269 that preprocessor lines are not to be removed from the file, so its
18270 use will force @option{^-b^/BLANK_LINES^} mode if
18271 @option{^-c^/COMMENTS^}
18272 has not been specified explicitly.
18273
18274 Note that if the file to be preprocessed contains multiple units, then
18275 it will be necessary to @code{gnatchop} the output file from
18276 @code{gnatprep}. If a @code{Source_Reference} pragma is present
18277 in the preprocessed file, it will be respected by
18278 @code{gnatchop ^-r^/REFERENCE^}
18279 so that the final chopped files will correctly refer to the original
18280 input source file for @code{gnatprep}.
18281
18282 @item ^-s^/SYMBOLS^
18283 @cindex @option{^-s^/SYMBOLS^} (@command{gnatprep})
18284 Causes a sorted list of symbol names and values to be
18285 listed on the standard output file.
18286
18287 @item ^-u^/UNDEFINED^
18288 @cindex @option{^-u^/UNDEFINED^} (@command{gnatprep})
18289 Causes undefined symbols to be treated as having the value FALSE in the context
18290 of a preprocessor test. In the absence of this option, an undefined symbol in
18291 a @code{#if} or @code{#elsif} test will be treated as an error.
18292
18293 @end table
18294
18295 @ifclear vms
18296 @noindent
18297 Note: if neither @option{-b} nor @option{-c} is present,
18298 then preprocessor lines and
18299 deleted lines are completely removed from the output, unless -r is
18300 specified, in which case -b is assumed.
18301 @end ifclear
18302
18303 @node Form of Definitions File
18304 @section Form of Definitions File
18305
18306 @noindent
18307 The definitions file contains lines of the form
18308
18309 @smallexample
18310 symbol := value
18311 @end smallexample
18312
18313 @noindent
18314 where symbol is a preprocessing symbol, and value is one of the following:
18315
18316 @itemize @bullet
18317 @item
18318 Empty, corresponding to a null substitution
18319 @item
18320 A string literal using normal Ada syntax
18321 @item
18322 Any sequence of characters from the set
18323 (letters, digits, period, underline).
18324 @end itemize
18325
18326 @noindent
18327 Comment lines may also appear in the definitions file, starting with
18328 the usual @code{--},
18329 and comments may be added to the definitions lines.
18330
18331 @node Form of Input Text for gnatprep
18332 @section Form of Input Text for @code{gnatprep}
18333
18334 @noindent
18335 The input text may contain preprocessor conditional inclusion lines,
18336 as well as general symbol substitution sequences.
18337
18338 The preprocessor conditional inclusion commands have the form
18339
18340 @smallexample
18341 @group
18342 @cartouche
18343 #if @i{expression} @r{[}then@r{]}
18344    lines
18345 #elsif @i{expression} @r{[}then@r{]}
18346    lines
18347 #elsif @i{expression} @r{[}then@r{]}
18348    lines
18349 @dots{}
18350 #else
18351    lines
18352 #end if;
18353 @end cartouche
18354 @end group
18355 @end smallexample
18356
18357 @noindent
18358 In this example, @i{expression} is defined by the following grammar:
18359 @smallexample
18360 @i{expression} ::=  <symbol>
18361 @i{expression} ::=  <symbol> = "<value>"
18362 @i{expression} ::=  <symbol> = <symbol>
18363 @i{expression} ::=  <symbol> 'Defined
18364 @i{expression} ::=  not @i{expression}
18365 @i{expression} ::=  @i{expression} and @i{expression}
18366 @i{expression} ::=  @i{expression} or @i{expression}
18367 @i{expression} ::=  @i{expression} and then @i{expression}
18368 @i{expression} ::=  @i{expression} or else @i{expression}
18369 @i{expression} ::=  ( @i{expression} )
18370 @end smallexample
18371
18372 The following restriction exists: it is not allowed to have "and" or "or"
18373 following "not" in the same expression without parentheses. For example, this
18374 is not allowed:
18375
18376 @smallexample
18377    not X or Y
18378 @end smallexample
18379
18380 This should be one of the following:
18381
18382 @smallexample
18383    (not X) or Y
18384    not (X or Y)
18385 @end smallexample
18386
18387 @noindent
18388 For the first test (@i{expression} ::= <symbol>) the symbol must have
18389 either the value true or false, that is to say the right-hand of the
18390 symbol definition must be one of the (case-insensitive) literals
18391 @code{True} or @code{False}. If the value is true, then the
18392 corresponding lines are included, and if the value is false, they are
18393 excluded.
18394
18395 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
18396 the symbol has been defined in the definition file or by a @option{-D}
18397 switch on the command line. Otherwise, the test is false.
18398
18399 The equality tests are case insensitive, as are all the preprocessor lines.
18400
18401 If the symbol referenced is not defined in the symbol definitions file,
18402 then the effect depends on whether or not switch @option{-u}
18403 is specified. If so, then the symbol is treated as if it had the value
18404 false and the test fails. If this switch is not specified, then
18405 it is an error to reference an undefined symbol. It is also an error to
18406 reference a symbol that is defined with a value other than @code{True}
18407 or @code{False}.
18408
18409 The use of the @code{not} operator inverts the sense of this logical test.
18410 The @code{not} operator cannot be combined with the @code{or} or @code{and}
18411 operators, without parentheses. For example, "if not X or Y then" is not
18412 allowed, but "if (not X) or Y then" and "if not (X or Y) then" are.
18413
18414 The @code{then} keyword is optional as shown
18415
18416 The @code{#} must be the first non-blank character on a line, but
18417 otherwise the format is free form. Spaces or tabs may appear between
18418 the @code{#} and the keyword. The keywords and the symbols are case
18419 insensitive as in normal Ada code. Comments may be used on a
18420 preprocessor line, but other than that, no other tokens may appear on a
18421 preprocessor line. Any number of @code{elsif} clauses can be present,
18422 including none at all. The @code{else} is optional, as in Ada.
18423
18424 The @code{#} marking the start of a preprocessor line must be the first
18425 non-blank character on the line, i.e., it must be preceded only by
18426 spaces or horizontal tabs.
18427
18428 Symbol substitution outside of preprocessor lines is obtained by using
18429 the sequence
18430
18431 @smallexample
18432 $symbol
18433 @end smallexample
18434
18435 @noindent
18436 anywhere within a source line, except in a comment or within a
18437 string literal. The identifier
18438 following the @code{$} must match one of the symbols defined in the symbol
18439 definition file, and the result is to substitute the value of the
18440 symbol in place of @code{$symbol} in the output file.
18441
18442 Note that although the substitution of strings within a string literal
18443 is not possible, it is possible to have a symbol whose defined value is
18444 a string literal. So instead of setting XYZ to @code{hello} and writing:
18445
18446 @smallexample
18447 Header : String := "$XYZ";
18448 @end smallexample
18449
18450 @noindent
18451 you should set XYZ to @code{"hello"} and write:
18452
18453 @smallexample
18454 Header : String := $XYZ;
18455 @end smallexample
18456
18457 @noindent
18458 and then the substitution will occur as desired.
18459
18460 @ifset vms
18461 @node The GNAT Run-Time Library Builder gnatlbr
18462 @chapter The GNAT Run-Time Library Builder @code{gnatlbr}
18463 @findex gnatlbr
18464 @cindex Library builder
18465
18466 @noindent
18467 @code{gnatlbr} is a tool for rebuilding the GNAT run time with user
18468 supplied configuration pragmas.
18469
18470 @menu
18471 * Running gnatlbr::
18472 * Switches for gnatlbr::
18473 * Examples of gnatlbr Usage::
18474 @end menu
18475
18476 @node Running gnatlbr
18477 @section Running @code{gnatlbr}
18478
18479 @noindent
18480 The @code{gnatlbr} command has the form
18481
18482 @smallexample
18483 $ GNAT LIBRARY /@r{[}CREATE@r{|}SET@r{|}DELETE@r{]}=directory @r{[}/CONFIG=file@r{]}
18484 @end smallexample
18485
18486 @node Switches for gnatlbr
18487 @section Switches for @code{gnatlbr}
18488
18489 @noindent
18490 @code{gnatlbr} recognizes the following switches:
18491
18492 @table @option
18493 @c !sort!
18494 @item /CREATE=directory
18495 @cindex @code{/CREATE} (@code{gnatlbr})
18496 Create the new run-time library in the specified directory.
18497
18498 @item /SET=directory
18499 @cindex @code{/SET} (@code{gnatlbr})
18500 Make the library in the specified directory the current run-time library.
18501
18502 @item /DELETE=directory
18503 @cindex @code{/DELETE} (@code{gnatlbr})
18504 Delete the run-time library in the specified directory.
18505
18506 @item /CONFIG=file
18507 @cindex @code{/CONFIG} (@code{gnatlbr})
18508 With /CREATE: Use the configuration pragmas in the specified file when
18509 building the library.
18510
18511 With /SET: Use the configuration pragmas in the specified file when
18512 compiling.
18513
18514 @end table
18515
18516 @node Examples of gnatlbr Usage
18517 @section Example of @code{gnatlbr} Usage
18518
18519 @smallexample
18520 Contents of VAXFLOAT.ADC:
18521 pragma Float_Representation (VAX_Float);
18522
18523 $ GNAT LIBRARY /CREATE=[.VAXFLOAT] /CONFIG=VAXFLOAT.ADC
18524
18525 GNAT LIBRARY rebuilds the run-time library in directory [.VAXFLOAT]
18526
18527 @end smallexample
18528 @end ifset
18529
18530 @node The GNAT Library Browser gnatls
18531 @chapter The GNAT Library Browser @code{gnatls}
18532 @findex gnatls
18533 @cindex Library browser
18534
18535 @noindent
18536 @code{gnatls} is a tool that outputs information about compiled
18537 units. It gives the relationship between objects, unit names and source
18538 files. It can also be used to check the source dependencies of a unit
18539 as well as various characteristics.
18540
18541 Note: to invoke @code{gnatls} with a project file, use the @code{gnat}
18542 driver (see @ref{The GNAT Driver and Project Files}).
18543
18544 @menu
18545 * Running gnatls::
18546 * Switches for gnatls::
18547 * Examples of gnatls Usage::
18548 @end menu
18549
18550 @node Running gnatls
18551 @section Running @code{gnatls}
18552
18553 @noindent
18554 The @code{gnatls} command has the form
18555
18556 @smallexample
18557 $ gnatls switches @var{object_or_ali_file}
18558 @end smallexample
18559
18560 @noindent
18561 The main argument is the list of object or @file{ali} files
18562 (@pxref{The Ada Library Information Files})
18563 for which information is requested.
18564
18565 In normal mode, without additional option, @code{gnatls} produces a
18566 four-column listing. Each line represents information for a specific
18567 object. The first column gives the full path of the object, the second
18568 column gives the name of the principal unit in this object, the third
18569 column gives the status of the source and the fourth column gives the
18570 full path of the source representing this unit.
18571 Here is a simple example of use:
18572
18573 @smallexample
18574 $ gnatls *.o
18575 ^./^[]^demo1.o            demo1            DIF demo1.adb
18576 ^./^[]^demo2.o            demo2             OK demo2.adb
18577 ^./^[]^hello.o            h1                OK hello.adb
18578 ^./^[]^instr-child.o      instr.child      MOK instr-child.adb
18579 ^./^[]^instr.o            instr             OK instr.adb
18580 ^./^[]^tef.o              tef              DIF tef.adb
18581 ^./^[]^text_io_example.o  text_io_example   OK text_io_example.adb
18582 ^./^[]^tgef.o             tgef             DIF tgef.adb
18583 @end smallexample
18584
18585 @noindent
18586 The first line can be interpreted as follows: the main unit which is
18587 contained in
18588 object file @file{demo1.o} is demo1, whose main source is in
18589 @file{demo1.adb}. Furthermore, the version of the source used for the
18590 compilation of demo1 has been modified (DIF). Each source file has a status
18591 qualifier which can be:
18592
18593 @table @code
18594 @item OK (unchanged)
18595 The version of the source file used for the compilation of the
18596 specified unit corresponds exactly to the actual source file.
18597
18598 @item MOK (slightly modified)
18599 The version of the source file used for the compilation of the
18600 specified unit differs from the actual source file but not enough to
18601 require recompilation. If you use gnatmake with the qualifier
18602 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
18603 MOK will not be recompiled.
18604
18605 @item DIF (modified)
18606 No version of the source found on the path corresponds to the source
18607 used to build this object.
18608
18609 @item ??? (file not found)
18610 No source file was found for this unit.
18611
18612 @item HID (hidden,  unchanged version not first on PATH)
18613 The version of the source that corresponds exactly to the source used
18614 for compilation has been found on the path but it is hidden by another
18615 version of the same source that has been modified.
18616
18617 @end table
18618
18619 @node Switches for gnatls
18620 @section Switches for @code{gnatls}
18621
18622 @noindent
18623 @code{gnatls} recognizes the following switches:
18624
18625 @table @option
18626 @c !sort!
18627 @cindex @option{--version} @command{gnatls}
18628 Display Copyright and version, then exit disregarding all other options.
18629
18630 @item --help
18631 @cindex @option{--help} @command{gnatls}
18632 If @option{--version} was not used, display usage, then exit disregarding
18633 all other options.
18634
18635 @item ^-a^/ALL_UNITS^
18636 @cindex @option{^-a^/ALL_UNITS^} (@code{gnatls})
18637 Consider all units, including those of the predefined Ada library.
18638 Especially useful with @option{^-d^/DEPENDENCIES^}.
18639
18640 @item ^-d^/DEPENDENCIES^
18641 @cindex @option{^-d^/DEPENDENCIES^} (@code{gnatls})
18642 List sources from which specified units depend on.
18643
18644 @item ^-h^/OUTPUT=OPTIONS^
18645 @cindex @option{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
18646 Output the list of options.
18647
18648 @item ^-o^/OUTPUT=OBJECTS^
18649 @cindex @option{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
18650 Only output information about object files.
18651
18652 @item ^-s^/OUTPUT=SOURCES^
18653 @cindex @option{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
18654 Only output information about source files.
18655
18656 @item ^-u^/OUTPUT=UNITS^
18657 @cindex @option{^-u^/OUTPUT=UNITS^} (@code{gnatls})
18658 Only output information about compilation units.
18659
18660 @item ^-files^/FILES^=@var{file}
18661 @cindex @option{^-files^/FILES^} (@code{gnatls})
18662 Take as arguments the files listed in text file @var{file}.
18663 Text file @var{file} may contain empty lines that are ignored.
18664 Each nonempty line should contain the name of an existing file.
18665 Several such switches may be specified simultaneously.
18666
18667 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
18668 @itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
18669 @itemx ^-I^/SEARCH=^@var{dir}
18670 @itemx  ^-I-^/NOCURRENT_DIRECTORY^
18671 @itemx -nostdinc
18672 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatls})
18673 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatls})
18674 @cindex @option{^-I^/SEARCH^} (@code{gnatls})
18675 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatls})
18676 Source path manipulation. Same meaning as the equivalent @command{gnatmake}
18677 flags (@pxref{Switches for gnatmake}).
18678
18679 @item --RTS=@var{rts-path}
18680 @cindex @option{--RTS} (@code{gnatls})
18681 Specifies the default location of the runtime library. Same meaning as the
18682 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
18683
18684 @item ^-v^/OUTPUT=VERBOSE^
18685 @cindex @option{^-v^/OUTPUT=VERBOSE^} (@code{gnatls})
18686 Verbose mode. Output the complete source, object and project paths. Do not use
18687 the default column layout but instead use long format giving as much as
18688 information possible on each requested units, including special
18689 characteristics such as:
18690
18691 @table @code
18692 @item  Preelaborable
18693 The unit is preelaborable in the Ada sense.
18694
18695 @item No_Elab_Code
18696 No elaboration code has been produced by the compiler for this unit.
18697
18698 @item Pure
18699 The unit is pure in the Ada sense.
18700
18701 @item Elaborate_Body
18702 The unit contains a pragma Elaborate_Body.
18703
18704 @item Remote_Types
18705 The unit contains a pragma Remote_Types.
18706
18707 @item Shared_Passive
18708 The unit contains a pragma Shared_Passive.
18709
18710 @item Predefined
18711 This unit is part of the predefined environment and cannot be modified
18712 by the user.
18713
18714 @item Remote_Call_Interface
18715 The unit contains a pragma Remote_Call_Interface.
18716
18717 @end table
18718
18719 @end table
18720
18721 @node Examples of gnatls Usage
18722 @section Example of @code{gnatls} Usage
18723 @ifclear vms
18724
18725 @noindent
18726 Example of using the verbose switch. Note how the source and
18727 object paths are affected by the -I switch.
18728
18729 @smallexample
18730 $ gnatls -v -I.. demo1.o
18731
18732 GNATLS 5.03w (20041123-34)
18733 Copyright 1997-2004 Free Software Foundation, Inc.
18734
18735 Source Search Path:
18736    <Current_Directory>
18737    ../
18738    /home/comar/local/adainclude/
18739
18740 Object Search Path:
18741    <Current_Directory>
18742    ../
18743    /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
18744
18745 Project Search Path:
18746    <Current_Directory>
18747    /home/comar/local/lib/gnat/
18748
18749 ./demo1.o
18750    Unit =>
18751      Name   => demo1
18752      Kind   => subprogram body
18753      Flags  => No_Elab_Code
18754      Source => demo1.adb    modified
18755 @end smallexample
18756
18757 @noindent
18758 The following is an example of use of the dependency list.
18759 Note the use of the -s switch
18760 which gives a straight list of source files. This can be useful for
18761 building specialized scripts.
18762
18763 @smallexample
18764 $ gnatls -d demo2.o
18765 ./demo2.o   demo2        OK demo2.adb
18766                          OK gen_list.ads
18767                          OK gen_list.adb
18768                          OK instr.ads
18769                          OK instr-child.ads
18770
18771 $ gnatls -d -s -a demo1.o
18772 demo1.adb
18773 /home/comar/local/adainclude/ada.ads
18774 /home/comar/local/adainclude/a-finali.ads
18775 /home/comar/local/adainclude/a-filico.ads
18776 /home/comar/local/adainclude/a-stream.ads
18777 /home/comar/local/adainclude/a-tags.ads
18778 gen_list.ads
18779 gen_list.adb
18780 /home/comar/local/adainclude/gnat.ads
18781 /home/comar/local/adainclude/g-io.ads
18782 instr.ads
18783 /home/comar/local/adainclude/system.ads
18784 /home/comar/local/adainclude/s-exctab.ads
18785 /home/comar/local/adainclude/s-finimp.ads
18786 /home/comar/local/adainclude/s-finroo.ads
18787 /home/comar/local/adainclude/s-secsta.ads
18788 /home/comar/local/adainclude/s-stalib.ads
18789 /home/comar/local/adainclude/s-stoele.ads
18790 /home/comar/local/adainclude/s-stratt.ads
18791 /home/comar/local/adainclude/s-tasoli.ads
18792 /home/comar/local/adainclude/s-unstyp.ads
18793 /home/comar/local/adainclude/unchconv.ads
18794 @end smallexample
18795 @end ifclear
18796
18797 @ifset vms
18798 @smallexample
18799 GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
18800
18801 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
18802 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
18803 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
18804 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
18805 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
18806 demo1.adb
18807 gen_list.ads
18808 gen_list.adb
18809 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
18810 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
18811 instr.ads
18812 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
18813 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
18814 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
18815 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
18816 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
18817 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
18818 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
18819 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
18820 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
18821 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
18822 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
18823 @end smallexample
18824 @end ifset
18825
18826 @node Cleaning Up Using gnatclean
18827 @chapter Cleaning Up Using @code{gnatclean}
18828 @findex gnatclean
18829 @cindex Cleaning tool
18830
18831 @noindent
18832 @code{gnatclean} is a tool that allows the deletion of files produced by the
18833 compiler, binder and linker, including ALI files, object files, tree files,
18834 expanded source files, library files, interface copy source files, binder
18835 generated files and executable files.
18836
18837 @menu
18838 * Running gnatclean::
18839 * Switches for gnatclean::
18840 @c * Examples of gnatclean Usage::
18841 @end menu
18842
18843 @node Running gnatclean
18844 @section Running @code{gnatclean}
18845
18846 @noindent
18847 The @code{gnatclean} command has the form:
18848
18849 @smallexample
18850 $ gnatclean switches @var{names}
18851 @end smallexample
18852
18853 @noindent
18854 @var{names} is a list of source file names. Suffixes @code{.^ads^ADS^} and
18855 @code{^adb^ADB^} may be omitted. If a project file is specified using switch
18856 @code{^-P^/PROJECT_FILE=^}, then @var{names} may be completely omitted.
18857
18858 @noindent
18859 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
18860 if switch @code{^-c^/COMPILER_FILES_ONLY^} is not specified, by the binder and
18861 the linker. In informative-only mode, specified by switch
18862 @code{^-n^/NODELETE^}, the list of files that would have been deleted in
18863 normal mode is listed, but no file is actually deleted.
18864
18865 @node Switches for gnatclean
18866 @section Switches for @code{gnatclean}
18867
18868 @noindent
18869 @code{gnatclean} recognizes the following switches:
18870
18871 @table @option
18872 @c !sort!
18873 @cindex @option{--version} @command{gnatclean}
18874 Display Copyright and version, then exit disregarding all other options.
18875
18876 @item --help
18877 @cindex @option{--help} @command{gnatclean}
18878 If @option{--version} was not used, display usage, then exit disregarding
18879 all other options.
18880
18881 @item ^-c^/COMPILER_FILES_ONLY^
18882 @cindex @option{^-c^/COMPILER_FILES_ONLY^} (@code{gnatclean})
18883 Only attempt to delete the files produced by the compiler, not those produced
18884 by the binder or the linker. The files that are not to be deleted are library
18885 files, interface copy files, binder generated files and executable files.
18886
18887 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
18888 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatclean})
18889 Indicate that ALI and object files should normally be found in directory
18890 @var{dir}.
18891
18892 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
18893 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatclean})
18894 When using project files, if some errors or warnings are detected during
18895 parsing and verbose mode is not in effect (no use of switch
18896 ^-v^/VERBOSE^), then error lines start with the full path name of the project
18897 file, rather than its simple file name.
18898
18899 @item ^-h^/HELP^
18900 @cindex @option{^-h^/HELP^} (@code{gnatclean})
18901 Output a message explaining the usage of @code{^gnatclean^gnatclean^}.
18902
18903 @item ^-n^/NODELETE^
18904 @cindex @option{^-n^/NODELETE^} (@code{gnatclean})
18905 Informative-only mode. Do not delete any files. Output the list of the files
18906 that would have been deleted if this switch was not specified.
18907
18908 @item ^-P^/PROJECT_FILE=^@var{project}
18909 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatclean})
18910 Use project file @var{project}. Only one such switch can be used.
18911 When cleaning a project file, the files produced by the compilation of the
18912 immediate sources or inherited sources of the project files are to be
18913 deleted. This is not depending on the presence or not of executable names
18914 on the command line.
18915
18916 @item ^-q^/QUIET^
18917 @cindex @option{^-q^/QUIET^} (@code{gnatclean})
18918 Quiet output. If there are no errors, do not output anything, except in
18919 verbose mode (switch ^-v^/VERBOSE^) or in informative-only mode
18920 (switch ^-n^/NODELETE^).
18921
18922 @item ^-r^/RECURSIVE^
18923 @cindex @option{^-r^/RECURSIVE^} (@code{gnatclean})
18924 When a project file is specified (using switch ^-P^/PROJECT_FILE=^),
18925 clean all imported and extended project files, recursively. If this switch
18926 is not specified, only the files related to the main project file are to be
18927 deleted. This switch has no effect if no project file is specified.
18928
18929 @item ^-v^/VERBOSE^
18930 @cindex @option{^-v^/VERBOSE^} (@code{gnatclean})
18931 Verbose mode.
18932
18933 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
18934 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (@code{gnatclean})
18935 Indicates the verbosity of the parsing of GNAT project files.
18936 @xref{Switches Related to Project Files}.
18937
18938 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
18939 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (@code{gnatclean})
18940 Indicates that external variable @var{name} has the value @var{value}.
18941 The Project Manager will use this value for occurrences of
18942 @code{external(name)} when parsing the project file.
18943 @xref{Switches Related to Project Files}.
18944
18945 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
18946 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatclean})
18947 When searching for ALI and object files, look in directory
18948 @var{dir}.
18949
18950 @item ^-I^/SEARCH=^@var{dir}
18951 @cindex @option{^-I^/SEARCH^} (@code{gnatclean})
18952 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}}.
18953
18954 @item ^-I-^/NOCURRENT_DIRECTORY^
18955 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatclean})
18956 @cindex Source files, suppressing search
18957 Do not look for ALI or object files in the directory
18958 where @code{gnatclean} was invoked.
18959
18960 @end table
18961
18962 @c @node Examples of gnatclean Usage
18963 @c @section Examples of @code{gnatclean} Usage
18964
18965 @ifclear vms
18966 @node GNAT and Libraries
18967 @chapter GNAT and Libraries
18968 @cindex Library, building, installing, using
18969
18970 @noindent
18971 This chapter describes how to build and use libraries with GNAT, and also shows
18972 how to recompile the GNAT run-time library. You should be familiar with the
18973 Project Manager facility (@pxref{GNAT Project Manager}) before reading this
18974 chapter.
18975
18976 @menu
18977 * Introduction to Libraries in GNAT::
18978 * General Ada Libraries::
18979 * Stand-alone Ada Libraries::
18980 * Rebuilding the GNAT Run-Time Library::
18981 @end menu
18982
18983 @node Introduction to Libraries in GNAT
18984 @section Introduction to Libraries in GNAT
18985
18986 @noindent
18987 A library is, conceptually, a collection of objects which does not have its
18988 own main thread of execution, but rather provides certain services to the
18989 applications that use it. A library can be either statically linked with the
18990 application, in which case its code is directly included in the application,
18991 or, on platforms that support it, be dynamically linked, in which case
18992 its code is shared by all applications making use of this library.
18993
18994 GNAT supports both types of libraries.
18995 In the static case, the compiled code can be provided in different ways. The
18996 simplest approach is to provide directly the set of objects resulting from
18997 compilation of the library source files. Alternatively, you can group the
18998 objects into an archive using whatever commands are provided by the operating
18999 system. For the latter case, the objects are grouped into a shared library.
19000
19001 In the GNAT environment, a library has three types of components:
19002 @itemize @bullet
19003 @item
19004 Source files.
19005 @item
19006 @file{ALI} files.
19007 @xref{The Ada Library Information Files}.
19008 @item
19009 Object files, an archive or a shared library.
19010 @end itemize
19011
19012 @noindent
19013 A GNAT library may expose all its source files, which is useful for
19014 documentation purposes. Alternatively, it may expose only the units needed by
19015 an external user to make use of the library. That is to say, the specs
19016 reflecting the library services along with all the units needed to compile
19017 those specs, which can include generic bodies or any body implementing an
19018 inlined routine. In the case of @emph{stand-alone libraries} those exposed
19019 units are called @emph{interface units} (@pxref{Stand-alone Ada Libraries}).
19020
19021 All compilation units comprising an application, including those in a library,
19022 need to be elaborated in an order partially defined by Ada's semantics. GNAT
19023 computes the elaboration order from the @file{ALI} files and this is why they
19024 constitute a mandatory part of GNAT libraries.
19025 @emph{Stand-alone libraries} are the exception to this rule because a specific
19026 library elaboration routine is produced independently of the application(s)
19027 using the library.
19028
19029 @node General Ada Libraries
19030 @section General Ada Libraries
19031
19032 @menu
19033 * Building a library::
19034 * Installing a library::
19035 * Using a library::
19036 @end menu
19037
19038 @node Building a library
19039 @subsection Building a library
19040
19041 @noindent
19042 The easiest way to build a library is to use the Project Manager,
19043 which supports a special type of project called a @emph{Library Project}
19044 (@pxref{Library Projects}).
19045
19046 A project is considered a library project, when two project-level attributes
19047 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
19048 control different aspects of library configuration, additional optional
19049 project-level attributes can be specified:
19050 @table @code
19051 @item Library_Kind
19052 This attribute controls whether the library is to be static or dynamic
19053
19054 @item Library_Version
19055 This attribute specifies the library version; this value is used
19056 during dynamic linking of shared libraries to determine if the currently
19057 installed versions of the binaries are compatible.
19058
19059 @item Library_Options
19060 @item Library_GCC
19061 These attributes specify additional low-level options to be used during
19062 library generation, and redefine the actual application used to generate
19063 library.
19064 @end table
19065
19066 @noindent
19067 The GNAT Project Manager takes full care of the library maintenance task,
19068 including recompilation of the source files for which objects do not exist
19069 or are not up to date, assembly of the library archive, and installation of
19070 the library (i.e., copying associated source, object and @file{ALI} files
19071 to the specified location).
19072
19073 Here is a simple library project file:
19074 @smallexample @c ada
19075 project My_Lib is
19076    for Source_Dirs use ("src1", "src2");
19077    for Object_Dir use "obj";
19078    for Library_Name use "mylib";
19079    for Library_Dir use "lib";
19080    for Library_Kind use "dynamic";
19081 end My_lib;
19082 @end smallexample
19083
19084 @noindent
19085 and the compilation command to build and install the library:
19086
19087 @smallexample @c ada
19088   $ gnatmake -Pmy_lib
19089 @end smallexample
19090
19091 @noindent
19092 It is not entirely trivial to perform manually all the steps required to
19093 produce a library. We recommend that you use the GNAT Project Manager
19094 for this task. In special cases where this is not desired, the necessary
19095 steps are discussed below.
19096
19097 There are various possibilities for compiling the units that make up the
19098 library: for example with a Makefile (@pxref{Using the GNU make Utility}) or
19099 with a conventional script. For simple libraries, it is also possible to create
19100 a dummy main program which depends upon all the packages that comprise the
19101 interface of the library. This dummy main program can then be given to
19102 @command{gnatmake}, which will ensure that all necessary objects are built.
19103
19104 After this task is accomplished, you should follow the standard procedure
19105 of the underlying operating system to produce the static or shared library.
19106
19107 Here is an example of such a dummy program:
19108 @smallexample @c ada
19109 @group
19110 with My_Lib.Service1;
19111 with My_Lib.Service2;
19112 with My_Lib.Service3;
19113 procedure My_Lib_Dummy is
19114 begin
19115    null;
19116 end;
19117 @end group
19118 @end smallexample
19119
19120 @noindent
19121 Here are the generic commands that will build an archive or a shared library.
19122
19123 @smallexample
19124 # compiling the library
19125 $ gnatmake -c my_lib_dummy.adb
19126
19127 # we don't need the dummy object itself
19128 $ rm my_lib_dummy.o my_lib_dummy.ali
19129
19130 # create an archive with the remaining objects
19131 $ ar rc libmy_lib.a *.o
19132 # some systems may require "ranlib" to be run as well
19133
19134 # or create a shared library
19135 $ gcc -shared -o libmy_lib.so *.o
19136 # some systems may require the code to have been compiled with -fPIC
19137
19138 # remove the object files that are now in the library
19139 $ rm *.o
19140
19141 # Make the ALI files read-only so that gnatmake will not try to
19142 # regenerate the objects that are in the library
19143 $ chmod -w *.ali
19144 @end smallexample
19145
19146 @noindent
19147 Please note that the library must have a name of the form @file{lib@var{xxx}.a}
19148 or @file{lib@var{xxx}.so} (or @file{lib@var{xxx}.dll} on Windows) in order to
19149 be accessed by the directive @option{-l@var{xxx}} at link time.
19150
19151 @node Installing a library
19152 @subsection Installing a library
19153 @cindex @code{ADA_PROJECT_PATH}
19154 @cindex @code{GPR_PROJECT_PATH}
19155
19156 @noindent
19157 If you use project files, library installation is part of the library build
19158 process. Thus no further action is needed in order to make use of the
19159 libraries that are built as part of the general application build. A usable
19160 version of the library is installed in the directory specified by the
19161 @code{Library_Dir} attribute of the library project file.
19162
19163 You may want to install a library in a context different from where the library
19164 is built. This situation arises with third party suppliers, who may want
19165 to distribute a library in binary form where the user is not expected to be
19166 able to recompile the library. The simplest option in this case is to provide
19167 a project file slightly different from the one used to build the library, by
19168 using the @code{externally_built} attribute. For instance, the project
19169 file used to build the library in the previous section can be changed into the
19170 following one when the library is installed:
19171
19172 @smallexample @c projectfile
19173 project My_Lib is
19174    for Source_Dirs use ("src1", "src2");
19175    for Library_Name use "mylib";
19176    for Library_Dir use "lib";
19177    for Library_Kind use "dynamic";
19178    for Externally_Built use "true";
19179 end My_lib;
19180 @end smallexample
19181
19182 @noindent
19183 This project file assumes that the directories @file{src1},
19184 @file{src2}, and @file{lib} exist in
19185 the directory containing the project file. The @code{externally_built}
19186 attribute makes it clear to the GNAT builder that it should not attempt to
19187 recompile any of the units from this library. It allows the library provider to
19188 restrict the source set to the minimum necessary for clients to make use of the
19189 library as described in the first section of this chapter. It is the
19190 responsibility of the library provider to install the necessary sources, ALI
19191 files and libraries in the directories mentioned in the project file. For
19192 convenience, the user's library project file should be installed in a location
19193 that will be searched automatically by the GNAT
19194 builder. These are the directories referenced in the @env{GPR_PROJECT_PATH}
19195 environment variable (@pxref{Importing Projects}), and also the default GNAT
19196 library location that can be queried with @command{gnatls -v} and is usually of
19197 the form $gnat_install_root/lib/gnat.
19198
19199 When project files are not an option, it is also possible, but not recommended,
19200 to install the library so that the sources needed to use the library are on the
19201 Ada source path and the ALI files & libraries be on the Ada Object path (see
19202 @ref{Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
19203 administrator can place general-purpose libraries in the default compiler
19204 paths, by specifying the libraries' location in the configuration files
19205 @file{ada_source_path} and @file{ada_object_path}. These configuration files
19206 must be located in the GNAT installation tree at the same place as the gcc spec
19207 file. The location of the gcc spec file can be determined as follows:
19208 @smallexample
19209 $ gcc -v
19210 @end smallexample
19211
19212 @noindent
19213 The configuration files mentioned above have a simple format: each line
19214 must contain one unique directory name.
19215 Those names are added to the corresponding path
19216 in their order of appearance in the file. The names can be either absolute
19217 or relative; in the latter case, they are relative to where theses files
19218 are located.
19219
19220 The files @file{ada_source_path} and @file{ada_object_path} might not be
19221 present in a
19222 GNAT installation, in which case, GNAT will look for its run-time library in
19223 the directories @file{adainclude} (for the sources) and @file{adalib} (for the
19224 objects and @file{ALI} files). When the files exist, the compiler does not
19225 look in @file{adainclude} and @file{adalib}, and thus the
19226 @file{ada_source_path} file
19227 must contain the location for the GNAT run-time sources (which can simply
19228 be @file{adainclude}). In the same way, the @file{ada_object_path} file must
19229 contain the location for the GNAT run-time objects (which can simply
19230 be @file{adalib}).
19231
19232 You can also specify a new default path to the run-time library at compilation
19233 time with the switch @option{--RTS=rts-path}. You can thus choose / change
19234 the run-time library you want your program to be compiled with. This switch is
19235 recognized by @command{gcc}, @command{gnatmake}, @command{gnatbind},
19236 @command{gnatls}, @command{gnatfind} and @command{gnatxref}.
19237
19238 It is possible to install a library before or after the standard GNAT
19239 library, by reordering the lines in the configuration files. In general, a
19240 library must be installed before the GNAT library if it redefines
19241 any part of it.
19242
19243 @node Using a library
19244 @subsection Using a library
19245
19246 @noindent Once again, the project facility greatly simplifies the use of
19247 libraries. In this context, using a library is just a matter of adding a
19248 @code{with} clause in the user project. For instance, to make use of the
19249 library @code{My_Lib} shown in examples in earlier sections, you can
19250 write:
19251
19252 @smallexample @c projectfile
19253 with "my_lib";
19254 project My_Proj is
19255   @dots{}
19256 end My_Proj;
19257 @end smallexample
19258
19259 Even if you have a third-party, non-Ada library, you can still use GNAT's
19260 Project Manager facility to provide a wrapper for it. For example, the
19261 following project, when @code{with}ed by your main project, will link with the
19262 third-party library @file{liba.a}:
19263
19264 @smallexample @c projectfile
19265 @group
19266 project Liba is
19267    for Externally_Built use "true";
19268    for Source_Files use ();
19269    for Library_Dir use "lib";
19270    for Library_Name use "a";
19271    for Library_Kind use "static";
19272 end Liba;
19273 @end group
19274 @end smallexample
19275 This is an alternative to the use of @code{pragma Linker_Options}. It is
19276 especially interesting in the context of systems with several interdependent
19277 static libraries where finding a proper linker order is not easy and best be
19278 left to the tools having visibility over project dependence information.
19279
19280 @noindent
19281 In order to use an Ada library manually, you need to make sure that this
19282 library is on both your source and object path
19283 (see @ref{Search Paths and the Run-Time Library (RTL)}
19284 and @ref{Search Paths for gnatbind}). Furthermore, when the objects are grouped
19285 in an archive or a shared library, you need to specify the desired
19286 library at link time.
19287
19288 For example, you can use the library @file{mylib} installed in
19289 @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
19290
19291 @smallexample
19292 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
19293   -largs -lmy_lib
19294 @end smallexample
19295
19296 @noindent
19297 This can be expressed more simply:
19298 @smallexample
19299 $ gnatmake my_appl
19300 @end smallexample
19301 @noindent
19302 when the following conditions are met:
19303 @itemize @bullet
19304 @item
19305 @file{/dir/my_lib_src} has been added by the user to the environment
19306 variable @env{ADA_INCLUDE_PATH}, or by the administrator to the file
19307 @file{ada_source_path}
19308 @item
19309 @file{/dir/my_lib_obj} has been added by the user to the environment
19310 variable @env{ADA_OBJECTS_PATH}, or by the administrator to the file
19311 @file{ada_object_path}
19312 @item
19313 a pragma @code{Linker_Options} has been added to one of the sources.
19314 For example:
19315
19316 @smallexample @c ada
19317 pragma Linker_Options ("-lmy_lib");
19318 @end smallexample
19319 @end itemize
19320
19321 @node Stand-alone Ada Libraries
19322 @section Stand-alone Ada Libraries
19323 @cindex Stand-alone library, building, using
19324
19325 @menu
19326 * Introduction to Stand-alone Libraries::
19327 * Building a Stand-alone Library::
19328 * Creating a Stand-alone Library to be used in a non-Ada context::
19329 * Restrictions in Stand-alone Libraries::
19330 @end menu
19331
19332 @node Introduction to Stand-alone Libraries
19333 @subsection Introduction to Stand-alone Libraries
19334
19335 @noindent
19336 A Stand-alone Library (abbreviated ``SAL'') is a library that contains the
19337 necessary code to
19338 elaborate the Ada units that are included in the library. In contrast with
19339 an ordinary library, which consists of all sources, objects and @file{ALI}
19340 files of the
19341 library, a SAL may specify a restricted subset of compilation units
19342 to serve as a library interface. In this case, the fully
19343 self-sufficient set of files will normally consist of an objects
19344 archive, the sources of interface units' specs, and the @file{ALI}
19345 files of interface units.
19346 If an interface spec contains a generic unit or an inlined subprogram,
19347 the body's
19348 source must also be provided; if the units that must be provided in the source
19349 form depend on other units, the source and @file{ALI} files of those must
19350 also be provided.
19351
19352 The main purpose of a SAL is to minimize the recompilation overhead of client
19353 applications when a new version of the library is installed. Specifically,
19354 if the interface sources have not changed, client applications do not need to
19355 be recompiled. If, furthermore, a SAL is provided in the shared form and its
19356 version, controlled by @code{Library_Version} attribute, is not changed,
19357 then the clients do not need to be relinked.
19358
19359 SALs also allow the library providers to minimize the amount of library source
19360 text exposed to the clients.  Such ``information hiding'' might be useful or
19361 necessary for various reasons.
19362
19363 Stand-alone libraries are also well suited to be used in an executable whose
19364 main routine is not written in Ada.
19365
19366 @node Building a Stand-alone Library
19367 @subsection Building a Stand-alone Library
19368
19369 @noindent
19370 GNAT's Project facility provides a simple way of building and installing
19371 stand-alone libraries; see @ref{Stand-alone Library Projects}.
19372 To be a Stand-alone Library Project, in addition to the two attributes
19373 that make a project a Library Project (@code{Library_Name} and
19374 @code{Library_Dir}; see @ref{Library Projects}), the attribute
19375 @code{Library_Interface} must be defined.  For example:
19376
19377 @smallexample @c projectfile
19378 @group
19379    for Library_Dir use "lib_dir";
19380    for Library_Name use "dummy";
19381    for Library_Interface use ("int1", "int1.child");
19382 @end group
19383 @end smallexample
19384
19385 @noindent
19386 Attribute @code{Library_Interface} has a non-empty string list value,
19387 each string in the list designating a unit contained in an immediate source
19388 of the project file.
19389
19390 When a Stand-alone Library is built, first the binder is invoked to build
19391 a package whose name depends on the library name
19392 (@file{^b~dummy.ads/b^B$DUMMY.ADS/B^} in the example above).
19393 This binder-generated package includes initialization and
19394 finalization procedures whose
19395 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
19396 in the example
19397 above). The object corresponding to this package is included in the library.
19398
19399 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
19400 calling of these procedures if a static SAL is built, or if a shared SAL
19401 is built
19402 with the project-level attribute @code{Library_Auto_Init} set to
19403 @code{"false"}.
19404
19405 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
19406 (those that are listed in attribute @code{Library_Interface}) are copied to
19407 the Library Directory. As a consequence, only the Interface Units may be
19408 imported from Ada units outside of the library. If other units are imported,
19409 the binding phase will fail.
19410
19411 The attribute @code{Library_Src_Dir} may be specified for a
19412 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
19413 single string value. Its value must be the path (absolute or relative to the
19414 project directory) of an existing directory. This directory cannot be the
19415 object directory or one of the source directories, but it can be the same as
19416 the library directory. The sources of the Interface
19417 Units of the library that are needed by an Ada client of the library will be
19418 copied to the designated directory, called the Interface Copy directory.
19419 These sources include the specs of the Interface Units, but they may also
19420 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
19421 are used, or when there is a generic unit in the spec. Before the sources
19422 are copied to the Interface Copy directory, an attempt is made to delete all
19423 files in the Interface Copy directory.
19424
19425 Building stand-alone libraries by hand is somewhat tedious, but for those
19426 occasions when it is necessary here are the steps that you need to perform:
19427 @itemize @bullet
19428 @item
19429 Compile all library sources.
19430
19431 @item
19432 Invoke the binder with the switch @option{-n} (No Ada main program),
19433 with all the @file{ALI} files of the interfaces, and
19434 with the switch @option{-L} to give specific names to the @code{init}
19435 and @code{final} procedures.  For example:
19436 @smallexample
19437   gnatbind -n int1.ali int2.ali -Lsal1
19438 @end smallexample
19439
19440 @item
19441 Compile the binder generated file:
19442 @smallexample
19443   gcc -c b~int2.adb
19444 @end smallexample
19445
19446 @item
19447 Link the dynamic library with all the necessary object files,
19448 indicating to the linker the names of the @code{init} (and possibly
19449 @code{final}) procedures for automatic initialization (and finalization).
19450 The built library should be placed in a directory different from
19451 the object directory.
19452
19453 @item
19454 Copy the @code{ALI} files of the interface to the library directory,
19455 add in this copy an indication that it is an interface to a SAL
19456 (i.e., add a word @option{SL} on the line in the @file{ALI} file that starts
19457 with letter ``P'') and make the modified copy of the @file{ALI} file
19458 read-only.
19459 @end itemize
19460
19461 @noindent
19462 Using SALs is not different from using other libraries
19463 (see @ref{Using a library}).
19464
19465 @node Creating a Stand-alone Library to be used in a non-Ada context
19466 @subsection Creating a Stand-alone Library to be used in a non-Ada context
19467
19468 @noindent
19469 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
19470 a non-Ada context.
19471
19472 The only extra step required is to ensure that library interface subprograms
19473 are compatible with the main program, by means of @code{pragma Export}
19474 or @code{pragma Convention}.
19475
19476 Here is an example of simple library interface for use with C main program:
19477
19478 @smallexample @c ada
19479 package My_Package is
19480
19481    procedure Do_Something;
19482    pragma Export (C, Do_Something, "do_something");
19483
19484    procedure Do_Something_Else;
19485    pragma Export (C, Do_Something_Else, "do_something_else");
19486
19487 end My_Package;
19488 @end smallexample
19489
19490 @noindent
19491 On the foreign language side, you must provide a ``foreign'' view of the
19492 library interface; remember that it should contain elaboration routines in
19493 addition to interface subprograms.
19494
19495 The example below shows the content of @code{mylib_interface.h} (note
19496 that there is no rule for the naming of this file, any name can be used)
19497 @smallexample
19498 /* the library elaboration procedure */
19499 extern void mylibinit (void);
19500
19501 /* the library finalization procedure */
19502 extern void mylibfinal (void);
19503
19504 /* the interface exported by the library */
19505 extern void do_something (void);
19506 extern void do_something_else (void);
19507 @end smallexample
19508
19509 @noindent
19510 Libraries built as explained above can be used from any program, provided
19511 that the elaboration procedures (named @code{mylibinit} in the previous
19512 example) are called before the library services are used. Any number of
19513 libraries can be used simultaneously, as long as the elaboration
19514 procedure of each library is called.
19515
19516 Below is an example of a C program that uses the @code{mylib} library.
19517
19518 @smallexample
19519 #include "mylib_interface.h"
19520
19521 int
19522 main (void)
19523 @{
19524    /* First, elaborate the library before using it */
19525    mylibinit ();
19526
19527    /* Main program, using the library exported entities */
19528    do_something ();
19529    do_something_else ();
19530
19531    /* Library finalization at the end of the program */
19532    mylibfinal ();
19533    return 0;
19534 @}
19535 @end smallexample
19536
19537 @noindent
19538 Note that invoking any library finalization procedure generated by
19539 @code{gnatbind} shuts down the Ada run-time environment.
19540 Consequently, the
19541 finalization of all Ada libraries must be performed at the end of the program.
19542 No call to these libraries or to the Ada run-time library should be made
19543 after the finalization phase.
19544
19545 @node Restrictions in Stand-alone Libraries
19546 @subsection Restrictions in Stand-alone Libraries
19547
19548 @noindent
19549 The pragmas listed below should be used with caution inside libraries,
19550 as they can create incompatibilities with other Ada libraries:
19551 @itemize @bullet
19552 @item pragma @code{Locking_Policy}
19553 @item pragma @code{Queuing_Policy}
19554 @item pragma @code{Task_Dispatching_Policy}
19555 @item pragma @code{Unreserve_All_Interrupts}
19556 @end itemize
19557
19558 @noindent
19559 When using a library that contains such pragmas, the user must make sure
19560 that all libraries use the same pragmas with the same values. Otherwise,
19561 @code{Program_Error} will
19562 be raised during the elaboration of the conflicting
19563 libraries. The usage of these pragmas and its consequences for the user
19564 should therefore be well documented.
19565
19566 Similarly, the traceback in the exception occurrence mechanism should be
19567 enabled or disabled in a consistent manner across all libraries.
19568 Otherwise, Program_Error will be raised during the elaboration of the
19569 conflicting libraries.
19570
19571 If the @code{Version} or @code{Body_Version}
19572 attributes are used inside a library, then you need to
19573 perform a @code{gnatbind} step that specifies all @file{ALI} files in all
19574 libraries, so that version identifiers can be properly computed.
19575 In practice these attributes are rarely used, so this is unlikely
19576 to be a consideration.
19577
19578 @node  Rebuilding the GNAT Run-Time Library
19579 @section Rebuilding the GNAT Run-Time Library
19580 @cindex GNAT Run-Time Library, rebuilding
19581 @cindex Building the GNAT Run-Time Library
19582 @cindex Rebuilding the GNAT Run-Time Library
19583 @cindex Run-Time Library, rebuilding
19584
19585 @noindent
19586 It may be useful to recompile the GNAT library in various contexts, the
19587 most important one being the use of partition-wide configuration pragmas
19588 such as @code{Normalize_Scalars}. A special Makefile called
19589 @code{Makefile.adalib} is provided to that effect and can be found in
19590 the directory containing the GNAT library. The location of this
19591 directory depends on the way the GNAT environment has been installed and can
19592 be determined by means of the command:
19593
19594 @smallexample
19595 $ gnatls -v
19596 @end smallexample
19597
19598 @noindent
19599 The last entry in the object search path usually contains the
19600 gnat library. This Makefile contains its own documentation and in
19601 particular the set of instructions needed to rebuild a new library and
19602 to use it.
19603
19604 @node Using the GNU make Utility
19605 @chapter Using the GNU @code{make} Utility
19606 @findex make
19607
19608 @noindent
19609 This chapter offers some examples of makefiles that solve specific
19610 problems. It does not explain how to write a makefile (@pxref{Top,, GNU
19611 make, make, GNU @code{make}}), nor does it try to replace the
19612 @command{gnatmake} utility (@pxref{The GNAT Make Program gnatmake}).
19613
19614 All the examples in this section are specific to the GNU version of
19615 make. Although @command{make} is a standard utility, and the basic language
19616 is the same, these examples use some advanced features found only in
19617 @code{GNU make}.
19618
19619 @menu
19620 * Using gnatmake in a Makefile::
19621 * Automatically Creating a List of Directories::
19622 * Generating the Command Line Switches::
19623 * Overcoming Command Line Length Limits::
19624 @end menu
19625
19626 @node Using gnatmake in a Makefile
19627 @section Using gnatmake in a Makefile
19628 @findex makefile
19629 @cindex GNU make
19630
19631 @noindent
19632 Complex project organizations can be handled in a very powerful way by
19633 using GNU make combined with gnatmake. For instance, here is a Makefile
19634 which allows you to build each subsystem of a big project into a separate
19635 shared library. Such a makefile allows you to significantly reduce the link
19636 time of very big applications while maintaining full coherence at
19637 each step of the build process.
19638
19639 The list of dependencies are handled automatically by
19640 @command{gnatmake}. The Makefile is simply used to call gnatmake in each of
19641 the appropriate directories.
19642
19643 Note that you should also read the example on how to automatically
19644 create the list of directories
19645 (@pxref{Automatically Creating a List of Directories})
19646 which might help you in case your project has a lot of subdirectories.
19647
19648 @smallexample
19649 @iftex
19650 @leftskip=0cm
19651 @font@heightrm=cmr8
19652 @heightrm
19653 @end iftex
19654 ## This Makefile is intended to be used with the following directory
19655 ## configuration:
19656 ##  - The sources are split into a series of csc (computer software components)
19657 ##    Each of these csc is put in its own directory.
19658 ##    Their name are referenced by the directory names.
19659 ##    They will be compiled into shared library (although this would also work
19660 ##    with static libraries
19661 ##  - The main program (and possibly other packages that do not belong to any
19662 ##    csc is put in the top level directory (where the Makefile is).
19663 ##       toplevel_dir __ first_csc  (sources) __ lib (will contain the library)
19664 ##                    \_ second_csc (sources) __ lib (will contain the library)
19665 ##                    \_ @dots{}
19666 ## Although this Makefile is build for shared library, it is easy to modify
19667 ## to build partial link objects instead (modify the lines with -shared and
19668 ## gnatlink below)
19669 ##
19670 ## With this makefile, you can change any file in the system or add any new
19671 ## file, and everything will be recompiled correctly (only the relevant shared
19672 ## objects will be recompiled, and the main program will be re-linked).
19673
19674 # The list of computer software component for your project. This might be
19675 # generated automatically.
19676 CSC_LIST=aa bb cc
19677
19678 # Name of the main program (no extension)
19679 MAIN=main
19680
19681 # If we need to build objects with -fPIC, uncomment the following line
19682 #NEED_FPIC=-fPIC
19683
19684 # The following variable should give the directory containing libgnat.so
19685 # You can get this directory through 'gnatls -v'. This is usually the last
19686 # directory in the Object_Path.
19687 GLIB=@dots{}
19688
19689 # The directories for the libraries
19690 # (This macro expands the list of CSC to the list of shared libraries, you
19691 # could simply use the expanded form:
19692 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
19693 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
19694
19695 $@{MAIN@}: objects $@{LIB_DIR@}
19696     gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
19697     gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
19698
19699 objects::
19700     # recompile the sources
19701     gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
19702
19703 # Note: In a future version of GNAT, the following commands will be simplified
19704 # by a new tool, gnatmlib
19705 $@{LIB_DIR@}:
19706     mkdir -p $@{dir $@@ @}
19707     cd $@{dir $@@ @} && gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
19708     cd $@{dir $@@ @} && cp -f ../*.ali .
19709
19710 # The dependencies for the modules
19711 # Note that we have to force the expansion of *.o, since in some cases
19712 # make won't be able to do it itself.
19713 aa/lib/libaa.so: $@{wildcard aa/*.o@}
19714 bb/lib/libbb.so: $@{wildcard bb/*.o@}
19715 cc/lib/libcc.so: $@{wildcard cc/*.o@}
19716
19717 # Make sure all of the shared libraries are in the path before starting the
19718 # program
19719 run::
19720     LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
19721
19722 clean::
19723     $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
19724     $@{RM@} $@{CSC_LIST:%=%/*.ali@}
19725     $@{RM@} $@{CSC_LIST:%=%/*.o@}
19726     $@{RM@} *.o *.ali $@{MAIN@}
19727 @end smallexample
19728
19729 @node Automatically Creating a List of Directories
19730 @section Automatically Creating a List of Directories
19731
19732 @noindent
19733 In most makefiles, you will have to specify a list of directories, and
19734 store it in a variable. For small projects, it is often easier to
19735 specify each of them by hand, since you then have full control over what
19736 is the proper order for these directories, which ones should be
19737 included.
19738
19739 However, in larger projects, which might involve hundreds of
19740 subdirectories, it might be more convenient to generate this list
19741 automatically.
19742
19743 The example below presents two methods. The first one, although less
19744 general, gives you more control over the list. It involves wildcard
19745 characters, that are automatically expanded by @command{make}. Its
19746 shortcoming is that you need to explicitly specify some of the
19747 organization of your project, such as for instance the directory tree
19748 depth, whether some directories are found in a separate tree, @enddots{}
19749
19750 The second method is the most general one. It requires an external
19751 program, called @command{find}, which is standard on all Unix systems. All
19752 the directories found under a given root directory will be added to the
19753 list.
19754
19755 @smallexample
19756 @iftex
19757 @leftskip=0cm
19758 @font@heightrm=cmr8
19759 @heightrm
19760 @end iftex
19761 # The examples below are based on the following directory hierarchy:
19762 # All the directories can contain any number of files
19763 # ROOT_DIRECTORY ->  a  ->  aa  ->  aaa
19764 #                       ->  ab
19765 #                       ->  ac
19766 #                ->  b  ->  ba  ->  baa
19767 #                       ->  bb
19768 #                       ->  bc
19769 # This Makefile creates a variable called DIRS, that can be reused any time
19770 # you need this list (see the other examples in this section)
19771
19772 # The root of your project's directory hierarchy
19773 ROOT_DIRECTORY=.
19774
19775 ####
19776 # First method: specify explicitly the list of directories
19777 # This allows you to specify any subset of all the directories you need.
19778 ####
19779
19780 DIRS := a/aa/ a/ab/ b/ba/
19781
19782 ####
19783 # Second method: use wildcards
19784 # Note that the argument(s) to wildcard below should end with a '/'.
19785 # Since wildcards also return file names, we have to filter them out
19786 # to avoid duplicate directory names.
19787 # We thus use make's @code{dir} and @code{sort} functions.
19788 # It sets DIRs to the following value (note that the directories aaa and baa
19789 # are not given, unless you change the arguments to wildcard).
19790 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
19791 ####
19792
19793 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
19794                     $@{ROOT_DIRECTORY@}/*/*/@}@}@}
19795
19796 ####
19797 # Third method: use an external program
19798 # This command is much faster if run on local disks, avoiding NFS slowdowns.
19799 # This is the most complete command: it sets DIRs to the following value:
19800 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
19801 ####
19802
19803 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
19804
19805 @end smallexample
19806
19807 @node Generating the Command Line Switches
19808 @section Generating the Command Line Switches
19809
19810 @noindent
19811 Once you have created the list of directories as explained in the
19812 previous section (@pxref{Automatically Creating a List of Directories}),
19813 you can easily generate the command line arguments to pass to gnatmake.
19814
19815 For the sake of completeness, this example assumes that the source path
19816 is not the same as the object path, and that you have two separate lists
19817 of directories.
19818
19819 @smallexample
19820 # see "Automatically creating a list of directories" to create
19821 # these variables
19822 SOURCE_DIRS=
19823 OBJECT_DIRS=
19824
19825 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
19826 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
19827
19828 all:
19829         gnatmake $@{GNATMAKE_SWITCHES@} main_unit
19830 @end smallexample
19831
19832 @node Overcoming Command Line Length Limits
19833 @section Overcoming Command Line Length Limits
19834
19835 @noindent
19836 One problem that might be encountered on big projects is that many
19837 operating systems limit the length of the command line. It is thus hard to give
19838 gnatmake the list of source and object directories.
19839
19840 This example shows how you can set up environment variables, which will
19841 make @command{gnatmake} behave exactly as if the directories had been
19842 specified on the command line, but have a much higher length limit (or
19843 even none on most systems).
19844
19845 It assumes that you have created a list of directories in your Makefile,
19846 using one of the methods presented in
19847 @ref{Automatically Creating a List of Directories}.
19848 For the sake of completeness, we assume that the object
19849 path (where the ALI files are found) is different from the sources patch.
19850
19851 Note a small trick in the Makefile below: for efficiency reasons, we
19852 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
19853 expanded immediately by @code{make}. This way we overcome the standard
19854 make behavior which is to expand the variables only when they are
19855 actually used.
19856
19857 On Windows, if you are using the standard Windows command shell, you must
19858 replace colons with semicolons in the assignments to these variables.
19859
19860 @smallexample
19861 @iftex
19862 @leftskip=0cm
19863 @font@heightrm=cmr8
19864 @heightrm
19865 @end iftex
19866 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECT_PATH.
19867 # This is the same thing as putting the -I arguments on the command line.
19868 # (the equivalent of using -aI on the command line would be to define
19869 #  only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECT_PATH).
19870 # You can of course have different values for these variables.
19871 #
19872 # Note also that we need to keep the previous values of these variables, since
19873 # they might have been set before running 'make' to specify where the GNAT
19874 # library is installed.
19875
19876 # see "Automatically creating a list of directories" to create these
19877 # variables
19878 SOURCE_DIRS=
19879 OBJECT_DIRS=
19880
19881 empty:=
19882 space:=$@{empty@} $@{empty@}
19883 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
19884 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
19885 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
19886 ADA_OBJECT_PATH += $@{OBJECT_LIST@}
19887 export ADA_INCLUDE_PATH
19888 export ADA_OBJECT_PATH
19889
19890 all:
19891         gnatmake main_unit
19892 @end smallexample
19893 @end ifclear
19894
19895 @node Memory Management Issues
19896 @chapter Memory Management Issues
19897
19898 @noindent
19899 This chapter describes some useful memory pools provided in the GNAT library
19900 and in particular the GNAT Debug Pool facility, which can be used to detect
19901 incorrect uses of access values (including ``dangling references'').
19902 @ifclear vms
19903 It also describes the @command{gnatmem} tool, which can be used to track down
19904 ``memory leaks''.
19905 @end ifclear
19906
19907 @menu
19908 * Some Useful Memory Pools::
19909 * The GNAT Debug Pool Facility::
19910 @ifclear vms
19911 * The gnatmem Tool::
19912 @end ifclear
19913 @end menu
19914
19915 @node Some Useful Memory Pools
19916 @section Some Useful Memory Pools
19917 @findex Memory Pool
19918 @cindex storage, pool
19919
19920 @noindent
19921 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
19922 storage pool. Allocations use the standard system call @code{malloc} while
19923 deallocations use the standard system call @code{free}. No reclamation is
19924 performed when the pool goes out of scope. For performance reasons, the
19925 standard default Ada allocators/deallocators do not use any explicit storage
19926 pools but if they did, they could use this storage pool without any change in
19927 behavior. That is why this storage pool is used  when the user
19928 manages to make the default implicit allocator explicit as in this example:
19929 @smallexample @c ada
19930    type T1 is access Something;
19931     -- no Storage pool is defined for T2
19932    type T2 is access Something_Else;
19933    for T2'Storage_Pool use T1'Storage_Pool;
19934    -- the above is equivalent to
19935    for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
19936 @end smallexample
19937
19938 @noindent
19939 The @code{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
19940 pool. The allocation strategy is similar to @code{Pool_Local}'s
19941 except that the all
19942 storage allocated with this pool is reclaimed when the pool object goes out of
19943 scope. This pool provides a explicit mechanism similar to the implicit one
19944 provided by several Ada 83 compilers for allocations performed through a local
19945 access type and whose purpose was to reclaim memory when exiting the
19946 scope of a given local access. As an example, the following program does not
19947 leak memory even though it does not perform explicit deallocation:
19948
19949 @smallexample @c ada
19950 with System.Pool_Local;
19951 procedure Pooloc1 is
19952    procedure Internal is
19953       type A is access Integer;
19954       X : System.Pool_Local.Unbounded_Reclaim_Pool;
19955       for A'Storage_Pool use X;
19956       v : A;
19957    begin
19958       for I in  1 .. 50 loop
19959          v := new Integer;
19960       end loop;
19961    end Internal;
19962 begin
19963    for I in  1 .. 100 loop
19964       Internal;
19965    end loop;
19966 end Pooloc1;
19967 @end smallexample
19968
19969 @noindent
19970 The @code{System.Pool_Size} package implements the Stack_Bounded_Pool used when
19971 @code{Storage_Size} is specified for an access type.
19972 The whole storage for the pool is
19973 allocated at once, usually on the stack at the point where the access type is
19974 elaborated. It is automatically reclaimed when exiting the scope where the
19975 access type is defined. This package is not intended to be used directly by the
19976 user and it is implicitly used for each such declaration:
19977
19978 @smallexample @c ada
19979    type T1 is access Something;
19980    for T1'Storage_Size use 10_000;
19981 @end smallexample
19982
19983 @node The GNAT Debug Pool Facility
19984 @section The GNAT Debug Pool Facility
19985 @findex Debug Pool
19986 @cindex storage, pool, memory corruption
19987
19988 @noindent
19989 The use of unchecked deallocation and unchecked conversion can easily
19990 lead to incorrect memory references. The problems generated by such
19991 references are usually difficult to tackle because the symptoms can be
19992 very remote from the origin of the problem. In such cases, it is
19993 very helpful to detect the problem as early as possible. This is the
19994 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
19995
19996 In order to use the GNAT specific debugging pool, the user must
19997 associate a debug pool object with each of the access types that may be
19998 related to suspected memory problems. See Ada Reference Manual 13.11.
19999 @smallexample @c ada
20000 type Ptr is access Some_Type;
20001 Pool : GNAT.Debug_Pools.Debug_Pool;
20002 for Ptr'Storage_Pool use Pool;
20003 @end smallexample
20004
20005 @noindent
20006 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
20007 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
20008 allow the user to redefine allocation and deallocation strategies. They
20009 also provide a checkpoint for each dereference, through the use of
20010 the primitive operation @code{Dereference} which is implicitly called at
20011 each dereference of an access value.
20012
20013 Once an access type has been associated with a debug pool, operations on
20014 values of the type may raise four distinct exceptions,
20015 which correspond to four potential kinds of memory corruption:
20016 @itemize @bullet
20017 @item
20018 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
20019 @item
20020 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
20021 @item
20022 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
20023 @item
20024 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
20025 @end itemize
20026
20027 @noindent
20028 For types associated with a Debug_Pool, dynamic allocation is performed using
20029 the standard GNAT allocation routine. References to all allocated chunks of
20030 memory are kept in an internal dictionary. Several deallocation strategies are
20031 provided, whereupon the user can choose to release the memory to the system,
20032 keep it allocated for further invalid access checks, or fill it with an easily
20033 recognizable pattern for debug sessions. The memory pattern is the old IBM
20034 hexadecimal convention: @code{16#DEADBEEF#}.
20035
20036 See the documentation in the file g-debpoo.ads for more information on the
20037 various strategies.
20038
20039 Upon each dereference, a check is made that the access value denotes a
20040 properly allocated memory location. Here is a complete example of use of
20041 @code{Debug_Pools}, that includes typical instances of  memory corruption:
20042 @smallexample @c ada
20043 @iftex
20044 @leftskip=0cm
20045 @end iftex
20046 with Gnat.Io; use Gnat.Io;
20047 with Unchecked_Deallocation;
20048 with Unchecked_Conversion;
20049 with GNAT.Debug_Pools;
20050 with System.Storage_Elements;
20051 with Ada.Exceptions; use Ada.Exceptions;
20052 procedure Debug_Pool_Test is
20053
20054    type T is access Integer;
20055    type U is access all T;
20056
20057    P : GNAT.Debug_Pools.Debug_Pool;
20058    for T'Storage_Pool use P;
20059
20060    procedure Free is new Unchecked_Deallocation (Integer, T);
20061    function UC is new Unchecked_Conversion (U, T);
20062    A, B : aliased T;
20063
20064    procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
20065
20066 begin
20067    Info (P);
20068    A := new Integer;
20069    B := new Integer;
20070    B := A;
20071    Info (P);
20072    Free (A);
20073    begin
20074       Put_Line (Integer'Image(B.all));
20075    exception
20076       when E : others => Put_Line ("raised: " & Exception_Name (E));
20077    end;
20078    begin
20079       Free (B);
20080    exception
20081       when E : others => Put_Line ("raised: " & Exception_Name (E));
20082    end;
20083    B := UC(A'Access);
20084    begin
20085       Put_Line (Integer'Image(B.all));
20086    exception
20087       when E : others => Put_Line ("raised: " & Exception_Name (E));
20088    end;
20089    begin
20090       Free (B);
20091    exception
20092       when E : others => Put_Line ("raised: " & Exception_Name (E));
20093    end;
20094    Info (P);
20095 end Debug_Pool_Test;
20096 @end smallexample
20097
20098 @noindent
20099 The debug pool mechanism provides the following precise diagnostics on the
20100 execution of this erroneous program:
20101 @smallexample
20102 Debug Pool info:
20103   Total allocated bytes :  0
20104   Total deallocated bytes :  0
20105   Current Water Mark:  0
20106   High Water Mark:  0
20107
20108 Debug Pool info:
20109   Total allocated bytes :  8
20110   Total deallocated bytes :  0
20111   Current Water Mark:  8
20112   High Water Mark:  8
20113
20114 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
20115 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
20116 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
20117 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
20118 Debug Pool info:
20119   Total allocated bytes :  8
20120   Total deallocated bytes :  4
20121   Current Water Mark:  4
20122   High Water Mark:  8
20123 @end smallexample
20124
20125 @ifclear vms
20126 @node The gnatmem Tool
20127 @section The @command{gnatmem} Tool
20128 @findex gnatmem
20129
20130 @noindent
20131 The @code{gnatmem} utility monitors dynamic allocation and
20132 deallocation activity in a program, and displays information about
20133 incorrect deallocations and possible sources of memory leaks.
20134 It is designed to work in association with a static runtime library
20135 only and in this context provides three types of information:
20136 @itemize @bullet
20137 @item
20138 General information concerning memory management, such as the total
20139 number of allocations and deallocations, the amount of allocated
20140 memory and the high water mark, i.e.@: the largest amount of allocated
20141 memory in the course of program execution.
20142
20143 @item
20144 Backtraces for all incorrect deallocations, that is to say deallocations
20145 which do not correspond to a valid allocation.
20146
20147 @item
20148 Information on each allocation that is potentially the origin of a memory
20149 leak.
20150 @end itemize
20151
20152 @menu
20153 * Running gnatmem::
20154 * Switches for gnatmem::
20155 * Example of gnatmem Usage::
20156 @end menu
20157
20158 @node Running gnatmem
20159 @subsection Running @code{gnatmem}
20160
20161 @noindent
20162 @code{gnatmem} makes use of the output created by the special version of
20163 allocation and deallocation routines that record call information. This
20164 allows to obtain accurate dynamic memory usage history at a minimal cost to
20165 the execution speed. Note however, that @code{gnatmem} is not supported on
20166 all platforms (currently, it is supported on AIX, HP-UX, GNU/Linux,
20167 Solaris and Windows NT/2000/XP (x86).
20168
20169 @noindent
20170 The @code{gnatmem} command has the form
20171
20172 @smallexample
20173    $ gnatmem @ovar{switches} user_program
20174 @end smallexample
20175
20176 @noindent
20177 The program must have been linked with the instrumented version of the
20178 allocation and deallocation routines. This is done by linking with the
20179 @file{libgmem.a} library. For correct symbolic backtrace information,
20180 the user program should be compiled with debugging options
20181 (see @ref{Switches for gcc}). For example to build @file{my_program}:
20182
20183 @smallexample
20184 $ gnatmake -g my_program -largs -lgmem
20185 @end smallexample
20186
20187 @noindent
20188 As library @file{libgmem.a} contains an alternate body for package
20189 @code{System.Memory}, @file{s-memory.adb} should not be compiled and linked
20190 when an executable is linked with library @file{libgmem.a}. It is then not
20191 recommended to use @command{gnatmake} with switch @option{^-a^/ALL_FILES^}.
20192
20193 @noindent
20194 When @file{my_program} is executed, the file @file{gmem.out} is produced.
20195 This file contains information about all allocations and deallocations
20196 performed by the program. It is produced by the instrumented allocations and
20197 deallocations routines and will be used by @code{gnatmem}.
20198
20199 In order to produce symbolic backtrace information for allocations and
20200 deallocations performed by the GNAT run-time library, you need to use a
20201 version of that library that has been compiled with the @option{-g} switch
20202 (see @ref{Rebuilding the GNAT Run-Time Library}).
20203
20204 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
20205 examine. If the location of @file{gmem.out} file was not explicitly supplied by
20206 @option{-i} switch, gnatmem will assume that this file can be found in the
20207 current directory. For example, after you have executed @file{my_program},
20208 @file{gmem.out} can be analyzed by @code{gnatmem} using the command:
20209
20210 @smallexample
20211 $ gnatmem my_program
20212 @end smallexample
20213
20214 @noindent
20215 This will produce the output with the following format:
20216
20217 *************** debut cc
20218 @smallexample
20219 $ gnatmem my_program
20220
20221 Global information
20222 ------------------
20223    Total number of allocations        :  45
20224    Total number of deallocations      :   6
20225    Final Water Mark (non freed mem)   :  11.29 Kilobytes
20226    High Water Mark                    :  11.40 Kilobytes
20227
20228 .
20229 .
20230 .
20231 Allocation Root # 2
20232 -------------------
20233  Number of non freed allocations    :  11
20234  Final Water Mark (non freed mem)   :   1.16 Kilobytes
20235  High Water Mark                    :   1.27 Kilobytes
20236  Backtrace                          :
20237    my_program.adb:23 my_program.alloc
20238 .
20239 .
20240 .
20241 @end smallexample
20242
20243 The first block of output gives general information. In this case, the
20244 Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
20245 Unchecked_Deallocation routine occurred.
20246
20247 @noindent
20248 Subsequent paragraphs display  information on all allocation roots.
20249 An allocation root is a specific point in the execution of the program
20250 that generates some dynamic allocation, such as a ``@code{@b{new}}''
20251 construct. This root is represented by an execution backtrace (or subprogram
20252 call stack). By default the backtrace depth for allocations roots is 1, so
20253 that a root corresponds exactly to a source location. The backtrace can
20254 be made deeper, to make the root more specific.
20255
20256 @node Switches for gnatmem
20257 @subsection Switches for @code{gnatmem}
20258
20259 @noindent
20260 @code{gnatmem} recognizes the following switches:
20261
20262 @table @option
20263
20264 @item -q
20265 @cindex @option{-q} (@code{gnatmem})
20266 Quiet. Gives the minimum output needed to identify the origin of the
20267 memory leaks. Omits statistical information.
20268
20269 @item @var{N}
20270 @cindex @var{N} (@code{gnatmem})
20271 N is an integer literal (usually between 1 and 10) which controls the
20272 depth of the backtraces defining allocation root. The default value for
20273 N is 1. The deeper the backtrace, the more precise the localization of
20274 the root. Note that the total number of roots can depend on this
20275 parameter. This parameter must be specified @emph{before} the name of the
20276 executable to be analyzed, to avoid ambiguity.
20277
20278 @item -b n
20279 @cindex @option{-b} (@code{gnatmem})
20280 This switch has the same effect as just depth parameter.
20281
20282 @item -i @var{file}
20283 @cindex @option{-i} (@code{gnatmem})
20284 Do the @code{gnatmem} processing starting from @file{file}, rather than
20285 @file{gmem.out} in the current directory.
20286
20287 @item -m n
20288 @cindex @option{-m} (@code{gnatmem})
20289 This switch causes @code{gnatmem} to mask the allocation roots that have less
20290 than n leaks. The default value is 1. Specifying the value of 0 will allow to
20291 examine even the roots that didn't result in leaks.
20292
20293 @item -s order
20294 @cindex @option{-s} (@code{gnatmem})
20295 This switch causes @code{gnatmem} to sort the allocation roots according to the
20296 specified order of sort criteria, each identified by a single letter. The
20297 currently supported criteria are @code{n, h, w} standing respectively for
20298 number of unfreed allocations, high watermark, and final watermark
20299 corresponding to a specific root. The default order is @code{nwh}.
20300
20301 @end table
20302
20303 @node Example of gnatmem Usage
20304 @subsection Example of @code{gnatmem} Usage
20305
20306 @noindent
20307 The following example shows the use of @code{gnatmem}
20308 on a simple memory-leaking program.
20309 Suppose that we have the following Ada program:
20310
20311 @smallexample @c ada
20312 @group
20313 @cartouche
20314 with Unchecked_Deallocation;
20315 procedure Test_Gm is
20316
20317    type T is array (1..1000) of Integer;
20318    type Ptr is access T;
20319    procedure Free is new Unchecked_Deallocation (T, Ptr);
20320    A : Ptr;
20321
20322    procedure My_Alloc is
20323    begin
20324       A := new T;
20325    end My_Alloc;
20326
20327    procedure My_DeAlloc is
20328       B : Ptr := A;
20329    begin
20330       Free (B);
20331    end My_DeAlloc;
20332
20333 begin
20334    My_Alloc;
20335    for I in 1 .. 5 loop
20336       for J in I .. 5 loop
20337          My_Alloc;
20338       end loop;
20339       My_Dealloc;
20340    end loop;
20341 end;
20342 @end cartouche
20343 @end group
20344 @end smallexample
20345
20346 @noindent
20347 The program needs to be compiled with debugging option and linked with
20348 @code{gmem} library:
20349
20350 @smallexample
20351 $ gnatmake -g test_gm -largs -lgmem
20352 @end smallexample
20353
20354 @noindent
20355 Then we execute the program as usual:
20356
20357 @smallexample
20358 $ test_gm
20359 @end smallexample
20360
20361 @noindent
20362 Then @code{gnatmem} is invoked simply with
20363 @smallexample
20364 $ gnatmem test_gm
20365 @end smallexample
20366
20367 @noindent
20368 which produces the following output (result may vary on different platforms):
20369
20370 @smallexample
20371 Global information
20372 ------------------
20373    Total number of allocations        :  18
20374    Total number of deallocations      :   5
20375    Final Water Mark (non freed mem)   :  53.00 Kilobytes
20376    High Water Mark                    :  56.90 Kilobytes
20377
20378 Allocation Root # 1
20379 -------------------
20380  Number of non freed allocations    :  11
20381  Final Water Mark (non freed mem)   :  42.97 Kilobytes
20382  High Water Mark                    :  46.88 Kilobytes
20383  Backtrace                          :
20384    test_gm.adb:11 test_gm.my_alloc
20385
20386 Allocation Root # 2
20387 -------------------
20388  Number of non freed allocations    :   1
20389  Final Water Mark (non freed mem)   :  10.02 Kilobytes
20390  High Water Mark                    :  10.02 Kilobytes
20391  Backtrace                          :
20392    s-secsta.adb:81 system.secondary_stack.ss_init
20393
20394 Allocation Root # 3
20395 -------------------
20396  Number of non freed allocations    :   1
20397  Final Water Mark (non freed mem)   :  12 Bytes
20398  High Water Mark                    :  12 Bytes
20399  Backtrace                          :
20400    s-secsta.adb:181 system.secondary_stack.ss_init
20401 @end smallexample
20402
20403 @noindent
20404 Note that the GNAT run time contains itself a certain number of
20405 allocations that have no  corresponding deallocation,
20406 as shown here for root #2 and root
20407 #3. This is a normal behavior when the number of non-freed allocations
20408 is one, it allocates dynamic data structures that the run time needs for
20409 the complete lifetime of the program. Note also that there is only one
20410 allocation root in the user program with a single line back trace:
20411 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
20412 program shows that 'My_Alloc' is called at 2 different points in the
20413 source (line 21 and line 24). If those two allocation roots need to be
20414 distinguished, the backtrace depth parameter can be used:
20415
20416 @smallexample
20417 $ gnatmem 3 test_gm
20418 @end smallexample
20419
20420 @noindent
20421 which will give the following output:
20422
20423 @smallexample
20424 Global information
20425 ------------------
20426    Total number of allocations        :  18
20427    Total number of deallocations      :   5
20428    Final Water Mark (non freed mem)   :  53.00 Kilobytes
20429    High Water Mark                    :  56.90 Kilobytes
20430
20431 Allocation Root # 1
20432 -------------------
20433  Number of non freed allocations    :  10
20434  Final Water Mark (non freed mem)   :  39.06 Kilobytes
20435  High Water Mark                    :  42.97 Kilobytes
20436  Backtrace                          :
20437    test_gm.adb:11 test_gm.my_alloc
20438    test_gm.adb:24 test_gm
20439    b_test_gm.c:52 main
20440
20441 Allocation Root # 2
20442 -------------------
20443  Number of non freed allocations    :   1
20444  Final Water Mark (non freed mem)   :  10.02 Kilobytes
20445  High Water Mark                    :  10.02 Kilobytes
20446  Backtrace                          :
20447    s-secsta.adb:81  system.secondary_stack.ss_init
20448    s-secsta.adb:283 <system__secondary_stack___elabb>
20449    b_test_gm.c:33   adainit
20450
20451 Allocation Root # 3
20452 -------------------
20453  Number of non freed allocations    :   1
20454  Final Water Mark (non freed mem)   :   3.91 Kilobytes
20455  High Water Mark                    :   3.91 Kilobytes
20456  Backtrace                          :
20457    test_gm.adb:11 test_gm.my_alloc
20458    test_gm.adb:21 test_gm
20459    b_test_gm.c:52 main
20460
20461 Allocation Root # 4
20462 -------------------
20463  Number of non freed allocations    :   1
20464  Final Water Mark (non freed mem)   :  12 Bytes
20465  High Water Mark                    :  12 Bytes
20466  Backtrace                          :
20467    s-secsta.adb:181 system.secondary_stack.ss_init
20468    s-secsta.adb:283 <system__secondary_stack___elabb>
20469    b_test_gm.c:33   adainit
20470 @end smallexample
20471
20472 @noindent
20473 The allocation root #1 of the first example has been split in 2 roots #1
20474 and #3 thanks to the more precise associated backtrace.
20475
20476 @end ifclear
20477
20478 @node Stack Related Facilities
20479 @chapter Stack Related Facilities
20480
20481 @noindent
20482 This chapter describes some useful tools associated with stack
20483 checking and analysis. In
20484 particular, it deals with dynamic and static stack usage measurements.
20485
20486 @menu
20487 * Stack Overflow Checking::
20488 * Static Stack Usage Analysis::
20489 * Dynamic Stack Usage Analysis::
20490 @end menu
20491
20492 @node Stack Overflow Checking
20493 @section Stack Overflow Checking
20494 @cindex Stack Overflow Checking
20495 @cindex -fstack-check
20496
20497 @noindent
20498 For most operating systems, @command{gcc} does not perform stack overflow
20499 checking by default. This means that if the main environment task or
20500 some other task exceeds the available stack space, then unpredictable
20501 behavior will occur. Most native systems offer some level of protection by
20502 adding a guard page at the end of each task stack. This mechanism is usually
20503 not enough for dealing properly with stack overflow situations because
20504 a large local variable could ``jump'' above the guard page.
20505 Furthermore, when the
20506 guard page is hit, there may not be any space left on the stack for executing
20507 the exception propagation code. Enabling stack checking avoids
20508 such situations.
20509
20510 To activate stack checking, compile all units with the gcc option
20511 @option{-fstack-check}. For example:
20512
20513 @smallexample
20514 gcc -c -fstack-check package1.adb
20515 @end smallexample
20516
20517 @noindent
20518 Units compiled with this option will generate extra instructions to check
20519 that any use of the stack (for procedure calls or for declaring local
20520 variables in declare blocks) does not exceed the available stack space.
20521 If the space is exceeded, then a @code{Storage_Error} exception is raised.
20522
20523 For declared tasks, the stack size is controlled by the size
20524 given in an applicable @code{Storage_Size} pragma or by the value specified
20525 at bind time with @option{-d} (@pxref{Switches for gnatbind}) or is set to
20526 the default size as defined in the GNAT runtime otherwise.
20527
20528 For the environment task, the stack size depends on
20529 system defaults and is unknown to the compiler. Stack checking
20530 may still work correctly if a fixed
20531 size stack is allocated, but this cannot be guaranteed.
20532 @ifclear vms
20533 To ensure that a clean exception is signalled for stack
20534 overflow, set the environment variable
20535 @env{GNAT_STACK_LIMIT} to indicate the maximum
20536 stack area that can be used, as in:
20537 @cindex GNAT_STACK_LIMIT
20538
20539 @smallexample
20540 SET GNAT_STACK_LIMIT 1600
20541 @end smallexample
20542
20543 @noindent
20544 The limit is given in kilobytes, so the above declaration would
20545 set the stack limit of the environment task to 1.6 megabytes.
20546 Note that the only purpose of this usage is to limit the amount
20547 of stack used by the environment task. If it is necessary to
20548 increase the amount of stack for the environment task, then this
20549 is an operating systems issue, and must be addressed with the
20550 appropriate operating systems commands.
20551 @end ifclear
20552 @ifset vms
20553 To have a fixed size stack in the environment task, the stack must be put
20554 in the P0 address space and its size specified.  Use these switches to
20555 create a p0 image:
20556
20557 @smallexample
20558 gnatmake my_progs -largs "-Wl,--opt=STACK=4000,/p0image"
20559 @end smallexample
20560
20561 @noindent
20562 The quotes are required to keep case.  The number after @samp{STACK=} is the
20563 size of the environmental task stack in pagelets (512 bytes).  In this example
20564 the stack size is about 2 megabytes.
20565
20566 @noindent
20567 A consequence of the @option{/p0image} qualifier is also to makes RMS buffers
20568 be placed in P0 space.  Refer to @cite{HP OpenVMS Linker Utility Manual} for
20569 more details about the @option{/p0image} qualifier and the @option{stack}
20570 option.
20571 @end ifset
20572
20573 @node Static Stack Usage Analysis
20574 @section Static Stack Usage Analysis
20575 @cindex Static Stack Usage Analysis
20576 @cindex -fstack-usage
20577
20578 @noindent
20579 A unit compiled with @option{-fstack-usage} will generate an extra file
20580 that specifies
20581 the maximum amount of stack used, on a per-function basis.
20582 The file has the same
20583 basename as the target object file with a @file{.su} extension.
20584 Each line of this file is made up of three fields:
20585
20586 @itemize
20587 @item
20588 The name of the function.
20589 @item
20590 A number of bytes.
20591 @item
20592 One or more qualifiers: @code{static}, @code{dynamic}, @code{bounded}.
20593 @end itemize
20594
20595 The second field corresponds to the size of the known part of the function
20596 frame.
20597
20598 The qualifier @code{static} means that the function frame size
20599 is purely static.
20600 It usually means that all local variables have a static size.
20601 In this case, the second field is a reliable measure of the function stack
20602 utilization.
20603
20604 The qualifier @code{dynamic} means that the function frame size is not static.
20605 It happens mainly when some local variables have a dynamic size. When this
20606 qualifier appears alone, the second field is not a reliable measure
20607 of the function stack analysis. When it is qualified with  @code{bounded}, it
20608 means that the second field is a reliable maximum of the function stack
20609 utilization.
20610
20611 @node Dynamic Stack Usage Analysis
20612 @section Dynamic Stack Usage Analysis
20613
20614 @noindent
20615 It is possible to measure the maximum amount of stack used by a task, by
20616 adding a switch to @command{gnatbind}, as:
20617
20618 @smallexample
20619 $ gnatbind -u0 file
20620 @end smallexample
20621
20622 @noindent
20623 With this option, at each task termination, its stack usage is  output on
20624 @file{stderr}.
20625 It is not always convenient to output the stack usage when the program
20626 is still running. Hence, it is possible to delay this output until program
20627 termination. for a given number of tasks specified as the argument of the
20628 @option{-u} option. For instance:
20629
20630 @smallexample
20631 $ gnatbind -u100 file
20632 @end smallexample
20633
20634 @noindent
20635 will buffer the stack usage information of the first 100 tasks to terminate and
20636 output this info at program termination. Results are displayed in four
20637 columns:
20638
20639 @noindent
20640 Index | Task Name | Stack Size | Stack Usage [Value +/- Variation]
20641
20642 @noindent
20643 where:
20644
20645 @table @emph
20646 @item Index
20647 is a number associated with each task.
20648
20649 @item Task Name
20650 is the name of the task analyzed.
20651
20652 @item Stack Size
20653 is the maximum size for the stack.
20654
20655 @item Stack Usage
20656 is the measure done by the stack analyzer. In order to prevent overflow, the stack
20657 is not entirely analyzed, and it's not possible to know exactly how
20658 much has actually been used. The report thus contains the theoretical stack usage
20659 (Value) and the possible variation (Variation) around this value.
20660
20661 @end table
20662
20663 @noindent
20664 The environment task stack, e.g., the stack that contains the main unit, is
20665 only processed when the environment variable GNAT_STACK_LIMIT is set.
20666
20667
20668 @c *********************************
20669 @c *            GNATCHECK          *
20670 @c *********************************
20671 @node Verifying Properties Using gnatcheck
20672 @chapter Verifying Properties Using @command{gnatcheck}
20673 @findex gnatcheck
20674 @cindex @command{gnatcheck}
20675
20676 @noindent
20677 The @command{gnatcheck} tool is an ASIS-based utility that checks properties
20678 of Ada source files according to a given set of semantic rules.
20679 @cindex ASIS
20680
20681 In order to check compliance with a given rule, @command{gnatcheck} has to
20682 semantically analyze the Ada sources.
20683 Therefore, checks can only be performed on
20684 legal Ada units. Moreover, when a unit depends semantically upon units located
20685 outside the current directory, the source search path has to be provided when
20686 calling @command{gnatcheck}, either through a specified project file or
20687 through @command{gnatcheck} switches as described below.
20688
20689 A number of rules are predefined in @command{gnatcheck} and are described
20690 later in this chapter.
20691 You can also add new rules, by modifying the @command{gnatcheck} code and
20692 rebuilding the tool. In order to add a simple rule making some local checks,
20693 a small amount of straightforward ASIS-based programming is usually needed.
20694
20695 Project support for @command{gnatcheck} is provided by the GNAT
20696 driver (see @ref{The GNAT Driver and Project Files}).
20697
20698 Invoking @command{gnatcheck} on the command line has the form:
20699
20700 @smallexample
20701 $ gnatcheck @ovar{switches}  @{@var{filename}@}
20702       @r{[}^-files^/FILES^=@{@var{arg_list_filename}@}@r{]}
20703       @r{[}-cargs @var{gcc_switches}@r{]} -rules @var{rule_options}
20704 @end smallexample
20705
20706 @noindent
20707 where
20708 @itemize @bullet
20709 @item
20710 @var{switches} specify the general tool options
20711
20712 @item
20713 Each @var{filename} is the name (including the extension) of a source
20714 file to process. ``Wildcards'' are allowed, and
20715 the file name may contain path information.
20716
20717 @item
20718 Each @var{arg_list_filename} is the name (including the extension) of a text
20719 file containing the names of the source files to process, separated by spaces
20720 or line breaks.
20721
20722 @item
20723 @var{gcc_switches} is a list of switches for
20724 @command{gcc}. They will be passed on to all compiler invocations made by
20725 @command{gnatcheck} to generate the ASIS trees. Here you can provide
20726 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
20727 and use the @option{-gnatec} switch to set the configuration file.
20728
20729 @item
20730 @var{rule_options} is a list of options for controlling a set of
20731 rules to be checked by @command{gnatcheck} (@pxref{gnatcheck Rule Options}).
20732 @end itemize
20733
20734 @noindent
20735 Either a @file{@var{filename}} or an @file{@var{arg_list_filename}} must be
20736 supplied.
20737
20738 @menu
20739 * Format of the Report File::
20740 * General gnatcheck Switches::
20741 * gnatcheck Rule Options::
20742 * Adding the Results of Compiler Checks to gnatcheck Output::
20743 * Project-Wide Checks::
20744 * Rule exemption::
20745 * Predefined Rules::
20746 * Example of gnatcheck Usage::
20747 @end menu
20748
20749 @node Format of the Report File
20750 @section Format of the Report File
20751 @cindex Report file (for @code{gnatcheck})
20752
20753 @noindent
20754 The @command{gnatcheck} tool outputs on @file{stdout} all messages concerning
20755 rule violations.
20756 It also creates a text file  that
20757 contains the complete report of the last gnatcheck run. By default this file
20758 is named named @file{^gnatcheck.out^GNATCHECK.OUT^} and it is located in the
20759 current directory; the @option{^-o^/OUTPUT^} option can be used to change the
20760 name and/or location of the report file. This report contains:
20761 @itemize @bullet
20762 @item date and time of @command{gnatcheck} run, the version of
20763 the tool that has generated this report and the full parameters
20764 of the  @command{gnatcheck} invocation;
20765 @item list of enabled rules;
20766 @item total number of detected violations;
20767 @item list of source files where rule violations have been detected;
20768 @item list of source files where no violations have been detected.
20769 @end itemize
20770
20771 @node General gnatcheck Switches
20772 @section General @command{gnatcheck} Switches
20773
20774 @noindent
20775 The following switches control the general @command{gnatcheck} behavior
20776
20777 @table @option
20778 @c !sort!
20779 @cindex @option{^-a^/ALL^} (@command{gnatcheck})
20780 @item ^-a^/ALL^
20781 Process all units including those with read-only ALI files such as
20782 those from the GNAT Run-Time library.
20783
20784 @ifclear vms
20785 @ignore
20786 @cindex @option{-d} (@command{gnatcheck})
20787 @item -d
20788 Debug mode
20789 @end ignore
20790
20791 @cindex @option{-dd} (@command{gnatcheck})
20792 @item -dd
20793 Progress indicator mode (for use in GPS).
20794 @end ifclear
20795
20796 @cindex @option{^-h^/HELP^} (@command{gnatcheck})
20797 @item ^-h^/HELP^
20798 List the predefined and user-defined rules. For more details see
20799 @ref{Predefined Rules}.
20800
20801 @cindex @option{^-l^/LOCS^} (@command{gnatcheck})
20802 @item ^-l^/LOCS^
20803 Use full source locations references in the report file. For a construct from
20804 a generic instantiation a full source location is a chain from the location
20805 of this construct in the generic unit to the place where this unit is
20806 instantiated.
20807
20808 @cindex @option{^-log^/LOG^} (@command{gnatcheck})
20809 @item ^-log^/LOG^
20810 Duplicate all the output sent to @file{stderr} into a log file. The log file
20811 is named @file{gnatcheck.log} and is located in the current directory.
20812
20813 @cindex @option{^-m^/DIAGNOSTIC_LIMIT^} (@command{gnatcheck})
20814 @item ^-m@i{nnnn}^/DIAGNOSTIC_LIMIT=@i{nnnn}^
20815 Maximum number of diagnostics to be sent to @file{stdout}, where @i{nnnn} is in
20816 the range 0@dots{}1000;
20817 the default value is 500. Zero means that there is no limitation on
20818 the number of diagnostic messages to be output.
20819
20820 @cindex @option{^-q^/QUIET^} (@command{gnatcheck})
20821 @item ^-q^/QUIET^
20822 Quiet mode. All the diagnostics about rule violations are placed in the
20823 @command{gnatcheck} report file only, without duplication on @file{stdout}.
20824
20825 @cindex @option{^-s^/SHORT^} (@command{gnatcheck})
20826 @item ^-s^/SHORT^
20827 Short format of the report file (no version information, no list of applied
20828 rules, no list of checked sources is included)
20829
20830 @cindex @option{^--include-file=@var{file}^/INCLUDE_FILE=@var{file}^} (@command{gnatcheck})
20831 @item ^--include-file^/INCLUDE_FILE^
20832 Append the content of the specified text file to the report file
20833
20834 @cindex @option{^-t^/TIME^} (@command{gnatcheck})
20835 @item ^-t^/TIME^
20836 Print out execution time.
20837
20838 @cindex @option{^-v^/VERBOSE^} (@command{gnatcheck})
20839 @item ^-v^/VERBOSE^
20840 Verbose mode; @command{gnatcheck} generates version information and then
20841 a trace of sources being processed.
20842
20843 @cindex @option{^-o ^/OUTPUT^} (@command{gnatcheck})
20844 @item ^-o ^/OUTPUT=^@var{report_file}
20845 Set name of report file file to @var{report_file} .
20846
20847 @end table
20848
20849 @noindent
20850 Note that if any of the options @option{^-s1^/COMPILER_STYLE^},
20851 @option{^-s2^/BY_RULES^} or
20852 @option{^-s3^/BY_FILES_BY_RULES^} is specified,
20853 then the  @command{gnatcheck} report file will only contain sections
20854 explicitly denoted by these options.
20855
20856 @node gnatcheck Rule Options
20857 @section @command{gnatcheck} Rule Options
20858
20859 @noindent
20860 The following options control the processing performed by
20861 @command{gnatcheck}.
20862
20863 @table @option
20864 @cindex @option{+ALL} (@command{gnatcheck})
20865 @item +ALL
20866 Turn all the rule checks ON.
20867
20868 @cindex @option{-ALL} (@command{gnatcheck})
20869 @item -ALL
20870 Turn all the rule checks OFF.
20871
20872 @cindex @option{+R} (@command{gnatcheck})
20873 @item +R@var{rule_id}@r{[}:@var{param}@r{]}
20874 Turn on the check for a specified rule with the specified parameter, if any.
20875 @var{rule_id} must be the identifier of one of the currently implemented rules
20876 (use @option{^-h^/HELP^} for the list of implemented rules). Rule identifiers
20877 are not case-sensitive. The @var{param} item must
20878 be a string representing a valid parameter(s) for the specified rule.
20879 If it contains any space characters then this string must be enclosed in
20880 quotation marks.
20881
20882 @cindex @option{-R} (@command{gnatcheck})
20883 @item -R@var{rule_id}@r{[}:@var{param}@r{]}
20884 Turn off the check for a specified rule with the specified parameter, if any.
20885
20886 @cindex @option{-from} (@command{gnatcheck})
20887 @item -from=@var{rule_option_filename}
20888 Read the rule options from the text file @var{rule_option_filename}, referred
20889 to as a ``coding standard file'' below.
20890
20891 @end table
20892
20893 @noindent
20894 The default behavior is that all the rule checks are disabled.
20895
20896 A coding standard file is a text file that contains a set of rule options
20897 described above.
20898 @cindex Coding standard file (for @code{gnatcheck})
20899 The file may contain empty lines and Ada-style comments (comment
20900 lines and end-of-line comments). There can be several rule options on a
20901 single line (separated by a space).
20902
20903 A coding standard file may reference other coding standard files by including
20904 more @option{-from=@var{rule_option_filename}}
20905 options, each such option being replaced with the content of the
20906 corresponding coding standard file during processing. In case a
20907 cycle is detected (that is, @file{@var{rule_file_1}} reads rule options
20908 from @file{@var{rule_file_2}}, and @file{@var{rule_file_2}} reads
20909 (directly or indirectly) rule options from @file{@var{rule_file_1}}),
20910 processing fails with an error message.
20911
20912
20913 @node Adding the Results of Compiler Checks to gnatcheck Output
20914 @section Adding the Results of Compiler Checks to @command{gnatcheck} Output
20915
20916 @noindent
20917 The @command{gnatcheck} tool can include in the generated diagnostic messages
20918 and in
20919 the report file the results of the checks performed by the compiler. Though
20920 disabled by default, this effect may be obtained by using @option{+R} with
20921 the following rule identifiers and parameters:
20922
20923 @table @option
20924 @item Restrictions
20925 To record restrictions violations (which are performed by the compiler if the
20926 pragma @code{Restrictions} or @code{Restriction_Warnings} are given),
20927 use the @code{Restrictions} rule
20928 with the same parameters as pragma
20929 @code{Restrictions} or @code{Restriction_Warnings}.
20930
20931 @item Style_Checks
20932 To record compiler style checks (@pxref{Style Checking}), use the
20933 @code{Style_Checks} rule.
20934 This rule takes a parameter in one of the following forms:
20935 @itemize
20936 @item
20937 @code{All_Checks},
20938 which enables the standard style checks corresponding to the @option{-gnatyy}
20939 GNAT style check option, or
20940
20941 @item
20942 a string with the same
20943 structure and semantics as the @code{string_LITERAL} parameter of the
20944 GNAT pragma @code{Style_Checks}
20945 (for further information about this pragma,
20946 @pxref{Pragma Style_Checks,,, gnat_rm, GNAT Reference Manual}).
20947 @end itemize
20948
20949 @noindent
20950 For example, the
20951 @code{+RStyle_Checks:O} rule option activates
20952 the compiler style check that corresponds to
20953 @code{-gnatyO} style check option.
20954
20955 @item Warnings
20956 To record compiler warnings (@pxref{Warning Message Control}), use the
20957 @code{Warnings} rule with a parameter that is a valid
20958 @i{static_string_expression} argument of the GNAT pragma @code{Warnings}
20959 (for further information about this pragma,
20960 @pxref{Pragma Warnings,,,gnat_rm, GNAT Reference Manual}).
20961 Note that in case of gnatcheck
20962 's' parameter, that corresponds to the GNAT @option{-gnatws} option, disables
20963 all the specific warnings, but not suppresses the warning mode,
20964 and 'e' parameter, corresponding to @option{-gnatwe} that means
20965 "treat warnings as errors", does not have any effect.
20966
20967 @end table
20968
20969 To disable a specific restriction check, use @code{-RStyle_Checks} gnatcheck
20970 option with the corresponding restriction name as a parameter. @code{-R} is
20971 not available for @code{Style_Checks} and @code{Warnings} options, to disable
20972 warnings and style checks, use the corresponding warning and style options.
20973
20974 @node Project-Wide Checks
20975 @section Project-Wide Checks
20976 @cindex Project-wide checks (for @command{gnatcheck})
20977
20978 @noindent
20979 In order to perform checks on all units of a given project, you can use
20980 the GNAT driver along with the @option{-P} option:
20981 @smallexample
20982    gnat check -Pproj -rules -from=my_rules
20983 @end smallexample
20984
20985 @noindent
20986 If the project @code{proj} depends upon other projects, you can perform
20987 checks on the project closure using the @option{-U} option:
20988 @smallexample
20989    gnat check -Pproj -U -rules -from=my_rules
20990 @end smallexample
20991
20992 @noindent
20993 Finally, if not all the units are relevant to a particular main
20994 program in the project closure, you can perform checks for the set
20995 of units needed to create a given main program (unit closure) using
20996 the @option{-U} option followed by the name of the main unit:
20997 @smallexample
20998    gnat check -Pproj -U main -rules -from=my_rules
20999 @end smallexample
21000
21001
21002 @node Rule exemption
21003 @section Rule exemption
21004 @cindex Rule exemption (for @command{gnatcheck})
21005
21006 @noindent
21007 One of the most useful applications of @command{gnatcheck} is to
21008 automate the enforcement of project-specific coding standards,
21009 for example in safety-critical systems where particular features
21010 must be restricted in order to simplify the certification effort.
21011 However, it may sometimes be appropriate to violate a coding standard rule,
21012 and in such cases the rationale for the violation should be provided
21013 in the source program itself so that the individuals
21014 reviewing or maintaining the program can immediately understand the intent.
21015
21016 The @command{gnatcheck} tool supports this practice with the notion of
21017 a ``rule exemption'' covering a specific source code section. Normally
21018 rule violation messages are issued both on @file{stderr}
21019 and in a report file. In contrast, exempted violations are not listed on
21020 @file{stderr}; thus users invoking @command{gnatcheck} interactively
21021 (e.g. in its GPS interface) do not need to pay attention to known and
21022 justified violations. However, exempted violations along with their
21023 justification are documented in a special section of the report file that
21024 @command{gnatcheck} generates.
21025
21026 @menu
21027 * Using pragma Annotate to Control Rule Exemption::
21028 * gnatcheck Annotations Rules::
21029 @end menu
21030
21031 @node Using pragma Annotate to Control Rule Exemption
21032 @subsection Using pragma @code{Annotate} to Control Rule Exemption
21033 @cindex Using pragma Annotate to control rule exemption
21034
21035 @noindent
21036 Rule exemption is controlled by pragma @code{Annotate} when its first
21037 argument is ``gnatcheck''. The syntax of @command{gnatcheck}'s
21038 exemption control annotations is as follows:
21039
21040 @smallexample @c ada
21041 @group
21042 pragma Annotate (gnatcheck, @i{exemption_control}, @i{Rule_Name}, [@i{justification}]);
21043
21044 @i{exemption_control} ::= Exempt_On | Exempt_Off
21045
21046 @i{Rule_Name}         ::= string_literal
21047
21048 @i{justification}     ::= string_literal
21049 @end group
21050 @end smallexample
21051
21052 @noindent
21053 When a @command{gnatcheck} annotation has more then four arguments,
21054 @command{gnatcheck} issues a warning and ignores the additional arguments.
21055 If the additional arguments do not follow the syntax above,
21056 @command{gnatcheck} emits a warning and ignores the annotation.
21057
21058 The @i{@code{Rule_Name}} argument should be the name of some existing
21059 @command{gnatcheck} rule.
21060 Otherwise a warning message is generated and the pragma is
21061 ignored. If @code{Rule_Name} denotes a rule that is not activated by the given
21062 @command{gnatcheck} call, the pragma is ignored and no warning is issued.
21063
21064 A source code section where an exemption is active for a given rule is
21065 delimited by an @code{exempt_on} and @code{exempt_off} annotation pair:
21066
21067 @smallexample @c ada
21068 pragma Annotate (gnatcheck, Exempt_On, Rule_Name, "justification");
21069 -- source code section
21070 pragma Annotate (gnatcheck, Exempt_Off, Rule_Name);
21071 @end smallexample
21072
21073
21074 @node gnatcheck Annotations Rules
21075 @subsection @command{gnatcheck} Annotations Rules
21076 @cindex @command{gnatcheck} annotations rules
21077
21078 @itemize @bullet
21079
21080 @item
21081 An ``Exempt_Off'' annotation can only appear after a corresponding
21082 ``Exempt_On'' annotation.
21083
21084 @item
21085 Exempted source code sections are only based on the source location of the
21086 annotations. Any source construct between the two
21087 annotations is part of the exempted source code section.
21088
21089 @item
21090 Exempted source code sections for different rules are independent. They can
21091 be nested or intersect with one another without limitation.
21092 Creating nested or intersecting source code sections for the same rule is
21093 not allowed.
21094
21095 @item
21096 Malformed exempted source code sections are reported by a warning, and
21097 the corresponding rule exemptions are ignored.
21098
21099 @item
21100 When an exempted source code section does not contain at least one violation
21101 of the exempted rule, a warning is emitted on @file{stderr}.
21102
21103 @item
21104 If an ``Exempt_On'' annotation pragma does not have a matching
21105 ``Exempt_Off'' annotation pragma in the same compilation unit, then the
21106 exemption for the given rule is ignored and a warning is issued.
21107 @end itemize
21108
21109
21110 @node Predefined Rules
21111 @section Predefined Rules
21112 @cindex Predefined rules (for @command{gnatcheck})
21113
21114 @ignore
21115 @c (Jan 2007) Since the global rules are still under development and are not
21116 @c documented, there is no point in explaining the difference between
21117 @c global and local rules
21118 @noindent
21119 A rule in @command{gnatcheck} is either local or global.
21120 A @emph{local rule} is a rule that applies to a well-defined section
21121 of a program and that can be checked by analyzing only this section.
21122 A @emph{global rule} requires analysis of some global properties of the
21123 whole program (mostly related to the program call graph).
21124 As of @value{NOW}, the implementation of global rules should be
21125 considered to be at a preliminary stage. You can use the
21126 @option{+GLOBAL} option to enable all the global rules, and the
21127 @option{-GLOBAL} rule option to disable all the global rules.
21128
21129 All the global rules in the list below are
21130 so indicated by marking them ``GLOBAL''.
21131 This +GLOBAL and -GLOBAL options are not
21132 included in the list of gnatcheck options above, because at the moment they
21133 are considered as a temporary debug options.
21134
21135 @command{gnatcheck} performs rule checks for generic
21136 instances only for global rules.  This limitation may be relaxed in a later
21137 release.
21138 @end ignore
21139
21140 @noindent
21141 The following subsections document the rules implemented in
21142 @command{gnatcheck}.
21143 The subsection title is the same as the rule identifier, which may be
21144 used as a parameter of the @option{+R} or @option{-R} options.
21145
21146
21147 @menu
21148 * Abstract_Type_Declarations::
21149 * Anonymous_Arrays::
21150 * Anonymous_Subtypes::
21151 * Blocks::
21152 * Boolean_Relational_Operators::
21153 @ignore
21154 * Ceiling_Violations::
21155 @end ignore
21156 * Complex_Inlined_Subprograms::
21157 * Controlled_Type_Declarations::
21158 * Declarations_In_Blocks::
21159 * Deep_Inheritance_Hierarchies::
21160 * Deeply_Nested_Generics::
21161 * Deeply_Nested_Inlining::
21162 @ignore
21163 * Deeply_Nested_Local_Inlining::
21164 @end ignore
21165 * Default_Parameters::
21166 * Direct_Calls_To_Primitives::
21167 * Discriminated_Records::
21168 * Enumeration_Ranges_In_CASE_Statements::
21169 * Exceptions_As_Control_Flow::
21170 * Exits_From_Conditional_Loops::
21171 * EXIT_Statements_With_No_Loop_Name::
21172 * Expanded_Loop_Exit_Names::
21173 * Explicit_Full_Discrete_Ranges::
21174 * Float_Equality_Checks::
21175 * Forbidden_Attributes::
21176 * Forbidden_Pragmas::
21177 * Function_Style_Procedures::
21178 * Generics_In_Subprograms::
21179 * GOTO_Statements::
21180 * Implicit_IN_Mode_Parameters::
21181 * Implicit_SMALL_For_Fixed_Point_Types::
21182 * Improperly_Located_Instantiations::
21183 * Improper_Returns::
21184 * Library_Level_Subprograms::
21185 * Local_Packages::
21186 @ignore
21187 * Improperly_Called_Protected_Entries::
21188 @end ignore
21189 * Metrics::
21190 * Misnamed_Controlling_Parameters::
21191 * Misnamed_Identifiers::
21192 * Multiple_Entries_In_Protected_Definitions::
21193 * Name_Clashes::
21194 * Non_Qualified_Aggregates::
21195 * Non_Short_Circuit_Operators::
21196 * Non_SPARK_Attributes::
21197 * Non_Tagged_Derived_Types::
21198 * Non_Visible_Exceptions::
21199 * Numeric_Literals::
21200 * OTHERS_In_Aggregates::
21201 * OTHERS_In_CASE_Statements::
21202 * OTHERS_In_Exception_Handlers::
21203 * Outer_Loop_Exits::
21204 * Overloaded_Operators::
21205 * Overly_Nested_Control_Structures::
21206 * Parameters_Out_Of_Order::
21207 * Positional_Actuals_For_Defaulted_Generic_Parameters::
21208 * Positional_Actuals_For_Defaulted_Parameters::
21209 * Positional_Components::
21210 * Positional_Generic_Parameters::
21211 * Positional_Parameters::
21212 * Predefined_Numeric_Types::
21213 * Raising_External_Exceptions::
21214 * Raising_Predefined_Exceptions::
21215 * Separate_Numeric_Error_Handlers::
21216 @ignore
21217 * Recursion::
21218 * Side_Effect_Functions::
21219 @end ignore
21220 * Slices::
21221 * Too_Many_Parents::
21222 * Unassigned_OUT_Parameters::
21223 * Uncommented_BEGIN_In_Package_Bodies::
21224 * Unconditional_Exits::
21225 * Unconstrained_Array_Returns::
21226 * Universal_Ranges::
21227 * Unnamed_Blocks_And_Loops::
21228 @ignore
21229 * Unused_Subprograms::
21230 @end ignore
21231 * USE_PACKAGE_Clauses::
21232 * Visible_Components::
21233 * Volatile_Objects_Without_Address_Clauses::
21234 @end menu
21235
21236
21237 @node Abstract_Type_Declarations
21238 @subsection @code{Abstract_Type_Declarations}
21239 @cindex @code{Abstract_Type_Declarations} rule (for @command{gnatcheck})
21240
21241 @noindent
21242 Flag all declarations of abstract types. For an abstract private
21243 type, both the private and full type declarations are flagged.
21244
21245 This rule has no parameters.
21246
21247
21248 @node Anonymous_Arrays
21249 @subsection @code{Anonymous_Arrays}
21250 @cindex @code{Anonymous_Arrays} rule (for @command{gnatcheck})
21251
21252 @noindent
21253 Flag all anonymous array type definitions (by Ada semantics these can only
21254 occur in object declarations).
21255
21256 This rule has no parameters.
21257
21258 @node Anonymous_Subtypes
21259 @subsection @code{Anonymous_Subtypes}
21260 @cindex @code{Anonymous_Subtypes} rule (for @command{gnatcheck})
21261
21262 @noindent
21263 Flag all uses of anonymous subtypes (except cases when subtype indication
21264 is a part of a record component definition, and this subtype indication
21265 depends on a discriminant). A use of an anonymous subtype is
21266 any instance of a subtype indication with a constraint, other than one
21267 that occurs immediately within a subtype declaration. Any use of a range
21268 other than as a constraint used immediately within a subtype declaration
21269 is considered as an anonymous subtype.
21270
21271 An effect of this rule is that @code{for} loops such as the following are
21272 flagged (since @code{1..N} is formally a ``range''):
21273
21274 @smallexample @c ada
21275 for I in 1 .. N loop
21276    @dots{}
21277 end loop;
21278 @end smallexample
21279
21280 @noindent
21281 Declaring an explicit subtype solves the problem:
21282
21283 @smallexample @c ada
21284 subtype S is Integer range 1..N;
21285 @dots{}
21286 for I in S loop
21287    @dots{}
21288 end loop;
21289 @end smallexample
21290
21291 @noindent
21292 This rule has no parameters.
21293
21294 @node Blocks
21295 @subsection @code{Blocks}
21296 @cindex @code{Blocks} rule (for @command{gnatcheck})
21297
21298 @noindent
21299 Flag each block statement.
21300
21301 This rule has no parameters.
21302
21303 @node Boolean_Relational_Operators
21304 @subsection @code{Boolean_Relational_Operators}
21305 @cindex @code{Boolean_Relational_Operators} rule (for @command{gnatcheck})
21306
21307 @noindent
21308 Flag each call to a predefined relational operator (``<'', ``>'', ``<='',
21309 ``>='', ``='' and ``/='') for the predefined Boolean type.
21310 (This rule is useful in enforcing the SPARK language restrictions.)
21311
21312 Calls to predefined relational operators of any type derived from
21313 @code{Standard.Boolean} are not detected.  Calls to user-defined functions
21314 with these designators, and uses of operators that are renamings
21315 of the predefined relational operators for @code{Standard.Boolean},
21316 are likewise not detected.
21317
21318 This rule has no parameters.
21319
21320 @ignore
21321 @node Ceiling_Violations
21322 @subsection @code{Ceiling5_Violations} (under construction, GLOBAL)
21323 @cindex @code{Ceiling_Violations} rule (for @command{gnatcheck})
21324
21325 @noindent
21326 Flag invocations of a protected operation by a task whose priority exceeds
21327 the protected object's ceiling.
21328
21329 As of @value{NOW}, this rule has the following limitations:
21330
21331 @itemize @bullet
21332
21333 @item
21334  We consider only pragmas Priority and Interrupt_Priority as means to define
21335   a task/protected operation priority. We do not consider the effect of using
21336   Ada.Dynamic_Priorities.Set_Priority procedure;
21337
21338 @item
21339  We consider only base task priorities, and no priority inheritance. That is,
21340   we do not make a difference between calls issued during task activation and
21341   execution of the sequence of statements from task body;
21342
21343 @item
21344  Any situation when the priority of protected operation caller is set by a
21345   dynamic expression (that is, the corresponding Priority or
21346   Interrupt_Priority pragma has a non-static expression as an argument) we
21347   treat as a priority inconsistency (and, therefore, detect this situation).
21348 @end itemize
21349
21350 @noindent
21351 At the moment the notion of the main subprogram is not implemented in
21352 gnatcheck, so any pragma Priority in a library level subprogram body (in case
21353 if this subprogram can be a main subprogram of a partition) changes the
21354 priority of an environment task. So if we have more then one such pragma in
21355 the set of processed sources, the pragma that is processed last, defines the
21356 priority of an environment task.
21357
21358 This rule has no parameters.
21359 @end ignore
21360
21361 @node Controlled_Type_Declarations
21362 @subsection @code{Controlled_Type_Declarations}
21363 @cindex @code{Controlled_Type_Declarations} rule (for @command{gnatcheck})
21364
21365 @noindent
21366 Flag all declarations of controlled types. A declaration of a private type
21367 is flagged if its full declaration declares a controlled type. A declaration
21368 of a derived type is flagged if its ancestor type is controlled. Subtype
21369 declarations are not checked. A declaration of a type that itself is not a
21370 descendant of a type declared in @code{Ada.Finalization} but has a controlled
21371 component is not checked.
21372
21373 This rule has no parameters.
21374
21375
21376 @node Complex_Inlined_Subprograms
21377 @subsection @code{Complex_Inlined_Subprograms}
21378 @cindex @code{Complex_Inlined_Subprograms} rule (for @command{gnatcheck})
21379
21380 @noindent
21381 Flags a subprogram (or generic subprogram) if
21382 pragma Inline is applied to the subprogram and at least one of the following
21383 conditions is met:
21384
21385 @itemize @bullet
21386 @item
21387 it contains at least one complex declaration such as a subprogram body,
21388 package, task, protected declaration, or a generic instantiation
21389 (except instantiation of @code{Ada.Unchecked_Conversion});
21390
21391 @item
21392 it contains at least one complex statement such as a loop, a case
21393 or a if statement, or a short circuit control form;
21394
21395 @item
21396 the number of statements exceeds
21397 a value specified by the @option{N} rule parameter;
21398 @end itemize
21399
21400 @noindent
21401 This rule has the following (mandatory) parameter for the @option{+R} option:
21402
21403 @table @emph
21404 @item N
21405 Positive integer specifying the maximum allowed total number of statements
21406 in the subprogram body.
21407 @end table
21408
21409
21410 @node Declarations_In_Blocks
21411 @subsection @code{Declarations_In_Blocks}
21412 @cindex @code{Declarations_In_Blocks} rule (for @command{gnatcheck})
21413
21414 @noindent
21415 Flag all block statements containing local declarations. A @code{declare}
21416 block with an empty @i{declarative_part} or with a @i{declarative part}
21417 containing only pragmas and/or @code{use} clauses is not flagged.
21418
21419 This rule has no parameters.
21420
21421
21422 @node Deep_Inheritance_Hierarchies
21423 @subsection @code{Deep_Inheritance_Hierarchies}
21424 @cindex @code{Deep_Inheritance_Hierarchies} rule (for @command{gnatcheck})
21425
21426 @noindent
21427 Flags a tagged derived type declaration or an interface type declaration if
21428 its depth (in its inheritance
21429 hierarchy) exceeds the value specified by the @option{N} rule parameter.
21430
21431 The inheritance depth of a tagged type or interface type is defined as 0 for
21432 a type  with no parent and no progenitor, and otherwise as 1 + max of the
21433 depths of the immediate parent and immediate progenitors.
21434
21435 This rule does not flag private extension
21436 declarations. In the case of a private extension, the corresponding full
21437 declaration is checked.
21438
21439 This rule has the following (mandatory) parameter for the @option{+R} option:
21440
21441 @table @emph
21442 @item N
21443 Integer not less than -1 specifying the maximal allowed depth of any inheritance
21444 hierarchy. If the rule parameter is set to -1, the rule flags all the declarations
21445 of tagged and interface types.
21446 @end table
21447
21448
21449 @node Deeply_Nested_Generics
21450 @subsection @code{Deeply_Nested_Generics}
21451 @cindex @code{Deeply_Nested_Generics} rule (for @command{gnatcheck})
21452
21453 @noindent
21454 Flags a generic declaration nested in another generic declaration if
21455 the nesting level of the inner generic exceeds
21456 a value specified by the @option{N} rule parameter.
21457 The nesting level is the number of generic declaratons that enclose the given
21458 (generic) declaration. Formal packages are not flagged by this rule.
21459
21460 This rule has the following (mandatory) parameters for the @option{+R} option:
21461
21462 @table @emph
21463 @item N
21464 Positive integer specifying the maximal allowed nesting level
21465 for a generic declaration.
21466 @end table
21467
21468 @node Deeply_Nested_Inlining
21469 @subsection @code{Deeply_Nested_Inlining}
21470 @cindex @code{Deeply_Nested_Inlining} rule (for @command{gnatcheck})
21471
21472 @noindent
21473 Flags a subprogram (or generic subprogram) if
21474 pragma Inline has been applied to the subprogram but the subprogram
21475 calls to another inlined subprogram that results in nested inlining
21476 with nesting depth exceeding the value specified by the
21477 @option{N} rule parameter.
21478
21479 This rule requires the global analysis of all the compilation units that
21480 are @command{gnatcheck} arguments; such analysis may affect the tool's
21481 performance.
21482
21483 This rule has the following (mandatory) parameter for the @option{+R} option:
21484
21485 @table @emph
21486 @item N
21487 Positive integer specifying the maximal allowed level of nested inlining.
21488 @end table
21489
21490
21491 @ignore
21492 @node Deeply_Nested_Local_Inlining
21493 @subsection @code{Deeply_Nested_Local_Inlining}
21494 @cindex @code{Deeply_Nested_Local_Inlining} rule (for @command{gnatcheck})
21495
21496 @noindent
21497 Flags a subprogram body if a pragma @code{Inline} is applied to the
21498 corresponding subprogram (or generic subprogram) and the body contains a call
21499 to another inlined subprogram that results in nested inlining with nesting
21500 depth more then a value specified by the @option{N} rule parameter.
21501 This rule is similar to @code{Deeply_Nested_Inlining} rule, but it
21502 assumes that calls to subprograms in
21503 with'ed units are not inlided, so all the analysis of the depth of inlining is
21504 limited by the compilation unit where the subprogram body is located and the
21505 units it depends semantically upon. Such analysis may be usefull for the case
21506 when neiter @option{-gnatn} nor @option{-gnatN} option is used when building
21507 the executable.
21508
21509 This rule has the following (mandatory) parameters for the @option{+R} option:
21510
21511 @table @emph
21512 @item N
21513 Positive integer specifying the maximal allowed level of nested inlining.
21514 @end table
21515
21516 @end ignore
21517
21518 @node Default_Parameters
21519 @subsection @code{Default_Parameters}
21520 @cindex @code{Default_Parameters} rule (for @command{gnatcheck})
21521
21522 @noindent
21523 Flag all default expressions for subprogram parameters. Parameter
21524 declarations of formal and generic subprograms are also checked.
21525
21526 This rule has no parameters.
21527
21528
21529 @node Direct_Calls_To_Primitives
21530 @subsection @code{Direct_Calls_To_Primitives}
21531 @cindex @code{Direct_Calls_To_Primitives} rule (for @command{gnatcheck})
21532
21533 @noindent
21534 Flags any non-dispatching call to a dispatching primitive operation, except
21535 for the common idiom where a primitive subprogram for a tagged type
21536 directly calls the same primitive subprogram of the type's immediate ancestor.
21537
21538 This rule has no parameters.
21539
21540
21541 @node Discriminated_Records
21542 @subsection @code{Discriminated_Records}
21543 @cindex @code{Discriminated_Records} rule (for @command{gnatcheck})
21544
21545 @noindent
21546 Flag all declarations of record types with discriminants. Only the
21547 declarations of record and record extension types are checked. Incomplete,
21548 formal, private, derived and private extension type declarations are not
21549 checked. Task and protected type declarations also are not checked.
21550
21551 This rule has no parameters.
21552
21553
21554 @node Enumeration_Ranges_In_CASE_Statements
21555 @subsection @code{Enumeration_Ranges_In_CASE_Statements}
21556 @cindex @code{Enumeration_Ranges_In_CASE_Statements} (for @command{gnatcheck})
21557
21558 @noindent
21559 Flag each use of a range of enumeration literals as a choice in a
21560 @code{case} statement.
21561 All forms for specifying a range (explicit ranges
21562 such as @code{A .. B}, subtype marks and @code{'Range} attributes) are flagged.
21563 An enumeration range is
21564 flagged even if contains exactly one enumeration value or no values at all. A
21565 type derived from an enumeration type is considered as an enumeration type.
21566
21567 This rule helps prevent maintenance problems arising from adding an
21568 enumeration value to a type and having it implicitly handled by an existing
21569 @code{case} statement with an enumeration range that includes the new literal.
21570
21571 This rule has no parameters.
21572
21573
21574 @node Exceptions_As_Control_Flow
21575 @subsection @code{Exceptions_As_Control_Flow}
21576 @cindex @code{Exceptions_As_Control_Flow} (for @command{gnatcheck})
21577
21578 @noindent
21579 Flag each place where an exception is explicitly raised and handled in the
21580 same subprogram body. A @code{raise} statement in an exception handler,
21581 package body, task body or entry body is not flagged.
21582
21583 The rule has no parameters.
21584
21585 @node Exits_From_Conditional_Loops
21586 @subsection @code{Exits_From_Conditional_Loops}
21587 @cindex @code{Exits_From_Conditional_Loops} (for @command{gnatcheck})
21588
21589 @noindent
21590 Flag any exit statement if it transfers the control out of a @code{for} loop
21591 or a @code{while} loop. This includes cases when the @code{exit} statement
21592 applies to a @code{FOR} or @code{while} loop, and cases when it is enclosed
21593 in some @code{for} or @code{while} loop, but transfers the control from some
21594 outer (inconditional) @code{loop} statement.
21595
21596 The rule has no parameters.
21597
21598
21599 @node EXIT_Statements_With_No_Loop_Name
21600 @subsection @code{EXIT_Statements_With_No_Loop_Name}
21601 @cindex @code{EXIT_Statements_With_No_Loop_Name} (for @command{gnatcheck})
21602
21603 @noindent
21604 Flag each @code{exit} statement that does not specify the name of the loop
21605 being exited.
21606
21607 The rule has no parameters.
21608
21609
21610 @node Expanded_Loop_Exit_Names
21611 @subsection @code{Expanded_Loop_Exit_Names}
21612 @cindex @code{Expanded_Loop_Exit_Names} rule (for @command{gnatcheck})
21613
21614 @noindent
21615 Flag all expanded loop names in @code{exit} statements.
21616
21617 This rule has no parameters.
21618
21619 @node Explicit_Full_Discrete_Ranges
21620 @subsection @code{Explicit_Full_Discrete_Ranges}
21621 @cindex @code{Explicit_Full_Discrete_Ranges} rule (for @command{gnatcheck})
21622
21623 @noindent
21624 Flag each discrete range that has the form @code{A'First .. A'Last}.
21625
21626 This rule has no parameters.
21627
21628 @node Float_Equality_Checks
21629 @subsection @code{Float_Equality_Checks}
21630 @cindex @code{Float_Equality_Checks} rule (for @command{gnatcheck})
21631
21632 @noindent
21633 Flag all calls to the predefined equality operations for floating-point types.
21634 Both ``@code{=}'' and ``@code{/=}'' operations are checked.
21635 User-defined equality operations are not flagged, nor are ``@code{=}''
21636 and ``@code{/=}'' operations for fixed-point types.
21637
21638 This rule has no parameters.
21639
21640
21641 @node Forbidden_Attributes
21642 @subsection @code{Forbidden_Attributes}
21643 @cindex @code{Forbidden_Attributes} rule (for @command{gnatcheck})
21644
21645 @noindent
21646 Flag each use of the specified attributes. The attributes to be detected are
21647 named in the rule's parameters.
21648
21649 This rule has the following parameters:
21650
21651 @itemize @bullet
21652 @item For the @option{+R} option
21653
21654 @table @asis
21655 @item @emph{Attribute_Designator}
21656 Adds the specified attribute to the set of attributes to be detected and sets
21657 the detection checks for all the specified attributes ON.
21658 If @emph{Attribute_Designator}
21659 does not denote any attribute defined in the Ada standard
21660 or in
21661 @ref{Implementation Defined Attributes,,, gnat_rm, GNAT Reference
21662 Manual}, it is treated as the name of unknown attribute.
21663
21664 @item @code{GNAT}
21665 All the GNAT-specific attributes are detected; this sets
21666 the detection checks for all the specified attributes ON.
21667
21668 @item @code{ALL}
21669 All attributes are detected; this sets the rule ON.
21670 @end table
21671
21672 @item For the @option{-R} option
21673 @table @asis
21674 @item @emph{Attribute_Designator}
21675 Removes the specified attribute from the set of attributes to be
21676 detected without affecting detection checks for
21677 other attributes. If @emph{Attribute_Designator} does not correspond to any
21678 attribute defined in the Ada standard or in
21679 @ref{Implementation Defined Attributes,,, gnat_rm, GNAT Reference Manual},
21680 this option is treated as turning OFF detection of all unknown attributes.
21681
21682 @item GNAT
21683 Turn OFF detection of all GNAT-specific attributes
21684
21685 @item ALL
21686 Clear the list of the attributes to be detected and
21687 turn the rule OFF.
21688 @end table
21689 @end itemize
21690
21691 @noindent
21692 Parameters are not case sensitive. If @emph{Attribute_Designator} does not
21693 have the syntax of an Ada identifier and therefore can not be considered as a
21694 (part of an) attribute designator, a diagnostic message is generated and the
21695 corresponding parameter is ignored. (If an attribute allows a static
21696 expression to be a part of the attribute designator, this expression is
21697 ignored by this rule.)
21698
21699 When more then one parameter is given in the same rule option, the parameters
21700 must be separated by commas.
21701
21702 If more then one option for this rule is specified for the gnatcheck call, a
21703 new option overrides the previous one(s).
21704
21705 The @option{+R} option with no parameters turns the rule ON, with the set of
21706 attributes to be detected defined by the previous rule options.
21707 (By default this set is empty, so if the only option specified for the rule is
21708 @option{+RForbidden_Attributes} (with
21709 no parameter), then the rule is enabled, but it does not detect anything).
21710 The @option{-R} option with no parameter turns the rule OFF, but it does not
21711 affect the set of attributes to be detected.
21712
21713
21714 @node Forbidden_Pragmas
21715 @subsection @code{Forbidden_Pragmas}
21716 @cindex @code{Forbidden_Pragmas} rule (for @command{gnatcheck})
21717
21718 @noindent
21719 Flag each use of the specified pragmas.  The pragmas to be detected
21720 are named in the rule's  parameters.
21721
21722 This rule has the following parameters:
21723
21724 @itemize @bullet
21725 @item For the @option{+R} option
21726
21727 @table @asis
21728 @item @emph{Pragma_Name}
21729 Adds the specified pragma to the set of pragmas to be
21730 checked and sets the checks for all the specified pragmas
21731 ON. @emph{Pragma_Name} is treated as a name of a pragma. If it
21732 does not correspond to any pragma name defined in the Ada
21733 standard or to the name of a GNAT-specific pragma defined
21734 in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference
21735 Manual}, it is treated as the name of unknown pragma.
21736
21737 @item @code{GNAT}
21738 All the GNAT-specific pragmas are detected; this sets
21739 the checks for all the specified pragmas ON.
21740
21741 @item @code{ALL}
21742 All pragmas are detected; this sets the rule ON.
21743 @end table
21744
21745 @item For the @option{-R} option
21746 @table @asis
21747 @item @emph{Pragma_Name}
21748 Removes the specified pragma from the set of pragmas to be
21749 checked without affecting checks for
21750 other pragmas. @emph{Pragma_Name} is treated as a name
21751 of a pragma. If it does not correspond to any pragma
21752 defined in the Ada standard or to any name defined in
21753 @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
21754 this option is treated as turning OFF detection of all unknown pragmas.
21755
21756 @item GNAT
21757 Turn OFF detection of all GNAT-specific pragmas
21758
21759 @item ALL
21760 Clear the list of the pragmas to be detected and
21761 turn the rule OFF.
21762 @end table
21763 @end itemize
21764
21765 @noindent
21766 Parameters are not case sensitive. If @emph{Pragma_Name} does not have
21767 the syntax of an Ada identifier and therefore can not be considered
21768 as a pragma name, a diagnostic message is generated and the corresponding
21769 parameter is ignored.
21770
21771 When more then one parameter is given in the same rule option, the parameters
21772 must be separated by a comma.
21773
21774 If more then one option for this rule is specified for the @command{gnatcheck}
21775 call, a new option overrides the previous one(s).
21776
21777 The @option{+R} option with no parameters turns the rule ON with the set of
21778 pragmas to be detected defined by the previous rule options.
21779 (By default this set is empty, so if the only option specified for the rule is
21780 @option{+RForbidden_Pragmas} (with
21781 no parameter), then the rule is enabled, but it does not detect anything).
21782 The @option{-R} option with no parameter turns the rule OFF, but it does not
21783 affect the set of pragmas to be detected.
21784
21785
21786
21787
21788 @node Function_Style_Procedures
21789 @subsection @code{Function_Style_Procedures}
21790 @cindex @code{Function_Style_Procedures} rule (for @command{gnatcheck})
21791
21792 @noindent
21793 Flag each procedure that can be rewritten as a function. A procedure can be
21794 converted into a function if it has exactly one parameter of mode @code{out}
21795 and no parameters of mode @code{in out}. Procedure declarations,
21796 formal procedure declarations, and generic procedure declarations are always
21797 checked. Procedure
21798 bodies and body stubs are flagged only if they do not have corresponding
21799 separate declarations. Procedure renamings and procedure instantiations are
21800 not flagged.
21801
21802 If a procedure can be rewritten as a function, but its @code{out} parameter is
21803 of a limited type, it is not flagged.
21804
21805 Protected procedures are not flagged. Null procedures also are not flagged.
21806
21807 This rule has no parameters.
21808
21809
21810 @node Generics_In_Subprograms
21811 @subsection @code{Generics_In_Subprograms}
21812 @cindex @code{Generics_In_Subprograms} rule (for @command{gnatcheck})
21813
21814 @noindent
21815 Flag each declaration of a generic unit in a subprogram. Generic
21816 declarations in the bodies of generic subprograms are also flagged.
21817 A generic unit nested in another generic unit is not flagged.
21818 If a generic unit is
21819 declared in a local package that is declared in a subprogram body, the
21820 generic unit is flagged.
21821
21822 This rule has no parameters.
21823
21824
21825 @node GOTO_Statements
21826 @subsection @code{GOTO_Statements}
21827 @cindex @code{GOTO_Statements} rule (for @command{gnatcheck})
21828
21829 @noindent
21830 Flag each occurrence of a @code{goto} statement.
21831
21832 This rule has no parameters.
21833
21834
21835 @node Implicit_IN_Mode_Parameters
21836 @subsection @code{Implicit_IN_Mode_Parameters}
21837 @cindex @code{Implicit_IN_Mode_Parameters} rule (for @command{gnatcheck})
21838
21839 @noindent
21840 Flag each occurrence of a formal parameter with an implicit @code{in} mode.
21841 Note that @code{access} parameters, although they technically behave
21842 like @code{in} parameters, are not flagged.
21843
21844 This rule has no parameters.
21845
21846
21847 @node Implicit_SMALL_For_Fixed_Point_Types
21848 @subsection @code{Implicit_SMALL_For_Fixed_Point_Types}
21849 @cindex @code{Implicit_SMALL_For_Fixed_Point_Types} rule (for @command{gnatcheck})
21850
21851 @noindent
21852 Flag each fixed point type declaration that lacks an explicit
21853 representation  clause to define its @code{'Small} value.
21854 Since @code{'Small} can be  defined only for ordinary fixed point types,
21855 decimal fixed point type declarations are not checked.
21856
21857 This rule has no parameters.
21858
21859
21860 @node Improperly_Located_Instantiations
21861 @subsection @code{Improperly_Located_Instantiations}
21862 @cindex @code{Improperly_Located_Instantiations} rule (for @command{gnatcheck})
21863
21864 @noindent
21865 Flag all generic instantiations in library-level package specs
21866 (including library generic packages) and in all subprogram bodies.
21867
21868 Instantiations in task and entry bodies are not flagged. Instantiations in the
21869 bodies of protected subprograms are flagged.
21870
21871 This rule has no parameters.
21872
21873
21874
21875 @node Improper_Returns
21876 @subsection @code{Improper_Returns}
21877 @cindex @code{Improper_Returns} rule (for @command{gnatcheck})
21878
21879 @noindent
21880 Flag each explicit @code{return} statement in procedures, and
21881 multiple @code{return} statements in functions.
21882 Diagnostic messages are generated for all @code{return} statements
21883 in a procedure (thus each procedure must be written so that it
21884 returns implicitly at the end of its statement part),
21885 and for all @code{return} statements in a function after the first one.
21886 This rule supports the stylistic convention that each subprogram
21887 should have no more than one point of normal return.
21888
21889 This rule has no parameters.
21890
21891
21892 @node Library_Level_Subprograms
21893 @subsection @code{Library_Level_Subprograms}
21894 @cindex @code{Library_Level_Subprograms} rule (for @command{gnatcheck})
21895
21896 @noindent
21897 Flag all library-level subprograms (including generic subprogram instantiations).
21898
21899 This rule has no parameters.
21900
21901
21902 @node Local_Packages
21903 @subsection @code{Local_Packages}
21904 @cindex @code{Local_Packages} rule (for @command{gnatcheck})
21905
21906 @noindent
21907 Flag all local packages declared in package and generic package
21908 specs.
21909 Local packages in bodies are not flagged.
21910
21911 This rule has no parameters.
21912
21913 @ignore
21914 @node Improperly_Called_Protected_Entries
21915 @subsection @code{Improperly_Called_Protected_Entries} (under construction, GLOBAL)
21916 @cindex @code{Improperly_Called_Protected_Entries} rule (for @command{gnatcheck})
21917
21918 @noindent
21919 Flag each protected entry that can be called from more than one task.
21920
21921 This rule has no parameters.
21922 @end ignore
21923
21924 @node Metrics
21925 @subsection @code{Metrics}
21926 @cindex @code{Metrics} rule (for @command{gnatcheck})
21927
21928 @noindent
21929 There is a set of checks based on computing a metric value and comparing the
21930 result with the specified upper (or lower, depending on a specific metric)
21931 value specified for a given metric. A construct is flagged if a given metric
21932 is applicable (can be computed) for it and the computed value is greater
21933 then (lover then) the specified upper (lower) bound.
21934
21935 The name of any metric-based rule consists of the prefix @code{Metrics_}
21936 followed by the name of the corresponding metric (see the table below).
21937 For @option{+R} option, each metric-based rule has a numeric parameter
21938 specifying the bound (integer or real, depending on a metric), @option{-R}
21939 option for metric rules does not have a parameter.
21940
21941 The following table shows the metric names for that the corresponding
21942 metrics-based checks are supported by gnatcheck, including the
21943 constraint that must be satisfied by the bound that is specified for the check
21944 and what bound - upper (U) or lower (L) - should be specified.
21945
21946 @multitable {@code{Cyclomatic_Complexity}}{Cyclomatic complexity}{Positive integer}
21947 @ifnothtml
21948 @headitem Check Name @tab Description @tab Bounds Value
21949 @end ifnothtml
21950 @ifhtml
21951 @item @b{Check Name} @tab @b{Description} @tab @b{Bounds Value}
21952 @end ifhtml
21953 @c Above conditional code is workaround to bug in texi2html (Feb 2008)
21954 @item @code{Essential_Complexity} @tab Essential complexity @tab Positive integer (U)
21955 @item @code{Cyclomatic_Complexity} @tab Cyclomatic complexity @tab Positive integer (U)
21956 @item @code{LSLOC} @tab Logical Source Lines of Code @tab Positive integer (U)
21957 @end multitable
21958
21959 @noindent
21960 The meaning and the computed values for all these metrics are exactly
21961 the same as for the corresponding metrics in @command{gnatmetric}.
21962
21963 @emph{Example:} the rule
21964 @smallexample
21965 +RMetrics_Cyclomatic_Complexity : 7
21966 @end smallexample
21967 @noindent
21968 means that all bodies with cyclomatic complexity exceeding 7 will be flagged.
21969
21970 To turn OFF the check for cyclomatic complexity metric, use the following option:
21971 @smallexample
21972 -RMetrics_Cyclomatic_Complexity
21973 @end smallexample
21974
21975
21976 @node Misnamed_Controlling_Parameters
21977 @subsection @code{Misnamed_Controlling_Parameters}
21978 @cindex @code{Misnamed_Controlling_Parameters} rule (for @command{gnatcheck})
21979
21980 @noindent
21981 Flags a declaration of a dispatching operation, if the first parameter is
21982 not a controlling one and its name is not @code{This} (the check for
21983 parameter name is not case-sensitive). Declarations of dispatching functions
21984 with controlling result and no controlling parameter are never flagged.
21985
21986 A subprogram body declaration, subprogram renaming declaration or subprogram
21987 body stub is flagged only if it is not a completion of a prior subprogram
21988 declaration.
21989
21990 This rule has no parameters.
21991
21992
21993
21994 @node Misnamed_Identifiers
21995 @subsection @code{Misnamed_Identifiers}
21996 @cindex @code{Misnamed_Identifiers} rule (for @command{gnatcheck})
21997
21998 @noindent
21999 Flag the declaration of each identifier that does not have a suffix
22000 corresponding to the kind of entity being declared.
22001 The following declarations are checked:
22002
22003 @itemize @bullet
22004 @item
22005 type declarations
22006
22007 @item
22008 subtype declarations
22009
22010 @item
22011 constant declarations (but not number declarations)
22012
22013 @item
22014 package renaming declarations (but not generic package renaming
22015 declarations)
22016 @end itemize
22017
22018 @noindent
22019 This rule may have parameters. When used without parameters, the rule enforces
22020 the following checks:
22021
22022 @itemize @bullet
22023 @item
22024 type-defining names end with @code{_T}, unless the type is an access type,
22025 in which case the suffix must be @code{_A}
22026 @item
22027 constant names end with @code{_C}
22028 @item
22029 names defining package renamings end with @code{_R}
22030 @end itemize
22031
22032 @noindent
22033 Defining identifiers from incomplete type declarations are never flagged.
22034
22035 For a private type declaration (including private extensions), the defining
22036 identifier from the private type declaration is checked against the type
22037 suffix (even if the corresponding full declaration is an access type
22038 declaration), and the defining identifier from the corresponding full type
22039 declaration is not checked.
22040
22041 @noindent
22042 For a deferred constant, the defining name in the corresponding full constant
22043 declaration is not checked.
22044
22045 Defining names of formal types are not checked.
22046
22047 The rule may have the following parameters:
22048
22049 @itemize @bullet
22050 @item
22051 For the @option{+R} option:
22052 @table @code
22053 @item Default
22054 Sets the default listed above for all the names to be checked.
22055
22056 @item Type_Suffix=@emph{string}
22057 Specifies the suffix for a type name.
22058
22059 @item Access_Suffix=@emph{string}
22060 Specifies the suffix for an access type name. If
22061 this parameter is set, it overrides for access
22062 types the suffix set by the @code{Type_Suffix} parameter.
22063 For access types, @emph{string} may have the following format:
22064 @emph{suffix1(suffix2)}. That means that an access type name
22065 should have the @emph{suffix1} suffix except for the case when
22066 the designated type is also an access type, in this case the
22067 type name should have the @emph{suffix1 & suffix2} suffix.
22068
22069 @item Class_Access_Suffix=@emph{string}
22070 Specifies the suffix for the name of an access type that points to some class-wide
22071 type. If this parameter is set, it overrides for such access
22072 types the suffix set by the @code{Type_Suffix} or @code{Access_Suffix}
22073 parameter.
22074
22075 @item Class_Subtype_Suffix=@emph{string}
22076 Specifies the suffix for the name of a subtype that denotes a class-wide type.
22077
22078 @item Constant_Suffix=@emph{string}
22079 Specifies the suffix for a constant name.
22080
22081 @item Renaming_Suffix=@emph{string}
22082 Specifies the suffix for a package renaming name.
22083 @end table
22084
22085 @item
22086 For the @option{-R} option:
22087 @table @code
22088 @item All_Suffixes
22089 Remove all the suffixes specified for the
22090 identifier suffix checks, whether by default or
22091 as specified by other rule parameters. All the
22092 checks for this rule are disabled as a result.
22093
22094 @item Type_Suffix
22095 Removes the suffix specified for types. This
22096 disables checks for types but does not disable
22097 any other checks for this rule (including the
22098 check for access type names if @code{Access_Suffix} is
22099 set).
22100
22101 @item Access_Suffix
22102 Removes the suffix specified for access types.
22103 This disables checks for access type names but
22104 does not disable any other checks for this rule.
22105 If @code{Type_Suffix} is set, access type names are
22106 checked as ordinary type names.
22107
22108 @item Class_Access_Suffix
22109 Removes the suffix specified for access types pointing to class-wide
22110 type. This disables specific checks for names of access types pointing to
22111 class-wide types but does not disable any other checks for this rule.
22112 If @code{Type_Suffix} is set, access type names are
22113 checked as ordinary type names. If @code{Access_Suffix} is set, these
22114 access types are checked as any other access type name.
22115
22116 @item Class_Subtype_Suffix=@emph{string}
22117 Removes the suffix specified for subtype names.
22118 This disables checks for subtype names but
22119 does not disable any other checks for this rule.
22120
22121 @item Constant_Suffix
22122 Removes the suffix specified for constants. This
22123 disables checks for constant names but does not
22124 disable any other checks for this rule.
22125
22126 @item Renaming_Suffix
22127 Removes the suffix specified for package
22128 renamings. This disables checks for package
22129 renamings but does not disable any other checks
22130 for this rule.
22131 @end table
22132 @end itemize
22133
22134 @noindent
22135 If more than one parameter is used, parameters must be separated by commas.
22136
22137 If more than one  option is specified for the @command{gnatcheck} invocation,
22138 a new option overrides the previous one(s).
22139
22140 The @option{+RMisnamed_Identifiers} option (with no parameter) enables
22141 checks for all the
22142 name suffixes specified by previous options used for this rule.
22143
22144 The @option{-RMisnamed_Identifiers} option (with no parameter) disables
22145 all the checks but keeps
22146 all the suffixes specified by previous options used for this rule.
22147
22148 The @emph{string} value must be a valid suffix for an Ada identifier (after
22149 trimming all the leading and trailing space characters, if any).
22150 Parameters are not case sensitive, except the @emph{string} part.
22151
22152 If any error is detected in a rule parameter, the parameter is ignored.
22153 In such a case the options that are set for the rule are not
22154 specified.
22155
22156
22157
22158 @node Multiple_Entries_In_Protected_Definitions
22159 @subsection @code{Multiple_Entries_In_Protected_Definitions}
22160 @cindex @code{Multiple_Entries_In_Protected_Definitions} rule (for @command{gnatcheck})
22161
22162 @noindent
22163 Flag each protected definition (i.e., each protected object/type declaration)
22164 that defines more than one entry.
22165 Diagnostic messages are generated for all the entry declarations
22166 except the first one. An entry family is counted as one entry. Entries from
22167 the private part of the protected definition are also checked.
22168
22169 This rule has no parameters.
22170
22171 @node Name_Clashes
22172 @subsection @code{Name_Clashes}
22173 @cindex @code{Name_Clashes} rule (for @command{gnatcheck})
22174
22175 @noindent
22176 Check that certain names are not used as defining identifiers. To activate
22177 this rule, you need to supply a reference to the dictionary file(s) as a rule
22178 parameter(s) (more then one dictionary file can be specified). If no
22179 dictionary file is set, this rule will not cause anything to be flagged.
22180 Only defining occurrences, not references, are checked.
22181 The check is not case-sensitive.
22182
22183 This rule is enabled by default, but without setting any corresponding
22184 dictionary file(s); thus the default effect is to do no checks.
22185
22186 A dictionary file is a plain text file. The maximum line length for this file
22187 is 1024 characters.  If the line is longer then this limit, extra characters
22188 are ignored.
22189
22190 Each line can be either an empty line, a comment line, or a line containing
22191 a list of identifiers separated by space or HT characters.
22192 A comment is an Ada-style comment (from @code{--} to end-of-line).
22193 Identifiers must follow the Ada syntax for identifiers.
22194 A line containing one or more identifiers may end with a comment.
22195
22196 @node Non_Qualified_Aggregates
22197 @subsection @code{Non_Qualified_Aggregates}
22198 @cindex @code{Non_Qualified_Aggregates} rule (for @command{gnatcheck})
22199
22200 @noindent
22201 Flag each non-qualified aggregate.
22202 A non-qualified aggregate is an
22203 aggregate that is not the expression of a qualified expression. A
22204 string literal is not considered an aggregate, but an array
22205 aggregate of a string type is considered as a normal aggregate.
22206 Aggregates of anonymous array types are not flagged.
22207
22208 This rule has no parameters.
22209
22210
22211 @node Non_Short_Circuit_Operators
22212 @subsection @code{Non_Short_Circuit_Operators}
22213 @cindex @code{Non_Short_Circuit_Operators} rule (for @command{gnatcheck})
22214
22215 @noindent
22216 Flag all calls to predefined @code{and} and @code{or} operators for
22217 any boolean type. Calls to
22218 user-defined @code{and} and @code{or} and to operators defined by renaming
22219 declarations are not flagged. Calls to predefined @code{and} and @code{or}
22220 operators for modular types or boolean array types are not flagged.
22221
22222 This rule has no parameters.
22223
22224
22225
22226 @node Non_SPARK_Attributes
22227 @subsection @code{Non_SPARK_Attributes}
22228 @cindex @code{Non_SPARK_Attributes} rule (for @command{gnatcheck})
22229
22230 @noindent
22231 The SPARK language defines the following subset of Ada 95 attribute
22232 designators as those that can be used in SPARK programs. The use of
22233 any other attribute is flagged.
22234
22235 @itemize @bullet
22236 @item @code{'Adjacent}
22237 @item @code{'Aft}
22238 @item @code{'Base}
22239 @item @code{'Ceiling}
22240 @item @code{'Component_Size}
22241 @item @code{'Compose}
22242 @item @code{'Copy_Sign}
22243 @item @code{'Delta}
22244 @item @code{'Denorm}
22245 @item @code{'Digits}
22246 @item @code{'Exponent}
22247 @item @code{'First}
22248 @item @code{'Floor}
22249 @item @code{'Fore}
22250 @item @code{'Fraction}
22251 @item @code{'Last}
22252 @item @code{'Leading_Part}
22253 @item @code{'Length}
22254 @item @code{'Machine}
22255 @item @code{'Machine_Emax}
22256 @item @code{'Machine_Emin}
22257 @item @code{'Machine_Mantissa}
22258 @item @code{'Machine_Overflows}
22259 @item @code{'Machine_Radix}
22260 @item @code{'Machine_Rounds}
22261 @item @code{'Max}
22262 @item @code{'Min}
22263 @item @code{'Model}
22264 @item @code{'Model_Emin}
22265 @item @code{'Model_Epsilon}
22266 @item @code{'Model_Mantissa}
22267 @item @code{'Model_Small}
22268 @item @code{'Modulus}
22269 @item @code{'Pos}
22270 @item @code{'Pred}
22271 @item @code{'Range}
22272 @item @code{'Remainder}
22273 @item @code{'Rounding}
22274 @item @code{'Safe_First}
22275 @item @code{'Safe_Last}
22276 @item @code{'Scaling}
22277 @item @code{'Signed_Zeros}
22278 @item @code{'Size}
22279 @item @code{'Small}
22280 @item @code{'Succ}
22281 @item @code{'Truncation}
22282 @item @code{'Unbiased_Rounding}
22283 @item @code{'Val}
22284 @item @code{'Valid}
22285 @end itemize
22286
22287 @noindent
22288 This rule has no parameters.
22289
22290
22291 @node Non_Tagged_Derived_Types
22292 @subsection @code{Non_Tagged_Derived_Types}
22293 @cindex @code{Non_Tagged_Derived_Types} rule (for @command{gnatcheck})
22294
22295 @noindent
22296 Flag all derived type declarations that do not have a record extension part.
22297
22298 This rule has no parameters.
22299
22300
22301
22302 @node Non_Visible_Exceptions
22303 @subsection @code{Non_Visible_Exceptions}
22304 @cindex @code{Non_Visible_Exceptions} rule (for @command{gnatcheck})
22305
22306 @noindent
22307 Flag constructs leading to the possibility of propagating an exception
22308 out of the scope in which the exception is declared.
22309 Two cases are detected:
22310
22311 @itemize @bullet
22312 @item
22313 An exception declaration in a subprogram body, task body or block
22314 statement is flagged if the body or statement does not contain a handler for
22315 that exception or a handler with an @code{others} choice.
22316
22317 @item
22318 A @code{raise} statement in an exception handler of a subprogram body,
22319 task body or block statement is flagged if it (re)raises a locally
22320 declared exception.  This may occur under the following circumstances:
22321 @itemize @minus
22322 @item
22323 it explicitly raises a locally declared exception, or
22324 @item
22325 it does not specify an exception name (i.e., it is simply @code{raise;})
22326 and the enclosing handler contains a locally declared exception in its
22327 exception choices.
22328 @end itemize
22329 @end itemize
22330
22331 @noindent
22332 Renamings of local exceptions are not flagged.
22333
22334 This rule has no parameters.
22335
22336
22337 @node Numeric_Literals
22338 @subsection @code{Numeric_Literals}
22339 @cindex @code{Numeric_Literals} rule (for @command{gnatcheck})
22340
22341 @noindent
22342 Flag each use of a numeric literal in an index expression, and in any
22343 circumstance except for the following:
22344
22345 @itemize @bullet
22346 @item
22347 a literal occurring in the initialization expression for a constant
22348 declaration or a named number declaration, or
22349
22350 @item
22351 an integer literal that is less than or equal to a value
22352 specified by the @option{N} rule parameter.
22353 @end itemize
22354
22355 @noindent
22356 This rule may have the following parameters for the @option{+R} option:
22357
22358 @table @asis
22359 @item @emph{N}
22360 @emph{N} is an integer literal used as the maximal value that is not flagged
22361 (i.e., integer literals not exceeding this value are allowed)
22362
22363 @item @code{ALL}
22364 All integer literals are flagged
22365 @end table
22366
22367 @noindent
22368 If no parameters are set, the maximum unflagged value is 1.
22369
22370 The last specified check limit (or the fact that there is no limit at
22371 all) is used when multiple @option{+R} options appear.
22372
22373 The @option{-R} option for this rule has no parameters.
22374 It disables the rule but retains the last specified maximum unflagged value.
22375 If the @option{+R} option subsequently appears, this value is used as the
22376 threshold for the check.
22377
22378
22379 @node OTHERS_In_Aggregates
22380 @subsection @code{OTHERS_In_Aggregates}
22381 @cindex @code{OTHERS_In_Aggregates} rule (for @command{gnatcheck})
22382
22383 @noindent
22384 Flag each use of an @code{others} choice in extension aggregates.
22385 In record and array aggregates, an @code{others} choice is flagged unless
22386 it is used to refer to all components, or to all but one component.
22387
22388 If, in case of a named array aggregate, there are two associations, one
22389 with an @code{others} choice and another with a discrete range, the
22390 @code{others} choice is flagged even if the discrete range specifies
22391 exactly one component; for example, @code{(1..1 => 0, others => 1)}.
22392
22393 This rule has no parameters.
22394
22395 @node OTHERS_In_CASE_Statements
22396 @subsection @code{OTHERS_In_CASE_Statements}
22397 @cindex @code{OTHERS_In_CASE_Statements} rule (for @command{gnatcheck})
22398
22399 @noindent
22400 Flag any use of an @code{others} choice in a @code{case} statement.
22401
22402 This rule has no parameters.
22403
22404 @node OTHERS_In_Exception_Handlers
22405 @subsection @code{OTHERS_In_Exception_Handlers}
22406 @cindex @code{OTHERS_In_Exception_Handlers} rule (for @command{gnatcheck})
22407
22408 @noindent
22409 Flag any use of an @code{others} choice in an exception handler.
22410
22411 This rule has no parameters.
22412
22413
22414 @node Outer_Loop_Exits
22415 @subsection @code{Outer_Loop_Exits}
22416 @cindex @code{Outer_Loop_Exits} rule (for @command{gnatcheck})
22417
22418 @noindent
22419 Flag each @code{exit} statement containing a loop name that is not the name
22420 of the immediately enclosing @code{loop} statement.
22421
22422 This rule has no parameters.
22423
22424
22425 @node Overloaded_Operators
22426 @subsection @code{Overloaded_Operators}
22427 @cindex @code{Overloaded_Operators} rule (for @command{gnatcheck})
22428
22429 @noindent
22430 Flag each function declaration that overloads an operator symbol.
22431 A function body is checked only if the body does not have a
22432 separate spec. Formal functions are also checked. For a
22433 renaming declaration, only renaming-as-declaration is checked
22434
22435 This rule has no parameters.
22436
22437
22438 @node Overly_Nested_Control_Structures
22439 @subsection @code{Overly_Nested_Control_Structures}
22440 @cindex @code{Overly_Nested_Control_Structures} rule (for @command{gnatcheck})
22441
22442 @noindent
22443 Flag each control structure whose nesting level exceeds the value provided
22444 in the rule parameter.
22445
22446 The control structures checked are the following:
22447
22448 @itemize @bullet
22449 @item    @code{if} statement
22450 @item    @code{case} statement
22451 @item    @code{loop} statement
22452 @item    Selective accept statement
22453 @item    Timed entry call statement
22454 @item    Conditional entry call
22455 @item    Asynchronous select statement
22456 @end itemize
22457
22458 @noindent
22459 The rule has the following parameter for the @option{+R} option:
22460
22461 @table @emph
22462 @item N
22463 Positive integer specifying the maximal control structure nesting
22464 level that is not flagged
22465 @end table
22466
22467 @noindent
22468 If the parameter for the @option{+R} option is not specified or
22469 if it is not a positive integer, @option{+R} option is ignored.
22470
22471 If more then one  option is specified for the gnatcheck call, the later option and
22472 new parameter override the previous one(s).
22473
22474
22475 @node Parameters_Out_Of_Order
22476 @subsection @code{Parameters_Out_Of_Order}
22477 @cindex @code{Parameters_Out_Of_Order} rule (for @command{gnatcheck})
22478
22479 @noindent
22480 Flag each subprogram and entry declaration whose formal parameters are not
22481 ordered according to the following scheme:
22482
22483 @itemize @bullet
22484
22485 @item @code{in} and @code{access} parameters first,
22486 then @code{in out} parameters,
22487 and then @code{out} parameters;
22488
22489 @item for @code{in} mode, parameters with default initialization expressions
22490 occur last
22491 @end itemize
22492
22493 @noindent
22494 Only the first violation of the described order is flagged.
22495
22496 The following constructs are checked:
22497
22498 @itemize @bullet
22499 @item   subprogram declarations (including null procedures);
22500 @item   generic subprogram declarations;
22501 @item   formal subprogram declarations;
22502 @item   entry declarations;
22503 @item   subprogram bodies and subprogram body stubs that do not
22504 have separate specifications
22505 @end itemize
22506
22507 @noindent
22508 Subprogram renamings are not checked.
22509
22510 This rule has no parameters.
22511
22512
22513 @node Positional_Actuals_For_Defaulted_Generic_Parameters
22514 @subsection @code{Positional_Actuals_For_Defaulted_Generic_Parameters}
22515 @cindex @code{Positional_Actuals_For_Defaulted_Generic_Parameters} rule (for @command{gnatcheck})
22516
22517 @noindent
22518 Flag each generic actual parameter corresponding to a generic formal
22519 parameter with a default initialization, if positional notation is used.
22520
22521 This rule has no parameters.
22522
22523 @node Positional_Actuals_For_Defaulted_Parameters
22524 @subsection @code{Positional_Actuals_For_Defaulted_Parameters}
22525 @cindex @code{Positional_Actuals_For_Defaulted_Parameters} rule (for @command{gnatcheck})
22526
22527 @noindent
22528 Flag each actual parameter to a subprogram or entry call where the
22529 corresponding formal parameter has a default expression, if positional
22530 notation is used.
22531
22532 This rule has no parameters.
22533
22534 @node Positional_Components
22535 @subsection @code{Positional_Components}
22536 @cindex @code{Positional_Components} rule (for @command{gnatcheck})
22537
22538 @noindent
22539 Flag each array, record and extension aggregate that includes positional
22540 notation.
22541
22542 This rule has no parameters.
22543
22544
22545 @node Positional_Generic_Parameters
22546 @subsection @code{Positional_Generic_Parameters}
22547 @cindex @code{Positional_Generic_Parameters} rule (for @command{gnatcheck})
22548
22549 @noindent
22550 Flag each positional actual generic parameter except for the case when
22551 the generic unit being iinstantiated has exactly one generic formal
22552 parameter.
22553
22554 This rule has no parameters.
22555
22556
22557 @node Positional_Parameters
22558 @subsection @code{Positional_Parameters}
22559 @cindex @code{Positional_Parameters} rule (for @command{gnatcheck})
22560
22561 @noindent
22562 Flag each positional parameter notation in a subprogram or entry call,
22563 except for the following:
22564
22565 @itemize @bullet
22566 @item
22567 Parameters of calls to of prefix or infix operators are not flagged
22568 @item
22569 If the called subprogram or entry has only one formal parameter,
22570 the parameter of the call is not flagged;
22571 @item
22572 If a subprogram call uses the @emph{Object.Operation} notation, then
22573 @itemize @minus
22574 @item
22575 the first parameter (that is, @emph{Object}) is not flagged;
22576 @item
22577 if the called subprogram has only two parameters, the second parameter
22578 of the call is not flagged;
22579 @end itemize
22580 @end itemize
22581
22582 @noindent
22583 This rule has no parameters.
22584
22585
22586
22587
22588 @node Predefined_Numeric_Types
22589 @subsection @code{Predefined_Numeric_Types}
22590 @cindex @code{Predefined_Numeric_Types} rule (for @command{gnatcheck})
22591
22592 @noindent
22593 Flag each explicit use of the name of any numeric type or subtype defined
22594 in package @code{Standard}.
22595
22596 The rationale for this rule is to detect when the
22597 program may depend on platform-specific characteristics of the implementation
22598 of the predefined numeric types. Note that this rule is over-pessimistic;
22599 for example, a program that uses @code{String} indexing
22600 likely needs a variable of type @code{Integer}.
22601 Another example is the flagging of predefined numeric types with explicit
22602 constraints:
22603
22604 @smallexample @c ada
22605     subtype My_Integer is Integer range Left .. Right;
22606     Vy_Var : My_Integer;
22607 @end smallexample
22608
22609 @noindent
22610 This rule detects only numeric types and subtypes defined in
22611 @code{Standard}. The use of numeric types and subtypes defined in other
22612 predefined packages (such as @code{System.Any_Priority} or
22613 @code{Ada.Text_IO.Count}) is not flagged
22614
22615 This rule has no parameters.
22616
22617
22618
22619 @node Raising_External_Exceptions
22620 @subsection @code{Raising_External_Exceptions}
22621 @cindex @code{Raising_External_Exceptions} rule (for @command{gnatcheck})
22622
22623 @noindent
22624 Flag any @code{raise} statement, in a program unit declared in a library
22625 package or in a generic library package, for an exception that is
22626 neither a predefined exception nor an exception that is also declared (or
22627 renamed) in the visible part of the package.
22628
22629 This rule has no parameters.
22630
22631
22632
22633 @node Raising_Predefined_Exceptions
22634 @subsection @code{Raising_Predefined_Exceptions}
22635 @cindex @code{Raising_Predefined_Exceptions} rule (for @command{gnatcheck})
22636
22637 @noindent
22638 Flag each @code{raise} statement that raises a predefined exception
22639 (i.e., one of the exceptions @code{Constraint_Error}, @code{Numeric_Error},
22640 @code{Program_Error}, @code{Storage_Error}, or @code{Tasking_Error}).
22641
22642 This rule has no parameters.
22643
22644 @node Separate_Numeric_Error_Handlers
22645 @subsection @code{Separate_Numeric_Error_Handlers}
22646 @cindex @code{Separate_Numeric_Error_Handlers} rule (for @command{gnatcheck})
22647
22648 @noindent
22649 Flags each exception handler that contains a choice for
22650 the predefined @code{Constraint_Error} exception, but does not contain
22651 the choice for the predefined @code{Numeric_Error} exception, or
22652 that contains the choice for @code{Numeric_Error}, but does not contain the
22653 choice for @code{Constraint_Error}.
22654
22655 This rule has no parameters.
22656
22657 @ignore
22658 @node Recursion
22659 @subsection @code{Recursion} (under construction, GLOBAL)
22660 @cindex @code{Recursion} rule (for @command{gnatcheck})
22661
22662 @noindent
22663 Flag recursive subprograms (cycles in the call graph). Declarations, and not
22664 calls, of recursive subprograms are detected.
22665
22666 This rule has no parameters.
22667 @end ignore
22668
22669 @ignore
22670 @node Side_Effect_Functions
22671 @subsection @code{Side_Effect_Functions} (under construction, GLOBAL)
22672 @cindex @code{Side_Effect_Functions} rule (for @command{gnatcheck})
22673
22674 @noindent
22675 Flag functions with side effects.
22676
22677 We define a side effect as changing any data object that is not local for the
22678 body of this function.
22679
22680 At the moment, we do NOT consider a side effect any input-output operations
22681 (changing a state or a content of any file).
22682
22683 We do not consider protected functions for this rule (???)
22684
22685 There are the following sources of side effect:
22686
22687 @enumerate
22688 @item Explicit (or direct) side-effect:
22689
22690 @itemize @bullet
22691 @item
22692 direct assignment to a non-local variable;
22693
22694 @item
22695 direct call to an entity that is known to change some data object that is
22696      not local for the body of this function (Note, that if F1 calls F2 and F2
22697      does have a side effect, this does not automatically mean that F1 also
22698      have a side effect, because it may be the case that F2 is declared in
22699      F1's body and it changes some data object that is global for F2, but
22700      local for F1);
22701 @end itemize
22702
22703 @item Indirect side-effect:
22704 @itemize @bullet
22705 @item
22706 Subprogram calls implicitly issued by:
22707 @itemize @bullet
22708 @item
22709 computing initialization expressions from type declarations as a part
22710          of object elaboration or allocator evaluation;
22711 @item
22712 computing implicit parameters of subprogram or entry calls or generic
22713          instantiations;
22714 @end itemize
22715
22716 @item
22717 activation of a task that change some non-local data object (directly or
22718      indirectly);
22719
22720 @item
22721 elaboration code of a package that is a result of a package instantiation;
22722
22723 @item
22724 controlled objects;
22725 @end itemize
22726
22727 @item Situations when we can suspect a side-effect, but the full static check
22728 is either impossible or too hard:
22729 @itemize @bullet
22730 @item
22731 assignment to access variables or to the objects pointed by access
22732      variables;
22733
22734 @item
22735 call to a subprogram pointed by access-to-subprogram value
22736
22737 @item
22738 dispatching calls;
22739 @end itemize
22740 @end enumerate
22741
22742 @noindent
22743 This rule has no parameters.
22744 @end ignore
22745
22746 @node Slices
22747 @subsection @code{Slices}
22748 @cindex @code{Slices} rule (for @command{gnatcheck})
22749
22750 @noindent
22751 Flag all uses of array slicing
22752
22753 This rule has no parameters.
22754
22755
22756 @node Too_Many_Parents
22757 @subsection @code{Too_Many_Parents}
22758 @cindex @code{Too_Many_Parents} rule (for @command{gnatcheck})
22759
22760 @noindent
22761 Flags any type declaration, single task declaration or single protected
22762 declaration that has more then  @option{N} parents,  @option{N} is a parameter
22763 of the rule.
22764 A parent here is either a (sub)type denoted by the subtype mark from the
22765 parent_subtype_indication (in case of a derived type declaration), or
22766 any of the progenitors from the interface list, if any.
22767
22768 This rule has the following (mandatory) parameters for the @option{+R} option:
22769
22770 @table @emph
22771 @item N
22772 Positive integer specifying the maximal allowed number of parents.
22773 @end table
22774
22775
22776 @node Unassigned_OUT_Parameters
22777 @subsection @code{Unassigned_OUT_Parameters}
22778 @cindex @code{Unassigned_OUT_Parameters} rule (for @command{gnatcheck})
22779
22780 @noindent
22781 Flags procedures' @code{out} parameters that are not assigned, and
22782 identifies the contexts in which the assignments are missing.
22783
22784 An @code{out} parameter is flagged in the statements in the procedure
22785 body's handled sequence of statements (before the procedure body's
22786 @code{exception} part, if any) if this sequence of statements contains
22787 no assignments to the parameter.
22788
22789 An @code{out} parameter is flagged in an exception handler in the exception
22790 part of the procedure body's handled sequence of statements if the handler
22791 contains no assignment to the parameter.
22792
22793 Bodies of generic procedures are also considered.
22794
22795 The following are treated as assignments to an @code{out} parameter:
22796
22797 @itemize @bullet
22798 @item
22799 an assignment statement, with the parameter or some component as the target;
22800
22801 @item
22802 passing the parameter (or one of its components) as an @code{out} or
22803 @code{in out} parameter.
22804 @end itemize
22805
22806 @noindent
22807 This rule does not have any parameters.
22808
22809
22810
22811 @node Uncommented_BEGIN_In_Package_Bodies
22812 @subsection @code{Uncommented_BEGIN_In_Package_Bodies}
22813 @cindex @code{Uncommented_BEGIN_In_Package_Bodies} rule (for @command{gnatcheck})
22814
22815 @noindent
22816 Flags each package body with declarations and a statement part that does not
22817 include a trailing comment on the line containing the @code{begin} keyword;
22818 this trailing comment needs to specify the package name and nothing else.
22819 The @code{begin} is not flagged if the package body does not
22820 contain any declarations.
22821
22822 If the @code{begin} keyword is placed on the
22823 same line as the last declaration or the first statement, it is flagged
22824 independently of whether the line contains a trailing comment. The
22825 diagnostic message is attached to the line containing the first statement.
22826
22827 This rule has no parameters.
22828
22829 @node Unconditional_Exits
22830 @subsection @code{Unconditional_Exits}
22831 @cindex @code{Unconditional_Exits} rule (for @command{gnatcheck})
22832
22833 @noindent
22834 Flag unconditional @code{exit} statements.
22835
22836 This rule has no parameters.
22837
22838 @node Unconstrained_Array_Returns
22839 @subsection @code{Unconstrained_Array_Returns}
22840 @cindex @code{Unconstrained_Array_Returns} rule (for @command{gnatcheck})
22841
22842 @noindent
22843 Flag each function returning an unconstrained array. Function declarations,
22844 function bodies (and body stubs) having no separate specifications,
22845 and generic function instantiations are checked.
22846 Function calls and function renamings are
22847 not checked.
22848
22849 Generic function declarations, and function declarations in generic
22850 packages are not checked, instead this rule checks the results of
22851 generic instantiations (that is, expanded specification and expanded
22852 body corresponding to an instantiation).
22853
22854 This rule has no parameters.
22855
22856 @node Universal_Ranges
22857 @subsection @code{Universal_Ranges}
22858 @cindex @code{Universal_Ranges} rule (for @command{gnatcheck})
22859
22860 @noindent
22861 Flag discrete ranges that are a part of an index constraint, constrained
22862 array definition, or @code{for}-loop parameter specification, and whose bounds
22863 are both of type @i{universal_integer}. Ranges that have at least one
22864 bound of a specific type (such as @code{1 .. N}, where @code{N} is a variable
22865 or an expression of non-universal type) are not flagged.
22866
22867 This rule has no parameters.
22868
22869
22870 @node Unnamed_Blocks_And_Loops
22871 @subsection @code{Unnamed_Blocks_And_Loops}
22872 @cindex @code{Unnamed_Blocks_And_Loops} rule (for @command{gnatcheck})
22873
22874 @noindent
22875 Flag each unnamed block statement and loop statement.
22876
22877 The rule has no parameters.
22878
22879
22880
22881 @ignore
22882 @node Unused_Subprograms
22883 @subsection @code{Unused_Subprograms} (under construction, GLOBAL)
22884 @cindex @code{Unused_Subprograms} rule (for @command{gnatcheck})
22885
22886 @noindent
22887 Flag all unused subprograms.
22888
22889 This rule has no parameters.
22890 @end ignore
22891
22892
22893
22894
22895 @node USE_PACKAGE_Clauses
22896 @subsection @code{USE_PACKAGE_Clauses}
22897 @cindex @code{USE_PACKAGE_Clauses} rule (for @command{gnatcheck})
22898
22899 @noindent
22900 Flag all @code{use} clauses for packages; @code{use type} clauses are
22901 not flagged.
22902
22903 This rule has no parameters.
22904
22905
22906 @node Visible_Components
22907 @subsection @code{Visible_Components}
22908 @cindex @code{Visible_Components} rule (for @command{gnatcheck})
22909
22910 @noindent
22911 Flags all the type declarations located in the visible part of a library
22912 package or a library generic package that can declare a visible component. A
22913 type is considered as declaring a visible component if it contains a record
22914 definition by its own or as a part of a record extension. Type declaration is
22915 flagged even if it contains a record definition that defines no components.
22916
22917 Declarations located in private parts of local (generic) packages are not
22918 flagged. Declarations in private packages are not flagged.
22919
22920 This rule has no parameters.
22921
22922
22923 @node Volatile_Objects_Without_Address_Clauses
22924 @subsection @code{Volatile_Objects_Without_Address_Clauses}
22925 @cindex @code{Volatile_Objects_Without_Address_Clauses} rule (for @command{gnatcheck})
22926
22927 @noindent
22928 Flag each volatile object that does not have an address clause.
22929
22930 The following check is made: if the pragma @code{Volatile} is applied to a
22931 data object or to its type, then an address clause must
22932 be supplied for this object.
22933
22934 This rule does not check the components of data objects,
22935 array components that are volatile as a result of the pragma
22936 @code{Volatile_Components}, or objects that are volatile because
22937 they are atomic as a result of pragmas @code{Atomic} or
22938 @code{Atomic_Components}.
22939
22940 Only variable declarations, and not constant declarations, are checked.
22941
22942 This rule has no parameters.
22943
22944 @node Example of gnatcheck Usage
22945 @section Example of @command{gnatcheck} Usage
22946
22947 @noindent
22948 Here is a simple example. Suppose that in the current directory we have a
22949 project file named @file{gnatcheck_example.gpr} with the following content:
22950
22951 @smallexample @c projectfile
22952 project Gnatcheck_Example is
22953
22954    for Source_Dirs use ("src");
22955    for Object_Dir use "obj";
22956    for Main use ("main.adb");
22957
22958    package Check is
22959       for Default_Switches ("ada") use ("-rules", "-from=coding_standard");
22960    end Check;
22961
22962 end Gnatcheck_Example;
22963 @end smallexample
22964
22965 @noindent
22966 And the file named @file{coding_standard} is also located in the current
22967 directory and has the following content:
22968
22969 @smallexample
22970 -----------------------------------------------------
22971 -- This is a sample gnatcheck coding standard file --
22972 -----------------------------------------------------
22973
22974 --  First, turning on rules, that are directly implemented in gnatcheck
22975 +RAbstract_Type_Declarations
22976 +RAnonymous_Arrays
22977 +RLocal_Packages
22978 +RFloat_Equality_Checks
22979 +REXIT_Statements_With_No_Loop_Name
22980
22981 --  Then, activating compiler checks of interest:
22982 +RStyle_Checks:e
22983 --  This style check checks if a unit name is present on END keyword that
22984 --  is the end of the unit declaration
22985 @end smallexample
22986
22987 @noindent
22988 And the subdirectory @file{src} contains the following Ada sources:
22989
22990 @file{pack.ads}:
22991
22992 @smallexample @c ada
22993 package Pack is
22994    type T is abstract tagged private;
22995    procedure P (X : T) is abstract;
22996
22997    package Inner is
22998       type My_Float is digits 8;
22999       function Is_Equal (L, R : My_Float) return Boolean;
23000    end Inner;
23001 private
23002    type T is abstract tagged null record;
23003 end;
23004 @end smallexample
23005
23006 @noindent
23007 @file{pack.adb}:
23008
23009 @smallexample @c ada
23010 package body Pack is
23011    package body Inner is
23012       function Is_Equal (L, R : My_Float) return Boolean is
23013       begin
23014          return L = R;
23015       end;
23016    end Inner;
23017 end Pack;
23018 @end smallexample
23019
23020 @noindent
23021 and @file{main.adb}
23022
23023 @smallexample @c ada
23024 with Pack; use Pack;
23025 procedure Main is
23026
23027    pragma Annotate
23028      (gnatcheck, Exempt_On, "Anonymous_Arrays", "this one is fine");
23029    Float_Array : array (1 .. 10) of Inner.My_Float;
23030    pragma Annotate (gnatcheck, Exempt_Off, "Anonymous_Arrays");
23031
23032    Another_Float_Array : array (1 .. 10) of Inner.My_Float;
23033
23034    use Inner;
23035
23036    B : Boolean := False;
23037
23038 begin
23039    for J in Float_Array'Range loop
23040       if Is_Equal (Float_Array (J), Another_Float_Array (J)) then
23041          B := True;
23042          exit;
23043       end if;
23044    end loop;
23045 end Main;
23046 @end smallexample
23047
23048 @noindent
23049 And suppose we call @command{gnatcheck} from the current directory using
23050 the @command{gnat} driver:
23051
23052 @smallexample
23053    gnat check -Pgnatcheck_example.gpr
23054 @end smallexample
23055
23056 @noindent
23057 As a result, @command{gnatcheck} is called to check all the files from the
23058 project @file{gnatcheck_example.gpr} using the coding standard defined by
23059 the file @file{coding_standard}. As the result, the @command{gnatcheck}
23060 report file named @file{gnatcheck.out} will be created in the current
23061 directory, and it will have the following content:
23062
23063 @smallexample
23064 RULE CHECKING REPORT
23065
23066 1. OVERVIEW
23067
23068 Date and time of execution: 2009.10.28 14:17
23069 Tool version: GNATCHECK (built with ASIS 2.0.R for GNAT Pro 6.3.0w (20091016))
23070 Command line:
23071
23072 gnatcheck -files=.../GNAT-TEMP-000004.TMP -cargs -gnatec=.../GNAT-TEMP-000003.TMP -rules -from=coding_standard
23073
23074 Coding standard (applied rules):
23075    Abstract_Type_Declarations
23076    Anonymous_Arrays
23077    EXIT_Statements_With_No_Loop_Name
23078    Float_Equality_Checks
23079    Local_Packages
23080
23081    Compiler style checks: -gnatye
23082
23083 Number of coding standard violations: 6
23084 Number of exempted coding standard violations: 1
23085
23086 2. DETECTED RULE VIOLATIONS
23087
23088 2.1. NON-EXEMPTED VIOLATIONS
23089
23090 Source files with non-exempted violations
23091    pack.ads
23092    pack.adb
23093    main.adb
23094
23095 List of violations grouped by files, and ordered by increasing source location:
23096
23097 pack.ads:2:4: declaration of abstract type
23098 pack.ads:5:4: declaration of local package
23099 pack.ads:10:30: declaration of abstract type
23100 pack.ads:11:1: (style) "end Pack" required
23101 pack.adb:5:19: use of equality operation for float values
23102 pack.adb:6:7: (style) "end Is_Equal" required
23103 main.adb:9:26: anonymous array type
23104 main.adb:19:10: exit statement with no loop name
23105
23106 2.2. EXEMPTED VIOLATIONS
23107
23108 Source files with exempted violations
23109    main.adb
23110
23111 List of violations grouped by files, and ordered by increasing source location:
23112
23113 main.adb:6:18: anonymous array type
23114    (this one is fine)
23115
23116 2.3. SOURCE FILES WITH NO VIOLATION
23117
23118    No files without violations
23119
23120 END OF REPORT
23121 @end smallexample
23122
23123
23124 @c *********************************
23125 @node Creating Sample Bodies Using gnatstub
23126 @chapter Creating Sample Bodies Using @command{gnatstub}
23127 @findex gnatstub
23128
23129 @noindent
23130 @command{gnatstub} creates body stubs, that is, empty but compilable bodies
23131 for library unit declarations.
23132
23133 Note: to invoke @code{gnatstub} with a project file, use the @code{gnat}
23134 driver (see @ref{The GNAT Driver and Project Files}).
23135
23136 To create a body stub, @command{gnatstub} has to compile the library
23137 unit declaration. Therefore, bodies can be created only for legal
23138 library units. Moreover, if a library unit depends semantically upon
23139 units located outside the current directory, you have to provide
23140 the source search path when calling @command{gnatstub}, see the description
23141 of @command{gnatstub} switches below.
23142
23143 By default, all the program unit body stubs generated by @code{gnatstub}
23144 raise the predefined @code{Program_Error} exception, which will catch
23145 accidental calls of generated stubs. This behavior can be changed with
23146 option @option{^--no-exception^/NO_EXCEPTION^} (see below).
23147
23148 @menu
23149 * Running gnatstub::
23150 * Switches for gnatstub::
23151 @end menu
23152
23153 @node Running gnatstub
23154 @section Running @command{gnatstub}
23155
23156 @noindent
23157 @command{gnatstub} has the command-line interface of the form
23158
23159 @smallexample
23160 $ gnatstub @ovar{switches} @var{filename} @ovar{directory}
23161 @end smallexample
23162
23163 @noindent
23164 where
23165 @table @var
23166 @item filename
23167 is the name of the source file that contains a library unit declaration
23168 for which a body must be created. The file name may contain the path
23169 information.
23170 The file name does not have to follow the GNAT file name conventions. If the
23171 name
23172 does not follow GNAT file naming conventions, the name of the body file must
23173 be provided
23174 explicitly as the value of the @option{^-o^/BODY=^@var{body-name}} option.
23175 If the file name follows the GNAT file naming
23176 conventions and the name of the body file is not provided,
23177 @command{gnatstub}
23178 creates the name
23179 of the body file from the argument file name by replacing the @file{.ads}
23180 suffix
23181 with the @file{.adb} suffix.
23182
23183 @item directory
23184 indicates the directory in which the body stub is to be placed (the default
23185 is the
23186 current directory)
23187
23188 @item switches
23189 is an optional sequence of switches as described in the next section
23190 @end table
23191
23192 @node Switches for gnatstub
23193 @section Switches for @command{gnatstub}
23194
23195 @table @option
23196 @c !sort!
23197
23198 @item ^-f^/FULL^
23199 @cindex @option{^-f^/FULL^} (@command{gnatstub})
23200 If the destination directory already contains a file with the name of the
23201 body file
23202 for the argument spec file, replace it with the generated body stub.
23203
23204 @item ^-hs^/HEADER=SPEC^
23205 @cindex @option{^-hs^/HEADER=SPEC^} (@command{gnatstub})
23206 Put the comment header (i.e., all the comments preceding the
23207 compilation unit) from the source of the library unit declaration
23208 into the body stub.
23209
23210 @item ^-hg^/HEADER=GENERAL^
23211 @cindex @option{^-hg^/HEADER=GENERAL^} (@command{gnatstub})
23212 Put a sample comment header into the body stub.
23213
23214 @item ^--header-file=@var{filename}^/FROM_HEADER_FILE=@var{filename}^
23215 @cindex @option{^--header-file^/FROM_HEADER_FILE=^} (@command{gnatstub})
23216 Use the content of the file as the comment header for a generated body stub.
23217
23218 @ifclear vms
23219 @item -IDIR
23220 @cindex @option{-IDIR} (@command{gnatstub})
23221 @itemx -I-
23222 @cindex @option{-I-} (@command{gnatstub})
23223 @end ifclear
23224 @ifset vms
23225 @item /NOCURRENT_DIRECTORY
23226 @cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub})
23227 @end ifset
23228 ^These switches have ^This switch has^ the same meaning as in calls to
23229 @command{gcc}.
23230 ^They define ^It defines ^ the source search path in the call to
23231 @command{gcc} issued
23232 by @command{gnatstub} to compile an argument source file.
23233
23234 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE=^@var{PATH}
23235 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatstub})
23236 This switch has the same meaning as in calls to @command{gcc}.
23237 It defines the additional configuration file to be passed to the call to
23238 @command{gcc} issued
23239 by @command{gnatstub} to compile an argument source file.
23240
23241 @item ^-gnatyM^/MAX_LINE_LENGTH=^@var{n}
23242 @cindex @option{^-gnatyM^/MAX_LINE_LENGTH^} (@command{gnatstub})
23243 (@var{n} is a non-negative integer). Set the maximum line length in the
23244 body stub to @var{n}; the default is 79. The maximum value that can be
23245 specified is 32767. Note that in the special case of configuration
23246 pragma files, the maximum is always 32767 regardless of whether or
23247 not this switch appears.
23248
23249 @item ^-gnaty^/STYLE_CHECKS=^@var{n}
23250 @cindex @option{^-gnaty^/STYLE_CHECKS=^} (@command{gnatstub})
23251 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
23252 the generated body sample to @var{n}.
23253 The default indentation is 3.
23254
23255 @item ^-gnatyo^/ORDERED_SUBPROGRAMS^
23256 @cindex @option{^-gnato^/ORDERED_SUBPROGRAMS^} (@command{gnatstub})
23257 Order local bodies alphabetically. (By default local bodies are ordered
23258 in the same way as the corresponding local specs in the argument spec file.)
23259
23260 @item ^-i^/INDENTATION=^@var{n}
23261 @cindex @option{^-i^/INDENTATION^} (@command{gnatstub})
23262 Same as @option{^-gnaty^/STYLE_CHECKS=^@var{n}}
23263
23264 @item ^-k^/TREE_FILE=SAVE^
23265 @cindex @option{^-k^/TREE_FILE=SAVE^} (@command{gnatstub})
23266 Do not remove the tree file (i.e., the snapshot of the compiler internal
23267 structures used by @command{gnatstub}) after creating the body stub.
23268
23269 @item ^-l^/LINE_LENGTH=^@var{n}
23270 @cindex @option{^-l^/LINE_LENGTH^} (@command{gnatstub})
23271 Same as @option{^-gnatyM^/MAX_LINE_LENGTH=^@var{n}}
23272
23273 @item ^--no-exception^/NO_EXCEPTION^
23274 @cindex @option{^--no-exception^/NO_EXCEPTION^} (@command{gnatstub})
23275 Avoind raising PROGRAM_ERROR in the generated bodies of program unit stubs.
23276 This is not always possible for function stubs.
23277
23278 @item ^--no-local-header^/NO_LOCAL_HEADER^
23279 @cindex @option{^--no-local-header^/NO_LOCAL_HEADER^} (@command{gnatstub})
23280 Do not place local comment header with unit name before body stub for a
23281 unit.
23282
23283 @item ^-o ^/BODY=^@var{body-name}
23284 @cindex @option{^-o^/BODY^} (@command{gnatstub})
23285 Body file name.  This should be set if the argument file name does not
23286 follow
23287 the GNAT file naming
23288 conventions. If this switch is omitted the default name for the body will be
23289 obtained
23290 from the argument file name according to the GNAT file naming conventions.
23291
23292 @item ^-q^/QUIET^
23293 @cindex @option{^-q^/QUIET^} (@command{gnatstub})
23294 Quiet mode: do not generate a confirmation when a body is
23295 successfully created, and do not generate a message when a body is not
23296 required for an
23297 argument unit.
23298
23299 @item ^-r^/TREE_FILE=REUSE^
23300 @cindex @option{^-r^/TREE_FILE=REUSE^} (@command{gnatstub})
23301 Reuse the tree file (if it exists) instead of creating it.  Instead of
23302 creating the tree file for the library unit declaration, @command{gnatstub}
23303 tries to find it in the current directory and use it for creating
23304 a body. If the tree file is not found, no body is created. This option
23305 also implies @option{^-k^/SAVE^}, whether or not
23306 the latter is set explicitly.
23307
23308 @item ^-t^/TREE_FILE=OVERWRITE^
23309 @cindex @option{^-t^/TREE_FILE=OVERWRITE^} (@command{gnatstub})
23310 Overwrite the existing tree file.  If the current directory already
23311 contains the file which, according to the GNAT file naming rules should
23312 be considered as a tree file for the argument source file,
23313 @command{gnatstub}
23314 will refuse to create the tree file needed to create a sample body
23315 unless this option is set.
23316
23317 @item ^-v^/VERBOSE^
23318 @cindex @option{^-v^/VERBOSE^} (@command{gnatstub})
23319 Verbose mode: generate version information.
23320
23321 @end table
23322
23323 @c *********************************
23324 @node Generating Ada Bindings for C and C++ headers
23325 @chapter Generating Ada Bindings for C and C++ headers
23326 @findex binding
23327
23328 @noindent
23329 GNAT now comes with a new experimental binding generator for C and C++
23330 headers which is intended to do 95% of the tedious work of generating
23331 Ada specs from C or C++ header files. Note that this still is a work in
23332 progress, not designed to generate 100% correct Ada specs.
23333
23334 The code generated is using the Ada 2005 syntax, which makes it
23335 easier to interface with other languages than previous versions of Ada.
23336
23337 @menu
23338 * Running the binding generator::
23339 * Generating bindings for C++ headers::
23340 * Switches::
23341 @end menu
23342
23343 @node Running the binding generator
23344 @section Running the binding generator
23345
23346 @noindent
23347 The binding generator is part of the @command{gcc} compiler and can be
23348 invoked via the @option{-fdump-ada-spec} switch, which will generate Ada
23349 spec files for the header files specified on the command line, and all
23350 header files needed by these files transitivitely. For example:
23351
23352 @smallexample
23353 $ g++ -c -fdump-ada-spec -C /usr/include/time.h
23354 $ gcc -c -gnat05 *.ads
23355 @end smallexample
23356
23357 will generate, under GNU/Linux, the following files: @file{time_h.ads},
23358 @file{bits_time_h.ads}, @file{stddef_h.ads}, @file{bits_types_h.ads} which
23359 correspond to the files @file{/usr/include/time.h},
23360 @file{/usr/include/bits/time.h}, etc@dots{}, and will then compile in Ada 2005
23361 mode these Ada specs.
23362
23363 The @code{-C} switch tells @command{gcc} to extract comments from headers,
23364 and will attempt to generate corresponding Ada comments.
23365
23366 If you want to generate a single Ada file and not the transitive closure, you
23367 can use instead the @option{-fdump-ada-spec-slim} switch.
23368
23369 Note that we recommend when possible to use the @command{g++} driver to
23370 generate bindings, even for most C headers, since this will in general
23371 generate better Ada specs. For generating bindings for C++ headers, it is
23372 mandatory to use the @command{g++} command, or @command{gcc -x c++} which
23373 is equivalent in this case. If @command{g++} cannot work on your C headers
23374 because of incompatibilities between C and C++, then you can fallback to
23375 @command{gcc} instead.
23376
23377 For an example of better bindings generated from the C++ front-end,
23378 the name of the parameters (when available) are actually ignored by the C
23379 front-end. Consider the following C header:
23380
23381 @smallexample
23382 extern void foo (int variable);
23383 @end smallexample
23384
23385 with the C front-end, @code{variable} is ignored, and the above is handled as:
23386
23387 @smallexample
23388 extern void foo (int);
23389 @end smallexample
23390
23391 generating a generic:
23392
23393 @smallexample
23394 procedure foo (param1 : int);
23395 @end smallexample
23396
23397 with the C++ front-end, the name is available, and we generate:
23398
23399 @smallexample
23400 procedure foo (variable : int);
23401 @end smallexample
23402
23403 In some cases, the generated bindings will be more complete or more meaningful
23404 when defining some macros, which you can do via the @option{-D} switch. This
23405 is for example the case with @file{Xlib.h} under GNU/Linux:
23406
23407 @smallexample
23408 g++ -c -fdump-ada-spec -DXLIB_ILLEGAL_ACCESS -C /usr/include/X11/Xlib.h
23409 @end smallexample
23410
23411 The above will generate more complete bindings than a straight call without
23412 the @option{-DXLIB_ILLEGAL_ACCESS} switch.
23413
23414 In other cases, it is not possible to parse a header file in a stand alone
23415 manner, because other include files need to be included first. In this
23416 case, the solution is to create a small header file including the needed
23417 @code{#include} and possible @code{#define} directives. For example, to
23418 generate Ada bindings for @file{readline/readline.h}, you need to first
23419 include @file{stdio.h}, so you can create a file with the following two
23420 lines in e.g. @file{readline1.h}:
23421
23422 @smallexample
23423 #include <stdio.h>
23424 #include <readline/readline.h>
23425 @end smallexample
23426
23427 and then generate Ada bindings from this file:
23428
23429 @smallexample
23430 $ g++ -c -fdump-ada-spec readline1.h
23431 @end smallexample
23432
23433 @node Generating bindings for C++ headers
23434 @section Generating bindings for C++ headers
23435
23436 @noindent
23437 Generating bindings for C++ headers is done using the same options, always
23438 with the @command{g++} compiler.
23439
23440 In this mode, C++ classes will be mapped to Ada tagged types, constructors
23441 will be mapped using the @code{CPP_Constructor} pragma, and when possible,
23442 multiple inheritance of abstract classes will be mapped to Ada interfaces
23443 (@xref{Interfacing to C++,,,gnat_rm, GNAT Reference Manual}, for additional
23444 information on interfacing to C++).
23445
23446 For example, given the following C++ header file:
23447
23448 @smallexample
23449 @group
23450 @cartouche
23451 class Carnivore @{
23452 public:
23453    virtual int Number_Of_Teeth () = 0;
23454 @};
23455
23456 class Domestic @{
23457 public:
23458    virtual void Set_Owner (char* Name) = 0;
23459 @};
23460
23461 class Animal @{
23462 public:
23463   int Age_Count;
23464   virtual void Set_Age (int New_Age);
23465 @};
23466
23467 class Dog : Animal, Carnivore, Domestic @{
23468  public:
23469   int  Tooth_Count;
23470   char *Owner;
23471
23472   virtual int  Number_Of_Teeth ();
23473   virtual void Set_Owner (char* Name);
23474
23475   Dog();
23476 @};
23477 @end cartouche
23478 @end group
23479 @end smallexample
23480
23481 The corresponding Ada code is generated:
23482
23483 @smallexample @c ada
23484 @group
23485 @cartouche
23486   package Class_Carnivore is
23487     type Carnivore is limited interface;
23488     pragma Import (CPP, Carnivore);
23489
23490     function Number_Of_Teeth (this : access Carnivore) return int is abstract;
23491   end;
23492   use Class_Carnivore;
23493
23494   package Class_Domestic is
23495     type Domestic is limited interface;
23496     pragma Import (CPP, Domestic);
23497
23498     procedure Set_Owner
23499       (this : access Domestic;
23500        Name : Interfaces.C.Strings.chars_ptr) is abstract;
23501   end;
23502   use Class_Domestic;
23503
23504   package Class_Animal is
23505     type Animal is tagged limited record
23506       Age_Count : aliased int;
23507     end record;
23508     pragma Import (CPP, Animal);
23509
23510     procedure Set_Age (this : access Animal; New_Age : int);
23511     pragma Import (CPP, Set_Age, "_ZN6Animal7Set_AgeEi");
23512   end;
23513   use Class_Animal;
23514
23515   package Class_Dog is
23516     type Dog is new Animal and Carnivore and Domestic with record
23517       Tooth_Count : aliased int;
23518       Owner : Interfaces.C.Strings.chars_ptr;
23519     end record;
23520     pragma Import (CPP, Dog);
23521
23522     function Number_Of_Teeth (this : access Dog) return int;
23523     pragma Import (CPP, Number_Of_Teeth, "_ZN3Dog15Number_Of_TeethEv");
23524
23525     procedure Set_Owner
23526       (this : access Dog; Name : Interfaces.C.Strings.chars_ptr);
23527     pragma Import (CPP, Set_Owner, "_ZN3Dog9Set_OwnerEPc");
23528
23529     function New_Dog return Dog;
23530     pragma CPP_Constructor (New_Dog);
23531     pragma Import (CPP, New_Dog, "_ZN3DogC1Ev");
23532   end;
23533   use Class_Dog;
23534 @end cartouche
23535 @end group
23536 @end smallexample
23537
23538 @node Switches
23539 @section Switches
23540
23541 @table @option
23542 @item -fdump-ada-spec
23543 @cindex @option{-fdump-ada-spec} (@command{gcc})
23544 Generate Ada spec files for the given header files transitively (including
23545 all header files that these headers depend upon).
23546
23547 @item -fdump-ada-spec-slim
23548 @cindex @option{-fdump-ada-spec-slim} (@command{gcc})
23549 Generate Ada spec files for the header files specified on the command line
23550 only.
23551
23552 @item -C
23553 @cindex @option{-C} (@command{gcc})
23554 Extract comments from headers and generate Ada comments in the Ada spec files.
23555 @end table
23556
23557 @node Other Utility Programs
23558 @chapter Other Utility Programs
23559
23560 @noindent
23561 This chapter discusses some other utility programs available in the Ada
23562 environment.
23563
23564 @menu
23565 * Using Other Utility Programs with GNAT::
23566 * The External Symbol Naming Scheme of GNAT::
23567 * Converting Ada Files to html with gnathtml::
23568 * Installing gnathtml::
23569 @ifset vms
23570 * LSE::
23571 * Profiling::
23572 @end ifset
23573 @end menu
23574
23575 @node Using Other Utility Programs with GNAT
23576 @section Using Other Utility Programs with GNAT
23577
23578 @noindent
23579 The object files generated by GNAT are in standard system format and in
23580 particular the debugging information uses this format. This means
23581 programs generated by GNAT can be used with existing utilities that
23582 depend on these formats.
23583
23584 @ifclear vms
23585 In general, any utility program that works with C will also often work with
23586 Ada programs generated by GNAT. This includes software utilities such as
23587 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
23588 as Purify.
23589 @end ifclear
23590
23591 @node The External Symbol Naming Scheme of GNAT
23592 @section The External Symbol Naming Scheme of GNAT
23593
23594 @noindent
23595 In order to interpret the output from GNAT, when using tools that are
23596 originally intended for use with other languages, it is useful to
23597 understand the conventions used to generate link names from the Ada
23598 entity names.
23599
23600 All link names are in all lowercase letters. With the exception of library
23601 procedure names, the mechanism used is simply to use the full expanded
23602 Ada name with dots replaced by double underscores. For example, suppose
23603 we have the following package spec:
23604
23605 @smallexample @c ada
23606 @group
23607 @cartouche
23608 package QRS is
23609    MN : Integer;
23610 end QRS;
23611 @end cartouche
23612 @end group
23613 @end smallexample
23614
23615 @noindent
23616 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
23617 the corresponding link name is @code{qrs__mn}.
23618 @findex Export
23619 Of course if a @code{pragma Export} is used this may be overridden:
23620
23621 @smallexample @c ada
23622 @group
23623 @cartouche
23624 package Exports is
23625    Var1 : Integer;
23626    pragma Export (Var1, C, External_Name => "var1_name");
23627    Var2 : Integer;
23628    pragma Export (Var2, C, Link_Name => "var2_link_name");
23629 end Exports;
23630 @end cartouche
23631 @end group
23632 @end smallexample
23633
23634 @noindent
23635 In this case, the link name for @var{Var1} is whatever link name the
23636 C compiler would assign for the C function @var{var1_name}. This typically
23637 would be either @var{var1_name} or @var{_var1_name}, depending on operating
23638 system conventions, but other possibilities exist. The link name for
23639 @var{Var2} is @var{var2_link_name}, and this is not operating system
23640 dependent.
23641
23642 @findex _main
23643 One exception occurs for library level procedures. A potential ambiguity
23644 arises between the required name @code{_main} for the C main program,
23645 and the name we would otherwise assign to an Ada library level procedure
23646 called @code{Main} (which might well not be the main program).
23647
23648 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
23649 names. So if we have a library level procedure such as
23650
23651 @smallexample @c ada
23652 @group
23653 @cartouche
23654 procedure Hello (S : String);
23655 @end cartouche
23656 @end group
23657 @end smallexample
23658
23659 @noindent
23660 the external name of this procedure will be @var{_ada_hello}.
23661
23662
23663 @node Converting Ada Files to html with gnathtml
23664 @section Converting Ada Files to HTML with @code{gnathtml}
23665
23666 @noindent
23667 This @code{Perl} script allows Ada source files to be browsed using
23668 standard Web browsers. For installation procedure, see the section
23669 @xref{Installing gnathtml}.
23670
23671 Ada reserved keywords are highlighted in a bold font and Ada comments in
23672 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
23673 switch to suppress the generation of cross-referencing information, user
23674 defined variables and types will appear in a different color; you will
23675 be able to click on any identifier and go to its declaration.
23676
23677 The command line is as follow:
23678 @smallexample
23679 $ perl gnathtml.pl @ovar{^switches^options^} @var{ada-files}
23680 @end smallexample
23681
23682 @noindent
23683 You can pass it as many Ada files as you want. @code{gnathtml} will generate
23684 an html file for every ada file, and a global file called @file{index.htm}.
23685 This file is an index of every identifier defined in the files.
23686
23687 The available ^switches^options^ are the following ones:
23688
23689 @table @option
23690 @item -83
23691 @cindex @option{-83} (@code{gnathtml})
23692 Only the Ada 83 subset of keywords will be highlighted.
23693
23694 @item -cc @var{color}
23695 @cindex @option{-cc} (@code{gnathtml})
23696 This option allows you to change the color used for comments. The default
23697 value is green. The color argument can be any name accepted by html.
23698
23699 @item -d
23700 @cindex @option{-d} (@code{gnathtml})
23701 If the Ada files depend on some other files (for instance through
23702 @code{with} clauses, the latter files will also be converted to html.
23703 Only the files in the user project will be converted to html, not the files
23704 in the run-time library itself.
23705
23706 @item -D
23707 @cindex @option{-D} (@code{gnathtml})
23708 This command is the same as @option{-d} above, but @command{gnathtml} will
23709 also look for files in the run-time library, and generate html files for them.
23710
23711 @item -ext @var{extension}
23712 @cindex @option{-ext} (@code{gnathtml})
23713 This option allows you to change the extension of the generated HTML files.
23714 If you do not specify an extension, it will default to @file{htm}.
23715
23716 @item -f
23717 @cindex @option{-f} (@code{gnathtml})
23718 By default, gnathtml will generate html links only for global entities
23719 ('with'ed units, global variables and types,@dots{}).  If you specify
23720 @option{-f} on the command line, then links will be generated for local
23721 entities too.
23722
23723 @item -l @var{number}
23724 @cindex @option{-l} (@code{gnathtml})
23725 If this ^switch^option^ is provided and @var{number} is not 0, then
23726 @code{gnathtml} will number the html files every @var{number} line.
23727
23728 @item -I @var{dir}
23729 @cindex @option{-I} (@code{gnathtml})
23730 Specify a directory to search for library files (@file{.ALI} files) and
23731 source files. You can provide several -I switches on the command line,
23732 and the directories will be parsed in the order of the command line.
23733
23734 @item -o @var{dir}
23735 @cindex @option{-o} (@code{gnathtml})
23736 Specify the output directory for html files. By default, gnathtml will
23737 saved the generated html files in a subdirectory named @file{html/}.
23738
23739 @item -p @var{file}
23740 @cindex @option{-p} (@code{gnathtml})
23741 If you are using Emacs and the most recent Emacs Ada mode, which provides
23742 a full Integrated Development Environment for compiling, checking,
23743 running and debugging applications, you may use @file{.gpr} files
23744 to give the directories where Emacs can find sources and object files.
23745
23746 Using this ^switch^option^, you can tell gnathtml to use these files.
23747 This allows you to get an html version of your application, even if it
23748 is spread over multiple directories.
23749
23750 @item -sc @var{color}
23751 @cindex @option{-sc} (@code{gnathtml})
23752 This ^switch^option^ allows you to change the color used for symbol
23753 definitions.
23754 The default value is red. The color argument can be any name accepted by html.
23755
23756 @item -t @var{file}
23757 @cindex @option{-t} (@code{gnathtml})
23758 This ^switch^option^ provides the name of a file. This file contains a list of
23759 file names to be converted, and the effect is exactly as though they had
23760 appeared explicitly on the command line. This
23761 is the recommended way to work around the command line length limit on some
23762 systems.
23763
23764 @end table
23765
23766 @node Installing gnathtml
23767 @section Installing @code{gnathtml}
23768
23769 @noindent
23770 @code{Perl} needs to be installed on your machine to run this script.
23771 @code{Perl} is freely available for almost every architecture and
23772 Operating System via the Internet.
23773
23774 On Unix systems, you  may want to modify  the  first line of  the script
23775 @code{gnathtml},  to explicitly  tell  the Operating  system  where Perl
23776 is. The syntax of this line is:
23777 @smallexample
23778 #!full_path_name_to_perl
23779 @end smallexample
23780
23781 @noindent
23782 Alternatively, you may run the script using the following command line:
23783
23784 @smallexample
23785 $ perl gnathtml.pl @ovar{switches} @var{files}
23786 @end smallexample
23787
23788 @ifset vms
23789 @node LSE
23790 @section LSE
23791 @findex LSE
23792
23793 @noindent
23794 The GNAT distribution provides an Ada 95 template for the HP Language
23795 Sensitive Editor (LSE), a component of DECset. In order to
23796 access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
23797
23798 @node Profiling
23799 @section Profiling
23800 @findex PCA
23801
23802 @noindent
23803 GNAT supports The HP Performance Coverage Analyzer (PCA), a component
23804 of DECset. To use it proceed as outlined under ``HELP PCA'', except for running
23805 the collection phase with the /DEBUG qualifier.
23806
23807 @smallexample
23808 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
23809 $ DEFINE LIB$DEBUG PCA$COLLECTOR
23810 $ RUN/DEBUG <PROGRAM_NAME>
23811 @end smallexample
23812 @noindent
23813 @end ifset
23814
23815 @ifclear vms
23816 @c ******************************
23817 @node Code Coverage and Profiling
23818 @chapter Code Coverage and Profiling
23819 @cindex Code Coverage
23820 @cindex Profiling
23821
23822 @noindent
23823 This chapter describes how to use @code{gcov} - coverage testing tool - and
23824 @code{gprof} - profiler tool - on your Ada programs.
23825
23826 @menu
23827 * Code Coverage of Ada Programs using gcov::
23828 * Profiling an Ada Program using gprof::
23829 @end menu
23830
23831 @node Code Coverage of Ada Programs using gcov
23832 @section Code Coverage of Ada Programs using gcov
23833 @cindex gcov
23834 @cindex -fprofile-arcs
23835 @cindex -ftest-coverage
23836 @cindex -coverage
23837 @cindex Code Coverage
23838
23839 @noindent
23840 @code{gcov} is a test coverage program: it analyzes the execution of a given
23841 program on selected tests, to help you determine the portions of the program
23842 that are still untested.
23843
23844 @code{gcov} is part of the GCC suite, and is described in detail in the GCC
23845 User's Guide. You can refer to this documentation for a more complete
23846 description.
23847
23848 This chapter provides a quick startup guide, and
23849 details some Gnat-specific features.
23850
23851 @menu
23852 * Quick startup guide::
23853 * Gnat specifics::
23854 @end menu
23855
23856 @node Quick startup guide
23857 @subsection Quick startup guide
23858
23859 In order to perform coverage analysis of a program using @code{gcov}, 3
23860 steps are needed:
23861
23862 @itemize @bullet
23863 @item
23864 Code instrumentation during the compilation process
23865 @item
23866 Execution of the instrumented program
23867 @item
23868 Execution of the @code{gcov} tool to generate the result.
23869 @end itemize
23870
23871 The code instrumentation needed by gcov is created at the object level:
23872 The source code is not modified in any way, because the instrumentation code is
23873 inserted by gcc during the compilation process. To compile your code with code
23874 coverage activated, you need to recompile your whole project using the
23875 switches
23876 @code{-fprofile-arcs} and @code{-ftest-coverage}, and link it using
23877 @code{-fprofile-arcs}.
23878
23879 @smallexample
23880 $ gnatmake -P my_project.gpr -f -cargs -fprofile-arcs -ftest-coverage \
23881    -largs -fprofile-arcs
23882 @end smallexample
23883
23884 This compilation process will create @file{.gcno} files together with
23885 the usual object files.
23886
23887 Once the program is compiled with coverage instrumentation, you can
23888 run it as many times as needed - on portions of a test suite for
23889 example. The first execution will produce @file{.gcda} files at the
23890 same location as the @file{.gcno} files.  The following executions
23891 will update those files, so that a cumulative result of the covered
23892 portions of the program is generated.
23893
23894 Finally, you need to call the @code{gcov} tool. The different options of
23895 @code{gcov} are available in the GCC User's Guide, section 'Invoking gcov'.
23896
23897 This will create annotated source files with a @file{.gcov} extension:
23898 @file{my_main.adb} file will be analysed in @file{my_main.adb.gcov}.
23899
23900 @node Gnat specifics
23901 @subsection Gnat specifics
23902
23903 Because Ada semantics, portions of the source code may be shared among
23904 several object files. This is the case for example when generics are
23905 involved, when inlining is active  or when declarations generate  initialisation
23906 calls. In order to take
23907 into account this shared code, you need to call @code{gcov} on all
23908 source files of the tested program at once.
23909
23910 The list of source files might exceed the system's maximum command line
23911 length. In order to bypass this limitation, a new mechanism has been
23912 implemented in @code{gcov}: you can now list all your project's files into a
23913 text file, and provide this file to gcov as a parameter,  preceded by a @@
23914 (e.g. @samp{gcov @@mysrclist.txt}).
23915
23916 Note that on AIX compiling a static library with @code{-fprofile-arcs} is
23917 not supported as there can be unresolved symbols during the final link.
23918
23919 @node Profiling an Ada Program using gprof
23920 @section Profiling an Ada Program using gprof
23921 @cindex gprof
23922 @cindex -pg
23923 @cindex Profiling
23924
23925 @noindent
23926 This section is not meant to be an exhaustive documentation of @code{gprof}.
23927 Full documentation for it can be found in the GNU Profiler User's Guide
23928 documentation that is part of this GNAT distribution.
23929
23930 Profiling a program helps determine the parts of a program that are executed
23931 most often, and are therefore the most time-consuming.
23932
23933 @code{gprof} is the standard GNU profiling tool; it has been enhanced to
23934 better handle Ada programs and multitasking.
23935 It is currently supported on the following platforms
23936 @itemize @bullet
23937 @item
23938 linux x86/x86_64
23939 @item
23940 solaris sparc/sparc64/x86
23941 @item
23942 windows x86
23943 @end itemize
23944
23945 @noindent
23946 In order to profile a program using @code{gprof}, 3 steps are needed:
23947
23948 @itemize @bullet
23949 @item
23950 Code instrumentation, requiring a full recompilation of the project with the
23951 proper switches.
23952 @item
23953 Execution of the program under the analysis conditions, i.e. with the desired
23954 input.
23955 @item
23956 Analysis of the results using the @code{gprof} tool.
23957 @end itemize
23958
23959 @noindent
23960 The following sections detail the different steps, and indicate how
23961 to interpret the results:
23962 @menu
23963 * Compilation for profiling::
23964 * Program execution::
23965 * Running gprof::
23966 * Interpretation of profiling results::
23967 @end menu
23968
23969 @node Compilation for profiling
23970 @subsection Compilation for profiling
23971 @cindex -pg
23972 @cindex Profiling
23973
23974 In order to profile a program the first step is to tell the compiler
23975 to generate the necessary profiling information. The compiler switch to be used
23976 is @code{-pg}, which must be added to other compilation switches. This
23977 switch needs to be specified both during compilation and link stages, and can
23978 be specified once when using gnatmake:
23979
23980 @smallexample
23981 gnatmake -f -pg -P my_project
23982 @end smallexample
23983
23984 @noindent
23985 Note that only the objects that were compiled with the @samp{-pg} switch will be
23986 profiled; if you need to profile your whole project, use the
23987 @samp{-f} gnatmake switch to force full recompilation.
23988
23989 @node Program execution
23990 @subsection Program execution
23991
23992 @noindent
23993 Once the program has been compiled for profiling, you can run it as usual.
23994
23995 The only constraint imposed by profiling is that the program must terminate
23996 normally. An interrupted program (via a Ctrl-C, kill, etc.) will not be
23997 properly analyzed.
23998
23999 Once the program completes execution, a data file called @file{gmon.out} is
24000 generated in the directory where the program was launched from. If this file
24001 already exists, it will be overwritten.
24002
24003 @node Running gprof
24004 @subsection Running gprof
24005
24006 @noindent
24007 The @code{gprof} tool is called as follow:
24008
24009 @smallexample
24010 gprof my_prog gmon.out
24011 @end smallexample
24012
24013 @noindent
24014 or simpler:
24015
24016 @smallexample
24017 gprof my_prog
24018 @end smallexample
24019
24020 @noindent
24021 The complete form of the gprof command line is the following:
24022
24023 @smallexample
24024 gprof [^switches^options^] [executable [data-file]]
24025 @end smallexample
24026
24027 @noindent
24028 @code{gprof} supports numerous ^switch^options^. The order of these
24029 ^switch^options^ does not matter. The full list of options can be found in
24030 the GNU Profiler User's Guide documentation that comes with this documentation.
24031
24032 The following is the subset of those switches that is most relevant:
24033
24034 @table @option
24035
24036 @item --demangle[=@var{style}]
24037 @itemx --no-demangle
24038 @cindex @option{--demangle} (@code{gprof})
24039 These options control whether symbol names should be demangled when
24040 printing output.  The default is to demangle C++ symbols.  The
24041 @code{--no-demangle} option may be used to turn off demangling. Different
24042 compilers have different mangling styles.  The optional demangling style
24043 argument can be used to choose an appropriate demangling style for your
24044 compiler, in particular Ada symbols generated by GNAT can be demangled using
24045 @code{--demangle=gnat}.
24046
24047 @item -e @var{function_name}
24048 @cindex @option{-e} (@code{gprof})
24049 The @samp{-e @var{function}} option tells @code{gprof} not to print
24050 information about the function @var{function_name} (and its
24051 children@dots{}) in the call graph.  The function will still be listed
24052 as a child of any functions that call it, but its index number will be
24053 shown as @samp{[not printed]}.  More than one @samp{-e} option may be
24054 given; only one @var{function_name} may be indicated with each @samp{-e}
24055 option.
24056
24057 @item -E @var{function_name}
24058 @cindex @option{-E} (@code{gprof})
24059 The @code{-E @var{function}} option works like the @code{-e} option, but
24060 execution time spent in the function (and children who were not called from
24061 anywhere else), will not be used to compute the percentages-of-time for
24062 the call graph.  More than one @samp{-E} option may be given; only one
24063 @var{function_name} may be indicated with each @samp{-E} option.
24064
24065 @item -f @var{function_name}
24066 @cindex @option{-f} (@code{gprof})
24067 The @samp{-f @var{function}} option causes @code{gprof} to limit the
24068 call graph to the function @var{function_name} and its children (and
24069 their children@dots{}).  More than one @samp{-f} option may be given;
24070 only one @var{function_name} may be indicated with each @samp{-f}
24071 option.
24072
24073 @item -F @var{function_name}
24074 @cindex @option{-F} (@code{gprof})
24075 The @samp{-F @var{function}} option works like the @code{-f} option, but
24076 only time spent in the function and its children (and their
24077 children@dots{}) will be used to determine total-time and
24078 percentages-of-time for the call graph.  More than one @samp{-F} option
24079 may be given; only one @var{function_name} may be indicated with each
24080 @samp{-F} option.  The @samp{-F} option overrides the @samp{-E} option.
24081
24082 @end table
24083
24084 @node Interpretation of profiling results
24085 @subsection Interpretation of profiling results
24086
24087 @noindent
24088
24089 The results of the profiling analysis are represented by two arrays: the
24090 'flat profile' and the 'call graph'. Full documentation of those outputs
24091 can be found in the GNU Profiler User's Guide.
24092
24093 The flat profile shows the time spent in each function of the program, and how
24094 many time it has been called. This allows you to locate easily the most
24095 time-consuming functions.
24096
24097 The call graph shows, for each subprogram, the subprograms that call it,
24098 and the subprograms that it calls. It also provides an estimate of the time
24099 spent in each of those callers/called subprograms.
24100 @end ifclear
24101
24102 @c ******************************
24103 @node Running and Debugging Ada Programs
24104 @chapter Running and Debugging Ada Programs
24105 @cindex Debugging
24106
24107 @noindent
24108 This chapter discusses how to debug Ada programs.
24109 @ifset vms
24110 It applies to GNAT on the Alpha OpenVMS platform;
24111 for I64 OpenVMS please refer to the @cite{OpenVMS Debugger Manual},
24112 since HP has implemented Ada support in the OpenVMS debugger on I64.
24113 @end ifset
24114
24115 An incorrect Ada program may be handled in three ways by the GNAT compiler:
24116
24117 @enumerate
24118 @item
24119 The illegality may be a violation of the static semantics of Ada. In
24120 that case GNAT diagnoses the constructs in the program that are illegal.
24121 It is then a straightforward matter for the user to modify those parts of
24122 the program.
24123
24124 @item
24125 The illegality may be a violation of the dynamic semantics of Ada. In
24126 that case the program compiles and executes, but may generate incorrect
24127 results, or may terminate abnormally with some exception.
24128
24129 @item
24130 When presented with a program that contains convoluted errors, GNAT
24131 itself may terminate abnormally without providing full diagnostics on
24132 the incorrect user program.
24133 @end enumerate
24134
24135 @menu
24136 * The GNAT Debugger GDB::
24137 * Running GDB::
24138 * Introduction to GDB Commands::
24139 * Using Ada Expressions::
24140 * Calling User-Defined Subprograms::
24141 * Using the Next Command in a Function::
24142 * Ada Exceptions::
24143 * Ada Tasks::
24144 * Debugging Generic Units::
24145 * GNAT Abnormal Termination or Failure to Terminate::
24146 * Naming Conventions for GNAT Source Files::
24147 * Getting Internal Debugging Information::
24148 * Stack Traceback::
24149 @end menu
24150
24151 @cindex Debugger
24152 @findex gdb
24153
24154 @node The GNAT Debugger GDB
24155 @section The GNAT Debugger GDB
24156
24157 @noindent
24158 @code{GDB} is a general purpose, platform-independent debugger that
24159 can be used to debug mixed-language programs compiled with @command{gcc},
24160 and in particular is capable of debugging Ada programs compiled with
24161 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
24162 complex Ada data structures.
24163
24164 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
24165 @ifset vms
24166 located in the GNU:[DOCS] directory,
24167 @end ifset
24168 for full details on the usage of @code{GDB}, including a section on
24169 its usage on programs. This manual should be consulted for full
24170 details. The section that follows is a brief introduction to the
24171 philosophy and use of @code{GDB}.
24172
24173 When GNAT programs are compiled, the compiler optionally writes debugging
24174 information into the generated object file, including information on
24175 line numbers, and on declared types and variables. This information is
24176 separate from the generated code. It makes the object files considerably
24177 larger, but it does not add to the size of the actual executable that
24178 will be loaded into memory, and has no impact on run-time performance. The
24179 generation of debug information is triggered by the use of the
24180 ^-g^/DEBUG^ switch in the @command{gcc} or @command{gnatmake} command
24181 used to carry out the compilations. It is important to emphasize that
24182 the use of these options does not change the generated code.
24183
24184 The debugging information is written in standard system formats that
24185 are used by many tools, including debuggers and profilers. The format
24186 of the information is typically designed to describe C types and
24187 semantics, but GNAT implements a translation scheme which allows full
24188 details about Ada types and variables to be encoded into these
24189 standard C formats. Details of this encoding scheme may be found in
24190 the file exp_dbug.ads in the GNAT source distribution. However, the
24191 details of this encoding are, in general, of no interest to a user,
24192 since @code{GDB} automatically performs the necessary decoding.
24193
24194 When a program is bound and linked, the debugging information is
24195 collected from the object files, and stored in the executable image of
24196 the program. Again, this process significantly increases the size of
24197 the generated executable file, but it does not increase the size of
24198 the executable program itself. Furthermore, if this program is run in
24199 the normal manner, it runs exactly as if the debug information were
24200 not present, and takes no more actual memory.
24201
24202 However, if the program is run under control of @code{GDB}, the
24203 debugger is activated.  The image of the program is loaded, at which
24204 point it is ready to run.  If a run command is given, then the program
24205 will run exactly as it would have if @code{GDB} were not present. This
24206 is a crucial part of the @code{GDB} design philosophy.  @code{GDB} is
24207 entirely non-intrusive until a breakpoint is encountered.  If no
24208 breakpoint is ever hit, the program will run exactly as it would if no
24209 debugger were present. When a breakpoint is hit, @code{GDB} accesses
24210 the debugging information and can respond to user commands to inspect
24211 variables, and more generally to report on the state of execution.
24212
24213 @c **************
24214 @node Running GDB
24215 @section Running GDB
24216
24217 @noindent
24218 This section describes how to initiate the debugger.
24219 @c The above sentence is really just filler, but it was otherwise
24220 @c clumsy to get the first paragraph nonindented given the conditional
24221 @c nature of the description
24222
24223 @ifclear vms
24224 The debugger can be launched from a @code{GPS} menu or
24225 directly from the command line. The description below covers the latter use.
24226 All the commands shown can be used in the @code{GPS} debug console window,
24227 but there are usually more GUI-based ways to achieve the same effect.
24228 @end ifclear
24229
24230 The command to run @code{GDB} is
24231
24232 @smallexample
24233 $ ^gdb program^GDB PROGRAM^
24234 @end smallexample
24235
24236 @noindent
24237 where @code{^program^PROGRAM^} is the name of the executable file. This
24238 activates the debugger and results in a prompt for debugger commands.
24239 The simplest command is simply @code{run}, which causes the program to run
24240 exactly as if the debugger were not present. The following section
24241 describes some of the additional commands that can be given to @code{GDB}.
24242
24243 @c *******************************
24244 @node Introduction to GDB Commands
24245 @section Introduction to GDB Commands
24246
24247 @noindent
24248 @code{GDB} contains a large repertoire of commands.  @xref{Top,,
24249 Debugging with GDB, gdb, Debugging with GDB},
24250 @ifset vms
24251 located in the GNU:[DOCS] directory,
24252 @end ifset
24253 for extensive documentation on the use
24254 of these commands, together with examples of their use. Furthermore,
24255 the command @command{help} invoked from within GDB activates a simple help
24256 facility which summarizes the available commands and their options.
24257 In this section we summarize a few of the most commonly
24258 used commands to give an idea of what @code{GDB} is about. You should create
24259 a simple program with debugging information and experiment with the use of
24260 these @code{GDB} commands on the program as you read through the
24261 following section.
24262
24263 @table @code
24264 @item set args @var{arguments}
24265 The @var{arguments} list above is a list of arguments to be passed to
24266 the program on a subsequent run command, just as though the arguments
24267 had been entered on a normal invocation of the program. The @code{set args}
24268 command is not needed if the program does not require arguments.
24269
24270 @item run
24271 The @code{run} command causes execution of the program to start from
24272 the beginning. If the program is already running, that is to say if
24273 you are currently positioned at a breakpoint, then a prompt will ask
24274 for confirmation that you want to abandon the current execution and
24275 restart.
24276
24277 @item breakpoint @var{location}
24278 The breakpoint command sets a breakpoint, that is to say a point at which
24279 execution will halt and @code{GDB} will await further
24280 commands. @var{location} is
24281 either a line number within a file, given in the format @code{file:linenumber},
24282 or it is the name of a subprogram. If you request that a breakpoint be set on
24283 a subprogram that is overloaded, a prompt will ask you to specify on which of
24284 those subprograms you want to breakpoint. You can also
24285 specify that all of them should be breakpointed. If the program is run
24286 and execution encounters the breakpoint, then the program
24287 stops and @code{GDB} signals that the breakpoint was encountered by
24288 printing the line of code before which the program is halted.
24289
24290 @item breakpoint exception @var{name}
24291 A special form of the breakpoint command which breakpoints whenever
24292 exception @var{name} is raised.
24293 If @var{name} is omitted,
24294 then a breakpoint will occur when any exception is raised.
24295
24296 @item print @var{expression}
24297 This will print the value of the given expression. Most simple
24298 Ada expression formats are properly handled by @code{GDB}, so the expression
24299 can contain function calls, variables, operators, and attribute references.
24300
24301 @item continue
24302 Continues execution following a breakpoint, until the next breakpoint or the
24303 termination of the program.
24304
24305 @item step
24306 Executes a single line after a breakpoint. If the next statement
24307 is a subprogram call, execution continues into (the first statement of)
24308 the called subprogram.
24309
24310 @item next
24311 Executes a single line. If this line is a subprogram call, executes and
24312 returns from the call.
24313
24314 @item list
24315 Lists a few lines around the current source location. In practice, it
24316 is usually more convenient to have a separate edit window open with the
24317 relevant source file displayed. Successive applications of this command
24318 print subsequent lines. The command can be given an argument which is a
24319 line number, in which case it displays a few lines around the specified one.
24320
24321 @item backtrace
24322 Displays a backtrace of the call chain. This command is typically
24323 used after a breakpoint has occurred, to examine the sequence of calls that
24324 leads to the current breakpoint. The display includes one line for each
24325 activation record (frame) corresponding to an active subprogram.
24326
24327 @item up
24328 At a breakpoint, @code{GDB} can display the values of variables local
24329 to the current frame. The command @code{up} can be used to
24330 examine the contents of other active frames, by moving the focus up
24331 the stack, that is to say from callee to caller, one frame at a time.
24332
24333 @item down
24334 Moves the focus of @code{GDB} down from the frame currently being
24335 examined to the frame of its callee (the reverse of the previous command),
24336
24337 @item frame @var{n}
24338 Inspect the frame with the given number. The value 0 denotes the frame
24339 of the current breakpoint, that is to say the top of the call stack.
24340
24341 @end table
24342
24343 @noindent
24344 The above list is a very short introduction to the commands that
24345 @code{GDB} provides. Important additional capabilities, including conditional
24346 breakpoints, the ability to execute command sequences on a breakpoint,
24347 the ability to debug at the machine instruction level and many other
24348 features are described in detail in @ref{Top,, Debugging with GDB, gdb,
24349 Debugging with GDB}.  Note that most commands can be abbreviated
24350 (for example, c for continue, bt for backtrace).
24351
24352 @node Using Ada Expressions
24353 @section Using Ada Expressions
24354 @cindex Ada expressions
24355
24356 @noindent
24357 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
24358 extensions. The philosophy behind the design of this subset is
24359
24360 @itemize @bullet
24361 @item
24362 That @code{GDB} should provide basic literals and access to operations for
24363 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
24364 leaving more sophisticated computations to subprograms written into the
24365 program (which therefore may be called from @code{GDB}).
24366
24367 @item
24368 That type safety and strict adherence to Ada language restrictions
24369 are not particularly important to the @code{GDB} user.
24370
24371 @item
24372 That brevity is important to the @code{GDB} user.
24373 @end itemize
24374
24375 @noindent
24376 Thus, for brevity, the debugger acts as if there were
24377 implicit @code{with} and @code{use} clauses in effect for all user-written
24378 packages, thus making it unnecessary to fully qualify most names with
24379 their packages, regardless of context. Where this causes ambiguity,
24380 @code{GDB} asks the user's intent.
24381
24382 For details on the supported Ada syntax, see @ref{Top,, Debugging with
24383 GDB, gdb, Debugging with GDB}.
24384
24385 @node Calling User-Defined Subprograms
24386 @section Calling User-Defined Subprograms
24387
24388 @noindent
24389 An important capability of @code{GDB} is the ability to call user-defined
24390 subprograms while debugging. This is achieved simply by entering
24391 a subprogram call statement in the form:
24392
24393 @smallexample
24394 call subprogram-name (parameters)
24395 @end smallexample
24396
24397 @noindent
24398 The keyword @code{call} can be omitted in the normal case where the
24399 @code{subprogram-name} does not coincide with any of the predefined
24400 @code{GDB} commands.
24401
24402 The effect is to invoke the given subprogram, passing it the
24403 list of parameters that is supplied. The parameters can be expressions and
24404 can include variables from the program being debugged. The
24405 subprogram must be defined
24406 at the library level within your program, and @code{GDB} will call the
24407 subprogram within the environment of your program execution (which
24408 means that the subprogram is free to access or even modify variables
24409 within your program).
24410
24411 The most important use of this facility is in allowing the inclusion of
24412 debugging routines that are tailored to particular data structures
24413 in your program. Such debugging routines can be written to provide a suitably
24414 high-level description of an abstract type, rather than a low-level dump
24415 of its physical layout. After all, the standard
24416 @code{GDB print} command only knows the physical layout of your
24417 types, not their abstract meaning. Debugging routines can provide information
24418 at the desired semantic level and are thus enormously useful.
24419
24420 For example, when debugging GNAT itself, it is crucial to have access to
24421 the contents of the tree nodes used to represent the program internally.
24422 But tree nodes are represented simply by an integer value (which in turn
24423 is an index into a table of nodes).
24424 Using the @code{print} command on a tree node would simply print this integer
24425 value, which is not very useful. But the PN routine (defined in file
24426 treepr.adb in the GNAT sources) takes a tree node as input, and displays
24427 a useful high level representation of the tree node, which includes the
24428 syntactic category of the node, its position in the source, the integers
24429 that denote descendant nodes and parent node, as well as varied
24430 semantic information. To study this example in more detail, you might want to
24431 look at the body of the PN procedure in the stated file.
24432
24433 @node Using the Next Command in a Function
24434 @section Using the Next Command in a Function
24435
24436 @noindent
24437 When you use the @code{next} command in a function, the current source
24438 location will advance to the next statement as usual. A special case
24439 arises in the case of a @code{return} statement.
24440
24441 Part of the code for a return statement is the ``epilog'' of the function.
24442 This is the code that returns to the caller. There is only one copy of
24443 this epilog code, and it is typically associated with the last return
24444 statement in the function if there is more than one return. In some
24445 implementations, this epilog is associated with the first statement
24446 of the function.
24447
24448 The result is that if you use the @code{next} command from a return
24449 statement that is not the last return statement of the function you
24450 may see a strange apparent jump to the last return statement or to
24451 the start of the function. You should simply ignore this odd jump.
24452 The value returned is always that from the first return statement
24453 that was stepped through.
24454
24455 @node Ada Exceptions
24456 @section Breaking on Ada Exceptions
24457 @cindex Exceptions
24458
24459 @noindent
24460 You can set breakpoints that trip when your program raises
24461 selected exceptions.
24462
24463 @table @code
24464 @item break exception
24465 Set a breakpoint that trips whenever (any task in the) program raises
24466 any exception.
24467
24468 @item break exception @var{name}
24469 Set a breakpoint that trips whenever (any task in the) program raises
24470 the exception @var{name}.
24471
24472 @item break exception unhandled
24473 Set a breakpoint that trips whenever (any task in the) program raises an
24474 exception for which there is no handler.
24475
24476 @item info exceptions
24477 @itemx info exceptions @var{regexp}
24478 The @code{info exceptions} command permits the user to examine all defined
24479 exceptions within Ada programs. With a regular expression, @var{regexp}, as
24480 argument, prints out only those exceptions whose name matches @var{regexp}.
24481 @end table
24482
24483 @node Ada Tasks
24484 @section Ada Tasks
24485 @cindex Tasks
24486
24487 @noindent
24488 @code{GDB} allows the following task-related commands:
24489
24490 @table @code
24491 @item info tasks
24492 This command shows a list of current Ada tasks, as in the following example:
24493
24494 @smallexample
24495 @iftex
24496 @leftskip=0cm
24497 @end iftex
24498 (gdb) info tasks
24499   ID       TID P-ID   Thread Pri State                 Name
24500    1   8088000   0   807e000  15 Child Activation Wait main_task
24501    2   80a4000   1   80ae000  15 Accept/Select Wait    b
24502    3   809a800   1   80a4800  15 Child Activation Wait a
24503 *  4   80ae800   3   80b8000  15 Running               c
24504 @end smallexample
24505
24506 @noindent
24507 In this listing, the asterisk before the first task indicates it to be the
24508 currently running task. The first column lists the task ID that is used
24509 to refer to tasks in the following commands.
24510
24511 @item break @var{linespec} task @var{taskid}
24512 @itemx break @var{linespec} task @var{taskid} if @dots{}
24513 @cindex Breakpoints and tasks
24514 These commands are like the @code{break @dots{} thread @dots{}}.
24515 @var{linespec} specifies source lines.
24516
24517 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
24518 to specify that you only want @code{GDB} to stop the program when a
24519 particular Ada task reaches this breakpoint. @var{taskid} is one of the
24520 numeric task identifiers assigned by @code{GDB}, shown in the first
24521 column of the @samp{info tasks} display.
24522
24523 If you do not specify @samp{task @var{taskid}} when you set a
24524 breakpoint, the breakpoint applies to @emph{all} tasks of your
24525 program.
24526
24527 You can use the @code{task} qualifier on conditional breakpoints as
24528 well; in this case, place @samp{task @var{taskid}} before the
24529 breakpoint condition (before the @code{if}).
24530
24531 @item task @var{taskno}
24532 @cindex Task switching
24533
24534 This command allows to switch to the task referred by @var{taskno}. In
24535 particular, This allows to browse the backtrace of the specified
24536 task. It is advised to switch back to the original task before
24537 continuing execution otherwise the scheduling of the program may be
24538 perturbed.
24539 @end table
24540
24541 @noindent
24542 For more detailed information on the tasking support,
24543 see @ref{Top,, Debugging with GDB, gdb, Debugging with GDB}.
24544
24545 @node Debugging Generic Units
24546 @section Debugging Generic Units
24547 @cindex Debugging Generic Units
24548 @cindex Generics
24549
24550 @noindent
24551 GNAT always uses code expansion for generic instantiation. This means that
24552 each time an instantiation occurs, a complete copy of the original code is
24553 made, with appropriate substitutions of formals by actuals.
24554
24555 It is not possible to refer to the original generic entities in
24556 @code{GDB}, but it is always possible to debug a particular instance of
24557 a generic, by using the appropriate expanded names. For example, if we have
24558
24559 @smallexample @c ada
24560 @group
24561 @cartouche
24562 procedure g is
24563
24564    generic package k is
24565       procedure kp (v1 : in out integer);
24566    end k;
24567
24568    package body k is
24569       procedure kp (v1 : in out integer) is
24570       begin
24571          v1 := v1 + 1;
24572       end kp;
24573    end k;
24574
24575    package k1 is new k;
24576    package k2 is new k;
24577
24578    var : integer := 1;
24579
24580 begin
24581    k1.kp (var);
24582    k2.kp (var);
24583    k1.kp (var);
24584    k2.kp (var);
24585 end;
24586 @end cartouche
24587 @end group
24588 @end smallexample
24589
24590 @noindent
24591 Then to break on a call to procedure kp in the k2 instance, simply
24592 use the command:
24593
24594 @smallexample
24595 (gdb) break g.k2.kp
24596 @end smallexample
24597
24598 @noindent
24599 When the breakpoint occurs, you can step through the code of the
24600 instance in the normal manner and examine the values of local variables, as for
24601 other units.
24602
24603 @node GNAT Abnormal Termination or Failure to Terminate
24604 @section GNAT Abnormal Termination or Failure to Terminate
24605 @cindex GNAT Abnormal Termination or Failure to Terminate
24606
24607 @noindent
24608 When presented with programs that contain serious errors in syntax
24609 or semantics,
24610 GNAT may on rare occasions  experience problems in operation, such
24611 as aborting with a
24612 segmentation fault or illegal memory access, raising an internal
24613 exception, terminating abnormally, or failing to terminate at all.
24614 In such cases, you can activate
24615 various features of GNAT that can help you pinpoint the construct in your
24616 program that is the likely source of the problem.
24617
24618 The following strategies are presented in increasing order of
24619 difficulty, corresponding to your experience in using GNAT and your
24620 familiarity with compiler internals.
24621
24622 @enumerate
24623 @item
24624 Run @command{gcc} with the @option{-gnatf}. This first
24625 switch causes all errors on a given line to be reported. In its absence,
24626 only the first error on a line is displayed.
24627
24628 The @option{-gnatdO} switch causes errors to be displayed as soon as they
24629 are encountered, rather than after compilation is terminated. If GNAT
24630 terminates prematurely or goes into an infinite loop, the last error
24631 message displayed may help to pinpoint the culprit.
24632
24633 @item
24634 Run @command{gcc} with the @option{^-v (verbose)^/VERBOSE^} switch. In this
24635 mode, @command{gcc} produces ongoing information about the progress of the
24636 compilation and provides the name of each procedure as code is
24637 generated. This switch allows you to find which Ada procedure was being
24638 compiled when it encountered a code generation problem.
24639
24640 @item
24641 @cindex @option{-gnatdc} switch
24642 Run @command{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
24643 switch that does for the front-end what @option{^-v^VERBOSE^} does
24644 for the back end. The system prints the name of each unit,
24645 either a compilation unit or nested unit, as it is being analyzed.
24646 @item
24647 Finally, you can start
24648 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
24649 front-end of GNAT, and can be run independently (normally it is just
24650 called from @command{gcc}). You can use @code{gdb} on @code{gnat1} as you
24651 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
24652 @code{where} command is the first line of attack; the variable
24653 @code{lineno} (seen by @code{print lineno}), used by the second phase of
24654 @code{gnat1} and by the @command{gcc} backend, indicates the source line at
24655 which the execution stopped, and @code{input_file name} indicates the name of
24656 the source file.
24657 @end enumerate
24658
24659 @node Naming Conventions for GNAT Source Files
24660 @section Naming Conventions for GNAT Source Files
24661
24662 @noindent
24663 In order to examine the workings of the GNAT system, the following
24664 brief description of its organization may be helpful:
24665
24666 @itemize @bullet
24667 @item
24668 Files with prefix @file{^sc^SC^} contain the lexical scanner.
24669
24670 @item
24671 All files prefixed with @file{^par^PAR^} are components of the parser. The
24672 numbers correspond to chapters of the Ada Reference Manual. For example,
24673 parsing of select statements can be found in @file{par-ch9.adb}.
24674
24675 @item
24676 All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
24677 numbers correspond to chapters of the Ada standard. For example, all
24678 issues involving context clauses can be found in @file{sem_ch10.adb}. In
24679 addition, some features of the language require sufficient special processing
24680 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
24681 dynamic dispatching, etc.
24682
24683 @item
24684 All files prefixed with @file{^exp^EXP^} perform normalization and
24685 expansion of the intermediate representation (abstract syntax tree, or AST).
24686 these files use the same numbering scheme as the parser and semantics files.
24687 For example, the construction of record initialization procedures is done in
24688 @file{exp_ch3.adb}.
24689
24690 @item
24691 The files prefixed with @file{^bind^BIND^} implement the binder, which
24692 verifies the consistency of the compilation, determines an order of
24693 elaboration, and generates the bind file.
24694
24695 @item
24696 The files @file{atree.ads} and @file{atree.adb} detail the low-level
24697 data structures used by the front-end.
24698
24699 @item
24700 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
24701 the abstract syntax tree as produced by the parser.
24702
24703 @item
24704 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
24705 all entities, computed during semantic analysis.
24706
24707 @item
24708 Library management issues are dealt with in files with prefix
24709 @file{^lib^LIB^}.
24710
24711 @item
24712 @findex Ada
24713 @cindex Annex A
24714 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
24715 defined in Annex A.
24716
24717 @item
24718 @findex Interfaces
24719 @cindex Annex B
24720 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
24721 defined in Annex B.
24722
24723 @item
24724 @findex System
24725 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
24726 both language-defined children and GNAT run-time routines.
24727
24728 @item
24729 @findex GNAT
24730 Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
24731 general-purpose packages, fully documented in their specs. All
24732 the other @file{.c} files are modifications of common @command{gcc} files.
24733 @end itemize
24734
24735 @node Getting Internal Debugging Information
24736 @section Getting Internal Debugging Information
24737
24738 @noindent
24739 Most compilers have internal debugging switches and modes. GNAT
24740 does also, except GNAT internal debugging switches and modes are not
24741 secret. A summary and full description of all the compiler and binder
24742 debug flags are in the file @file{debug.adb}. You must obtain the
24743 sources of the compiler to see the full detailed effects of these flags.
24744
24745 The switches that print the source of the program (reconstructed from
24746 the internal tree) are of general interest for user programs, as are the
24747 options to print
24748 the full internal tree, and the entity table (the symbol table
24749 information). The reconstructed source provides a readable version of the
24750 program after the front-end has completed analysis and  expansion,
24751 and is useful when studying the performance of specific constructs.
24752 For example, constraint checks are indicated, complex aggregates
24753 are replaced with loops and assignments, and tasking primitives
24754 are replaced with run-time calls.
24755
24756 @node Stack Traceback
24757 @section Stack Traceback
24758 @cindex traceback
24759 @cindex stack traceback
24760 @cindex stack unwinding
24761
24762 @noindent
24763 Traceback is a mechanism to display the sequence of subprogram calls that
24764 leads to a specified execution point in a program. Often (but not always)
24765 the execution point is an instruction at which an exception has been raised.
24766 This mechanism is also known as @i{stack unwinding} because it obtains
24767 its information by scanning the run-time stack and recovering the activation
24768 records of all active subprograms. Stack unwinding is one of the most
24769 important tools for program debugging.
24770
24771 The first entry stored in traceback corresponds to the deepest calling level,
24772 that is to say the subprogram currently executing the instruction
24773 from which we want to obtain the traceback.
24774
24775 Note that there is no runtime performance penalty when stack traceback
24776 is enabled, and no exception is raised during program execution.
24777
24778 @menu
24779 * Non-Symbolic Traceback::
24780 * Symbolic Traceback::
24781 @end menu
24782
24783 @node Non-Symbolic Traceback
24784 @subsection Non-Symbolic Traceback
24785 @cindex traceback, non-symbolic
24786
24787 @noindent
24788 Note: this feature is not supported on all platforms. See
24789 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
24790 platforms.
24791
24792 @menu
24793 * Tracebacks From an Unhandled Exception::
24794 * Tracebacks From Exception Occurrences (non-symbolic)::
24795 * Tracebacks From Anywhere in a Program (non-symbolic)::
24796 @end menu
24797
24798 @node Tracebacks From an Unhandled Exception
24799 @subsubsection Tracebacks From an Unhandled Exception
24800
24801 @noindent
24802 A runtime non-symbolic traceback is a list of addresses of call instructions.
24803 To enable this feature you must use the @option{-E}
24804 @code{gnatbind}'s option. With this option a stack traceback is stored as part
24805 of exception information. You can retrieve this information using the
24806 @code{addr2line} tool.
24807
24808 Here is a simple example:
24809
24810 @smallexample @c ada
24811 @cartouche
24812 procedure STB is
24813
24814    procedure P1 is
24815    begin
24816       raise Constraint_Error;
24817    end P1;
24818
24819    procedure P2 is
24820    begin
24821       P1;
24822    end P2;
24823
24824 begin
24825    P2;
24826 end STB;
24827 @end cartouche
24828 @end smallexample
24829
24830 @smallexample
24831 $ gnatmake stb -bargs -E
24832 $ stb
24833
24834 Execution terminated by unhandled exception
24835 Exception name: CONSTRAINT_ERROR
24836 Message: stb.adb:5
24837 Call stack traceback locations:
24838 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
24839 @end smallexample
24840
24841 @noindent
24842 As we see the traceback lists a sequence of addresses for the unhandled
24843 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
24844 guess that this exception come from procedure P1. To translate these
24845 addresses into the source lines where the calls appear, the
24846 @code{addr2line} tool, described below, is invaluable. The use of this tool
24847 requires the program to be compiled with debug information.
24848
24849 @smallexample
24850 $ gnatmake -g stb -bargs -E
24851 $ stb
24852
24853 Execution terminated by unhandled exception
24854 Exception name: CONSTRAINT_ERROR
24855 Message: stb.adb:5
24856 Call stack traceback locations:
24857 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
24858
24859 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
24860    0x4011f1 0x77e892a4
24861
24862 00401373 at d:/stb/stb.adb:5
24863 0040138B at d:/stb/stb.adb:10
24864 0040139C at d:/stb/stb.adb:14
24865 00401335 at d:/stb/b~stb.adb:104
24866 004011C4 at /build/@dots{}/crt1.c:200
24867 004011F1 at /build/@dots{}/crt1.c:222
24868 77E892A4 in ?? at ??:0
24869 @end smallexample
24870
24871 @noindent
24872 The @code{addr2line} tool has several other useful options:
24873
24874 @table @code
24875 @item --functions
24876 to get the function name corresponding to any location
24877
24878 @item --demangle=gnat
24879 to use the gnat decoding mode for the function names. Note that
24880 for binutils version 2.9.x the option is simply @option{--demangle}.
24881 @end table
24882
24883 @smallexample
24884 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
24885    0x40139c 0x401335 0x4011c4 0x4011f1
24886
24887 00401373 in stb.p1 at d:/stb/stb.adb:5
24888 0040138B in stb.p2 at d:/stb/stb.adb:10
24889 0040139C in stb at d:/stb/stb.adb:14
24890 00401335 in main at d:/stb/b~stb.adb:104
24891 004011C4 in <__mingw_CRTStartup> at /build/@dots{}/crt1.c:200
24892 004011F1 in <mainCRTStartup> at /build/@dots{}/crt1.c:222
24893 @end smallexample
24894
24895 @noindent
24896 From this traceback we can see that the exception was raised in
24897 @file{stb.adb} at line 5, which was reached from a procedure call in
24898 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
24899 which contains the call to the main program.
24900 @xref{Running gnatbind}. The remaining entries are assorted runtime routines,
24901 and the output will vary from platform to platform.
24902
24903 It is also possible to use @code{GDB} with these traceback addresses to debug
24904 the program. For example, we can break at a given code location, as reported
24905 in the stack traceback:
24906
24907 @smallexample
24908 $ gdb -nw stb
24909 @ifclear vms
24910 @noindent
24911 Furthermore, this feature is not implemented inside Windows DLL. Only
24912 the non-symbolic traceback is reported in this case.
24913 @end ifclear
24914
24915 (gdb) break *0x401373
24916 Breakpoint 1 at 0x401373: file stb.adb, line 5.
24917 @end smallexample
24918
24919 @noindent
24920 It is important to note that the stack traceback addresses
24921 do not change when debug information is included. This is particularly useful
24922 because it makes it possible to release software without debug information (to
24923 minimize object size), get a field report that includes a stack traceback
24924 whenever an internal bug occurs, and then be able to retrieve the sequence
24925 of calls with the same program compiled with debug information.
24926
24927 @node Tracebacks From Exception Occurrences (non-symbolic)
24928 @subsubsection Tracebacks From Exception Occurrences
24929
24930 @noindent
24931 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
24932 The stack traceback is attached to the exception information string, and can
24933 be retrieved in an exception handler within the Ada program, by means of the
24934 Ada facilities defined in @code{Ada.Exceptions}. Here is a simple example:
24935
24936 @smallexample @c ada
24937 with Ada.Text_IO;
24938 with Ada.Exceptions;
24939
24940 procedure STB is
24941
24942    use Ada;
24943    use Ada.Exceptions;
24944
24945    procedure P1 is
24946       K : Positive := 1;
24947    begin
24948       K := K - 1;
24949    exception
24950       when E : others =>
24951          Text_IO.Put_Line (Exception_Information (E));
24952    end P1;
24953
24954    procedure P2 is
24955    begin
24956       P1;
24957    end P2;
24958
24959 begin
24960    P2;
24961 end STB;
24962 @end smallexample
24963
24964 @noindent
24965 This program will output:
24966
24967 @smallexample
24968 $ stb
24969
24970 Exception name: CONSTRAINT_ERROR
24971 Message: stb.adb:12
24972 Call stack traceback locations:
24973 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
24974 @end smallexample
24975
24976 @node Tracebacks From Anywhere in a Program (non-symbolic)
24977 @subsubsection Tracebacks From Anywhere in a Program
24978
24979 @noindent
24980 It is also possible to retrieve a stack traceback from anywhere in a
24981 program. For this you need to
24982 use the @code{GNAT.Traceback} API. This package includes a procedure called
24983 @code{Call_Chain} that computes a complete stack traceback, as well as useful
24984 display procedures described below. It is not necessary to use the
24985 @option{-E gnatbind} option in this case, because the stack traceback mechanism
24986 is invoked explicitly.
24987
24988 @noindent
24989 In the following example we compute a traceback at a specific location in
24990 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
24991 convert addresses to strings:
24992
24993 @smallexample @c ada
24994 with Ada.Text_IO;
24995 with GNAT.Traceback;
24996 with GNAT.Debug_Utilities;
24997
24998 procedure STB is
24999
25000    use Ada;
25001    use GNAT;
25002    use GNAT.Traceback;
25003
25004    procedure P1 is
25005       TB  : Tracebacks_Array (1 .. 10);
25006       --  We are asking for a maximum of 10 stack frames.
25007       Len : Natural;
25008       --  Len will receive the actual number of stack frames returned.
25009    begin
25010       Call_Chain (TB, Len);
25011
25012       Text_IO.Put ("In STB.P1 : ");
25013
25014       for K in 1 .. Len loop
25015          Text_IO.Put (Debug_Utilities.Image (TB (K)));
25016          Text_IO.Put (' ');
25017       end loop;
25018
25019       Text_IO.New_Line;
25020    end P1;
25021
25022    procedure P2 is
25023    begin
25024       P1;
25025    end P2;
25026
25027 begin
25028    P2;
25029 end STB;
25030 @end smallexample
25031
25032 @smallexample
25033 $ gnatmake -g stb
25034 $ stb
25035
25036 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
25037 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
25038 @end smallexample
25039
25040 @noindent
25041 You can then get further information by invoking the @code{addr2line}
25042 tool as described earlier (note that the hexadecimal addresses
25043 need to be specified in C format, with a leading ``0x'').
25044
25045 @node Symbolic Traceback
25046 @subsection Symbolic Traceback
25047 @cindex traceback, symbolic
25048
25049 @noindent
25050 A symbolic traceback is a stack traceback in which procedure names are
25051 associated with each code location.
25052
25053 @noindent
25054 Note that this feature is not supported on all platforms. See
25055 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
25056 list of currently supported platforms.
25057
25058 @noindent
25059 Note that the symbolic traceback requires that the program be compiled
25060 with debug information. If it is not compiled with debug information
25061 only the non-symbolic information will be valid.
25062
25063 @menu
25064 * Tracebacks From Exception Occurrences (symbolic)::
25065 * Tracebacks From Anywhere in a Program (symbolic)::
25066 @end menu
25067
25068 @node Tracebacks From Exception Occurrences (symbolic)
25069 @subsubsection Tracebacks From Exception Occurrences
25070
25071 @smallexample @c ada
25072 with Ada.Text_IO;
25073 with GNAT.Traceback.Symbolic;
25074
25075 procedure STB is
25076
25077    procedure P1 is
25078    begin
25079       raise Constraint_Error;
25080    end P1;
25081
25082    procedure P2 is
25083    begin
25084       P1;
25085    end P2;
25086
25087    procedure P3 is
25088    begin
25089       P2;
25090    end P3;
25091
25092 begin
25093    P3;
25094 exception
25095    when E : others =>
25096       Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
25097 end STB;
25098 @end smallexample
25099
25100 @smallexample
25101 $ gnatmake -g .\stb -bargs -E -largs -lgnat -laddr2line -lintl
25102 $ stb
25103
25104 0040149F in stb.p1 at stb.adb:8
25105 004014B7 in stb.p2 at stb.adb:13
25106 004014CF in stb.p3 at stb.adb:18
25107 004015DD in ada.stb at stb.adb:22
25108 00401461 in main at b~stb.adb:168
25109 004011C4 in __mingw_CRTStartup at crt1.c:200
25110 004011F1 in mainCRTStartup at crt1.c:222
25111 77E892A4 in ?? at ??:0
25112 @end smallexample
25113
25114 @noindent
25115 In the above example the ``.\'' syntax in the @command{gnatmake} command
25116 is currently required by @command{addr2line} for files that are in
25117 the current working directory.
25118 Moreover, the exact sequence of linker options may vary from platform
25119 to platform.
25120 The above @option{-largs} section is for Windows platforms. By contrast,
25121 under Unix there is no need for the @option{-largs} section.
25122 Differences across platforms are due to details of linker implementation.
25123
25124 @node Tracebacks From Anywhere in a Program (symbolic)
25125 @subsubsection Tracebacks From Anywhere in a Program
25126
25127 @noindent
25128 It is possible to get a symbolic stack traceback
25129 from anywhere in a program, just as for non-symbolic tracebacks.
25130 The first step is to obtain a non-symbolic
25131 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
25132 information. Here is an example:
25133
25134 @smallexample @c ada
25135 with Ada.Text_IO;
25136 with GNAT.Traceback;
25137 with GNAT.Traceback.Symbolic;
25138
25139 procedure STB is
25140
25141    use Ada;
25142    use GNAT.Traceback;
25143    use GNAT.Traceback.Symbolic;
25144
25145    procedure P1 is
25146       TB  : Tracebacks_Array (1 .. 10);
25147       --  We are asking for a maximum of 10 stack frames.
25148       Len : Natural;
25149       --  Len will receive the actual number of stack frames returned.
25150    begin
25151       Call_Chain (TB, Len);
25152       Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
25153    end P1;
25154
25155    procedure P2 is
25156    begin
25157       P1;
25158    end P2;
25159
25160 begin
25161    P2;
25162 end STB;
25163 @end smallexample
25164
25165 @c ******************************
25166 @ifset vms
25167 @node Compatibility with HP Ada
25168 @chapter Compatibility with HP Ada
25169 @cindex Compatibility
25170
25171 @noindent
25172 @cindex DEC Ada
25173 @cindex HP Ada
25174 @cindex Compatibility between GNAT and HP Ada
25175 This chapter compares HP Ada (formerly known as ``DEC Ada'')
25176 for OpenVMS Alpha and GNAT for OpenVMS for Alpha and for I64.
25177 GNAT is highly compatible
25178 with HP Ada, and it should generally be straightforward to port code
25179 from the HP Ada environment to GNAT. However, there are a few language
25180 and implementation differences of which the user must be aware. These
25181 differences are discussed in this chapter. In
25182 addition, the operating environment and command structure for the
25183 compiler are different, and these differences are also discussed.
25184
25185 For further details on these and other compatibility issues,
25186 see Appendix E of the HP publication
25187 @cite{HP Ada, Technical Overview and Comparison on HP Platforms}.
25188
25189 Except where otherwise indicated, the description of GNAT for OpenVMS
25190 applies to both the Alpha and I64 platforms.
25191
25192 For information on porting Ada code from GNAT on Alpha OpenVMS to GNAT on
25193 I64 OpenVMS, see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
25194
25195 The discussion in this chapter addresses specifically the implementation
25196 of Ada 83 for HP OpenVMS Alpha Systems. In cases where the implementation
25197 of HP Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems,
25198 GNAT always follows the Alpha implementation.
25199
25200 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
25201 attributes are recognized, although only a subset of them can sensibly
25202 be implemented.  The description of pragmas in
25203 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
25204 indicates whether or not they are applicable to non-VMS systems.
25205
25206 @menu
25207 * Ada Language Compatibility::
25208 * Differences in the Definition of Package System::
25209 * Language-Related Features::
25210 * The Package STANDARD::
25211 * The Package SYSTEM::
25212 * Tasking and Task-Related Features::
25213 * Pragmas and Pragma-Related Features::
25214 * Library of Predefined Units::
25215 * Bindings::
25216 * Main Program Definition::
25217 * Implementation-Defined Attributes::
25218 * Compiler and Run-Time Interfacing::
25219 * Program Compilation and Library Management::
25220 * Input-Output::
25221 * Implementation Limits::
25222 * Tools and Utilities::
25223 @end menu
25224
25225 @node Ada Language Compatibility
25226 @section Ada Language Compatibility
25227
25228 @noindent
25229 GNAT handles Ada 95 and Ada 2005 as well as Ada 83, whereas HP Ada is only
25230 for Ada 83. Ada 95 and Ada 2005 are almost completely upwards compatible
25231 with Ada 83, and therefore Ada 83 programs will compile
25232 and run under GNAT with
25233 no changes or only minor changes. The @cite{Annotated Ada Reference Manual}
25234 provides details on specific incompatibilities.
25235
25236 GNAT provides the switch @option{/83} on the @command{GNAT COMPILE} command,
25237 as well as the pragma @code{ADA_83}, to force the compiler to
25238 operate in Ada 83 mode. This mode does not guarantee complete
25239 conformance to Ada 83, but in practice is sufficient to
25240 eliminate most sources of incompatibilities.
25241 In particular, it eliminates the recognition of the
25242 additional Ada 95 and Ada 2005 keywords, so that their use as identifiers
25243 in Ada 83 programs is legal, and handles the cases of packages
25244 with optional bodies, and generics that instantiate unconstrained
25245 types without the use of @code{(<>)}.
25246
25247 @node Differences in the Definition of Package System
25248 @section Differences in the Definition of Package @code{System}
25249
25250 @noindent
25251 An Ada compiler is allowed to add
25252 implementation-dependent declarations to package @code{System}.
25253 In normal mode,
25254 GNAT does not take advantage of this permission, and the version of
25255 @code{System} provided by GNAT exactly matches that defined in the Ada
25256 Reference Manual.
25257
25258 However, HP Ada adds an extensive set of declarations to package
25259 @code{System},
25260 as fully documented in the HP Ada manuals. To minimize changes required
25261 for programs that make use of these extensions, GNAT provides the pragma
25262 @code{Extend_System} for extending the definition of package System. By using:
25263 @cindex pragma @code{Extend_System}
25264 @cindex @code{Extend_System} pragma
25265
25266 @smallexample @c ada
25267 @group
25268 @cartouche
25269 pragma Extend_System (Aux_DEC);
25270 @end cartouche
25271 @end group
25272 @end smallexample
25273
25274 @noindent
25275 the set of definitions in @code{System} is extended to include those in
25276 package @code{System.Aux_DEC}.
25277 @cindex @code{System.Aux_DEC} package
25278 @cindex @code{Aux_DEC} package (child of @code{System})
25279 These definitions are incorporated directly into package @code{System},
25280 as though they had been declared there. For a
25281 list of the declarations added, see the spec of this package,
25282 which can be found in the file @file{s-auxdec.ads} in the GNAT library.
25283 @cindex @file{s-auxdec.ads} file
25284 The pragma @code{Extend_System} is a configuration pragma, which means that
25285 it can be placed in the file @file{gnat.adc}, so that it will automatically
25286 apply to all subsequent compilations. See @ref{Configuration Pragmas},
25287 for further details.
25288
25289 An alternative approach that avoids the use of the non-standard
25290 @code{Extend_System} pragma is to add a context clause to the unit that
25291 references these facilities:
25292
25293 @smallexample @c ada
25294 @cartouche
25295 with System.Aux_DEC;
25296 use  System.Aux_DEC;
25297 @end cartouche
25298 @end smallexample
25299
25300 @noindent
25301 The effect is not quite semantically identical to incorporating
25302 the declarations directly into package @code{System},
25303 but most programs will not notice a difference
25304 unless they use prefix notation (e.g.@: @code{System.Integer_8})
25305 to reference the entities directly in package @code{System}.
25306 For units containing such references,
25307 the prefixes must either be removed, or the pragma @code{Extend_System}
25308 must be used.
25309
25310 @node Language-Related Features
25311 @section Language-Related Features
25312
25313 @noindent
25314 The following sections highlight differences in types,
25315 representations of types, operations, alignment, and
25316 related topics.
25317
25318 @menu
25319 * Integer Types and Representations::
25320 * Floating-Point Types and Representations::
25321 * Pragmas Float_Representation and Long_Float::
25322 * Fixed-Point Types and Representations::
25323 * Record and Array Component Alignment::
25324 * Address Clauses::
25325 * Other Representation Clauses::
25326 @end menu
25327
25328 @node Integer Types and Representations
25329 @subsection Integer Types and Representations
25330
25331 @noindent
25332 The set of predefined integer types is identical in HP Ada and GNAT.
25333 Furthermore the representation of these integer types is also identical,
25334 including the capability of size clauses forcing biased representation.
25335
25336 In addition,
25337 HP Ada for OpenVMS Alpha systems has defined the
25338 following additional integer types in package @code{System}:
25339
25340 @itemize @bullet
25341
25342 @item
25343 @code{INTEGER_8}
25344
25345 @item
25346 @code{INTEGER_16}
25347
25348 @item
25349 @code{INTEGER_32}
25350
25351 @item
25352 @code{INTEGER_64}
25353
25354 @item
25355 @code{LARGEST_INTEGER}
25356 @end itemize
25357
25358 @noindent
25359 In GNAT, the first four of these types may be obtained from the
25360 standard Ada package @code{Interfaces}.
25361 Alternatively, by use of the pragma @code{Extend_System}, identical
25362 declarations can be referenced directly in package @code{System}.
25363 On both GNAT and HP Ada, the maximum integer size is 64 bits.
25364
25365 @node Floating-Point Types and Representations
25366 @subsection Floating-Point Types and Representations
25367 @cindex Floating-Point types
25368
25369 @noindent
25370 The set of predefined floating-point types is identical in HP Ada and GNAT.
25371 Furthermore the representation of these floating-point
25372 types is also identical. One important difference is that the default
25373 representation for HP Ada is @code{VAX_Float}, but the default representation
25374 for GNAT is IEEE.
25375
25376 Specific types may be declared to be @code{VAX_Float} or IEEE, using the
25377 pragma @code{Float_Representation} as described in the HP Ada
25378 documentation.
25379 For example, the declarations:
25380
25381 @smallexample @c ada
25382 @cartouche
25383 type F_Float is digits 6;
25384 pragma Float_Representation (VAX_Float, F_Float);
25385 @end cartouche
25386 @end smallexample
25387
25388 @noindent
25389 declares a type @code{F_Float} that will be represented in @code{VAX_Float}
25390 format.
25391 This set of declarations actually appears in @code{System.Aux_DEC},
25392 which contains
25393 the full set of additional floating-point declarations provided in
25394 the HP Ada version of package @code{System}.
25395 This and similar declarations may be accessed in a user program
25396 by using pragma @code{Extend_System}. The use of this
25397 pragma, and the related pragma @code{Long_Float} is described in further
25398 detail in the following section.
25399
25400 @node Pragmas Float_Representation and Long_Float
25401 @subsection Pragmas @code{Float_Representation} and @code{Long_Float}
25402
25403 @noindent
25404 HP Ada provides the pragma @code{Float_Representation}, which
25405 acts as a program library switch to allow control over
25406 the internal representation chosen for the predefined
25407 floating-point types declared in the package @code{Standard}.
25408 The format of this pragma is as follows:
25409
25410 @smallexample @c ada
25411 @cartouche
25412 pragma Float_Representation(VAX_Float | IEEE_Float);
25413 @end cartouche
25414 @end smallexample
25415
25416 @noindent
25417 This pragma controls the representation of floating-point
25418 types as follows:
25419
25420 @itemize @bullet
25421 @item
25422 @code{VAX_Float} specifies that floating-point
25423 types are represented by default with the VAX system hardware types
25424 @code{F-floating}, @code{D-floating}, @code{G-floating}.
25425 Note that the @code{H-floating}
25426 type was available only on VAX systems, and is not available
25427 in either HP Ada or GNAT.
25428
25429 @item
25430 @code{IEEE_Float} specifies that floating-point
25431 types are represented by default with the IEEE single and
25432 double floating-point types.
25433 @end itemize
25434
25435 @noindent
25436 GNAT provides an identical implementation of the pragma
25437 @code{Float_Representation}, except that it functions as a
25438 configuration pragma. Note that the
25439 notion of configuration pragma corresponds closely to the
25440 HP Ada notion of a program library switch.
25441
25442 When no pragma is used in GNAT, the default is @code{IEEE_Float},
25443 which is different
25444 from HP Ada 83, where the default is @code{VAX_Float}. In addition, the
25445 predefined libraries in GNAT are built using @code{IEEE_Float}, so it is not
25446 advisable to change the format of numbers passed to standard library
25447 routines, and if necessary explicit type conversions may be needed.
25448
25449 The use of @code{IEEE_Float} is recommended in GNAT since it is more
25450 efficient, and (given that it conforms to an international standard)
25451 potentially more portable.
25452 The situation in which @code{VAX_Float} may be useful is in interfacing
25453 to existing code and data that expect the use of @code{VAX_Float}.
25454 In such a situation use the predefined @code{VAX_Float}
25455 types in package @code{System}, as extended by
25456 @code{Extend_System}. For example, use @code{System.F_Float}
25457 to specify the 32-bit @code{F-Float} format.
25458
25459 @noindent
25460 On OpenVMS systems, HP Ada provides the pragma @code{Long_Float}
25461 to allow control over the internal representation chosen
25462 for the predefined type @code{Long_Float} and for floating-point
25463 type declarations with digits specified in the range 7 .. 15.
25464 The format of this pragma is as follows:
25465
25466 @smallexample @c ada
25467 @cartouche
25468 pragma Long_Float (D_FLOAT | G_FLOAT);
25469 @end cartouche
25470 @end smallexample
25471
25472 @node Fixed-Point Types and Representations
25473 @subsection Fixed-Point Types and Representations
25474
25475 @noindent
25476 On HP Ada for OpenVMS Alpha systems, rounding is
25477 away from zero for both positive and negative numbers.
25478 Therefore, @code{+0.5} rounds to @code{1},
25479 and @code{-0.5} rounds to @code{-1}.
25480
25481 On GNAT the results of operations
25482 on fixed-point types are in accordance with the Ada
25483 rules. In particular, results of operations on decimal
25484 fixed-point types are truncated.
25485
25486 @node Record and Array Component Alignment
25487 @subsection Record and Array Component Alignment
25488
25489 @noindent
25490 On HP Ada for OpenVMS Alpha, all non-composite components
25491 are aligned on natural boundaries. For example, 1-byte
25492 components are aligned on byte boundaries, 2-byte
25493 components on 2-byte boundaries, 4-byte components on 4-byte
25494 byte boundaries, and so on. The OpenVMS Alpha hardware
25495 runs more efficiently with naturally aligned data.
25496
25497 On GNAT, alignment rules are compatible
25498 with HP Ada for OpenVMS Alpha.
25499
25500 @node Address Clauses
25501 @subsection Address Clauses
25502
25503 @noindent
25504 In HP Ada and GNAT, address clauses are supported for
25505 objects and imported subprograms.
25506 The predefined type @code{System.Address} is a private type
25507 in both compilers on Alpha OpenVMS, with the same representation
25508 (it is simply a machine pointer). Addition, subtraction, and comparison
25509 operations are available in the standard Ada package
25510 @code{System.Storage_Elements}, or in package @code{System}
25511 if it is extended to include @code{System.Aux_DEC} using a
25512 pragma @code{Extend_System} as previously described.
25513
25514 Note that code that @code{with}'s both this extended package @code{System}
25515 and the package @code{System.Storage_Elements} should not @code{use}
25516 both packages, or ambiguities will result. In general it is better
25517 not to mix these two sets of facilities. The Ada package was
25518 designed specifically to provide the kind of features that HP Ada
25519 adds directly to package @code{System}.
25520
25521 The type @code{System.Address} is a 64-bit integer type in GNAT for
25522 I64 OpenVMS.  For more information,
25523 see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
25524
25525 GNAT is compatible with HP Ada in its handling of address
25526 clauses, except for some limitations in
25527 the form of address clauses for composite objects with
25528 initialization. Such address clauses are easily replaced
25529 by the use of an explicitly-defined constant as described
25530 in the Ada Reference Manual (13.1(22)). For example, the sequence
25531 of declarations:
25532
25533 @smallexample @c ada
25534 @cartouche
25535 X, Y : Integer := Init_Func;
25536 Q : String (X .. Y) := "abc";
25537 @dots{}
25538 for Q'Address use Compute_Address;
25539 @end cartouche
25540 @end smallexample
25541
25542 @noindent
25543 will be rejected by GNAT, since the address cannot be computed at the time
25544 that @code{Q} is declared. To achieve the intended effect, write instead:
25545
25546 @smallexample @c ada
25547 @group
25548 @cartouche
25549 X, Y : Integer := Init_Func;
25550 Q_Address : constant Address := Compute_Address;
25551 Q : String (X .. Y) := "abc";
25552 @dots{}
25553 for Q'Address use Q_Address;
25554 @end cartouche
25555 @end group
25556 @end smallexample
25557
25558 @noindent
25559 which will be accepted by GNAT (and other Ada compilers), and is also
25560 compatible with Ada 83. A fuller description of the restrictions
25561 on address specifications is found in @ref{Top, GNAT Reference Manual,
25562 About This Guide, gnat_rm, GNAT Reference Manual}.
25563
25564 @node Other Representation Clauses
25565 @subsection Other Representation Clauses
25566
25567 @noindent
25568 GNAT implements in a compatible manner all the representation
25569 clauses supported by HP Ada. In addition, GNAT
25570 implements the representation clause forms that were introduced in Ada 95,
25571 including @code{COMPONENT_SIZE} and @code{SIZE} clauses for objects.
25572
25573 @node The Package STANDARD
25574 @section The Package @code{STANDARD}
25575
25576 @noindent
25577 The package @code{STANDARD}, as implemented by HP Ada, is fully
25578 described in the @cite{Ada Reference Manual} and in the
25579 @cite{HP Ada Language Reference Manual}. As implemented by GNAT, the
25580 package @code{STANDARD} is described in the @cite{Ada Reference Manual}.
25581
25582 In addition, HP Ada supports the Latin-1 character set in
25583 the type @code{CHARACTER}. GNAT supports the Latin-1 character set
25584 in the type @code{CHARACTER} and also Unicode (ISO 10646 BMP) in
25585 the type @code{WIDE_CHARACTER}.
25586
25587 The floating-point types supported by GNAT are those
25588 supported by HP Ada, but the defaults are different, and are controlled by
25589 pragmas. See @ref{Floating-Point Types and Representations}, for details.
25590
25591 @node The Package SYSTEM
25592 @section The Package @code{SYSTEM}
25593
25594 @noindent
25595 HP Ada provides a specific version of the package
25596 @code{SYSTEM} for each platform on which the language is implemented.
25597 For the complete spec of the package @code{SYSTEM}, see
25598 Appendix F of the @cite{HP Ada Language Reference Manual}.
25599
25600 On HP Ada, the package @code{SYSTEM} includes the following conversion
25601 functions:
25602 @itemize @bullet
25603 @item @code{TO_ADDRESS(INTEGER)}
25604
25605 @item @code{TO_ADDRESS(UNSIGNED_LONGWORD)}
25606
25607 @item @code{TO_ADDRESS(}@i{universal_integer}@code{)}
25608
25609 @item @code{TO_INTEGER(ADDRESS)}
25610
25611 @item @code{TO_UNSIGNED_LONGWORD(ADDRESS)}
25612
25613 @item Function @code{IMPORT_VALUE return UNSIGNED_LONGWORD} and the
25614 functions @code{IMPORT_ADDRESS} and @code{IMPORT_LARGEST_VALUE}
25615 @end itemize
25616
25617 @noindent
25618 By default, GNAT supplies a version of @code{SYSTEM} that matches
25619 the definition given in the @cite{Ada Reference Manual}.
25620 This
25621 is a subset of the HP system definitions, which is as
25622 close as possible to the original definitions. The only difference
25623 is that the definition of @code{SYSTEM_NAME} is different:
25624
25625 @smallexample @c ada
25626 @cartouche
25627 type Name is (SYSTEM_NAME_GNAT);
25628 System_Name : constant Name := SYSTEM_NAME_GNAT;
25629 @end cartouche
25630 @end smallexample
25631
25632 @noindent
25633 Also, GNAT adds the Ada declarations for
25634 @code{BIT_ORDER} and @code{DEFAULT_BIT_ORDER}.
25635
25636 However, the use of the following pragma causes GNAT
25637 to extend the definition of package @code{SYSTEM} so that it
25638 encompasses the full set of HP-specific extensions,
25639 including the functions listed above:
25640
25641 @smallexample @c ada
25642 @cartouche
25643 pragma Extend_System (Aux_DEC);
25644 @end cartouche
25645 @end smallexample
25646
25647 @noindent
25648 The pragma @code{Extend_System} is a configuration pragma that
25649 is most conveniently placed in the @file{gnat.adc} file. @xref{Pragma
25650 Extend_System,,, gnat_rm, GNAT Reference Manual}, for further details.
25651
25652 HP Ada does not allow the recompilation of the package
25653 @code{SYSTEM}. Instead HP Ada provides several pragmas
25654 (@code{SYSTEM_NAME}, @code{STORAGE_UNIT}, and @code{MEMORY_SIZE})
25655 to modify values in the package @code{SYSTEM}.
25656 On OpenVMS Alpha systems, the pragma
25657 @code{SYSTEM_NAME} takes the enumeration literal @code{OPENVMS_AXP} as
25658 its single argument.
25659
25660 GNAT does permit the recompilation of package @code{SYSTEM} using
25661 the special switch @option{-gnatg}, and this switch can be used if
25662 it is necessary to modify the definitions in @code{SYSTEM}. GNAT does
25663 not permit the specification of @code{SYSTEM_NAME}, @code{STORAGE_UNIT}
25664 or @code{MEMORY_SIZE} by any other means.
25665
25666 On GNAT systems, the pragma @code{SYSTEM_NAME} takes the
25667 enumeration literal @code{SYSTEM_NAME_GNAT}.
25668
25669 The definitions provided by the use of
25670
25671 @smallexample @c ada
25672 pragma Extend_System (AUX_Dec);
25673 @end smallexample
25674
25675 @noindent
25676 are virtually identical to those provided by the HP Ada 83 package
25677 @code{SYSTEM}. One important difference is that the name of the
25678 @code{TO_ADDRESS}
25679 function for type @code{UNSIGNED_LONGWORD} is changed to
25680 @code{TO_ADDRESS_LONG}.
25681 @xref{Address Clauses,,, gnat_rm, GNAT Reference Manual}, for a
25682 discussion of why this change was necessary.
25683
25684 @noindent
25685 The version of @code{TO_ADDRESS} taking a @i{universal_integer} argument
25686 is in fact
25687 an extension to Ada 83 not strictly compatible with the reference manual.
25688 GNAT, in order to be exactly compatible with the standard,
25689 does not provide this capability. In HP Ada 83, the
25690 point of this definition is to deal with a call like:
25691
25692 @smallexample @c ada
25693 TO_ADDRESS (16#12777#);
25694 @end smallexample
25695
25696 @noindent
25697 Normally, according to Ada 83 semantics, one would expect this to be
25698 ambiguous, since it matches both the @code{INTEGER} and
25699 @code{UNSIGNED_LONGWORD} forms of @code{TO_ADDRESS}.
25700 However, in HP Ada 83, there is no ambiguity, since the
25701 definition using @i{universal_integer} takes precedence.
25702
25703 In GNAT, since the version with @i{universal_integer} cannot be supplied,
25704 it is
25705 not possible to be 100% compatible. Since there are many programs using
25706 numeric constants for the argument to @code{TO_ADDRESS}, the decision in
25707 GNAT was
25708 to change the name of the function in the @code{UNSIGNED_LONGWORD} case,
25709 so the declarations provided in the GNAT version of @code{AUX_Dec} are:
25710
25711 @smallexample @c ada
25712 function To_Address (X : Integer) return Address;
25713 pragma Pure_Function (To_Address);
25714
25715 function To_Address_Long (X : Unsigned_Longword) return Address;
25716 pragma Pure_Function (To_Address_Long);
25717 @end smallexample
25718
25719 @noindent
25720 This means that programs using @code{TO_ADDRESS} for
25721 @code{UNSIGNED_LONGWORD} must change the name to @code{TO_ADDRESS_LONG}.
25722
25723 @node Tasking and Task-Related Features
25724 @section Tasking and Task-Related Features
25725
25726 @noindent
25727 This section compares the treatment of tasking in GNAT
25728 and in HP Ada for OpenVMS Alpha.
25729 The GNAT description applies to both Alpha and I64 OpenVMS.
25730 For detailed information on tasking in
25731 HP Ada, see the @cite{HP Ada Language Reference Manual} and the
25732 relevant run-time reference manual.
25733
25734 @menu
25735 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
25736 * Assigning Task IDs::
25737 * Task IDs and Delays::
25738 * Task-Related Pragmas::
25739 * Scheduling and Task Priority::
25740 * The Task Stack::
25741 * External Interrupts::
25742 @end menu
25743
25744 @node Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
25745 @subsection Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
25746
25747 @noindent
25748 On OpenVMS Alpha systems, each Ada task (except a passive
25749 task) is implemented as a single stream of execution
25750 that is created and managed by the kernel. On these
25751 systems, HP Ada tasking support is based on DECthreads,
25752 an implementation of the POSIX standard for threads.
25753
25754 Also, on OpenVMS Alpha systems, HP Ada tasks and foreign
25755 code that calls DECthreads routines can be used together.
25756 The interaction between Ada tasks and DECthreads routines
25757 can have some benefits. For example when on OpenVMS Alpha,
25758 HP Ada can call C code that is already threaded.
25759
25760 GNAT uses the facilities of DECthreads,
25761 and Ada tasks are mapped to threads.
25762
25763 @node Assigning Task IDs
25764 @subsection Assigning Task IDs
25765
25766 @noindent
25767 The HP Ada Run-Time Library always assigns @code{%TASK 1} to
25768 the environment task that executes the main program. On
25769 OpenVMS Alpha systems, @code{%TASK 0} is often used for tasks
25770 that have been created but are not yet activated.
25771
25772 On OpenVMS Alpha systems, task IDs are assigned at
25773 activation. On GNAT systems, task IDs are also assigned at
25774 task creation but do not have the same form or values as
25775 task ID values in HP Ada. There is no null task, and the
25776 environment task does not have a specific task ID value.
25777
25778 @node Task IDs and Delays
25779 @subsection Task IDs and Delays
25780
25781 @noindent
25782 On OpenVMS Alpha systems, tasking delays are implemented
25783 using Timer System Services. The Task ID is used for the
25784 identification of the timer request (the @code{REQIDT} parameter).
25785 If Timers are used in the application take care not to use
25786 @code{0} for the identification, because cancelling such a timer
25787 will cancel all timers and may lead to unpredictable results.
25788
25789 @node Task-Related Pragmas
25790 @subsection Task-Related Pragmas
25791
25792 @noindent
25793 Ada supplies the pragma @code{TASK_STORAGE}, which allows
25794 specification of the size of the guard area for a task
25795 stack. (The guard area forms an area of memory that has no
25796 read or write access and thus helps in the detection of
25797 stack overflow.) On OpenVMS Alpha systems, if the pragma
25798 @code{TASK_STORAGE} specifies a value of zero, a minimal guard
25799 area is created. In the absence of a pragma @code{TASK_STORAGE},
25800 a default guard area is created.
25801
25802 GNAT supplies the following task-related pragmas:
25803
25804 @itemize @bullet
25805 @item  @code{TASK_INFO}
25806
25807 This pragma appears within a task definition and
25808 applies to the task in which it appears. The argument
25809 must be of type @code{SYSTEM.TASK_INFO.TASK_INFO_TYPE}.
25810
25811 @item  @code{TASK_STORAGE}
25812
25813 GNAT implements pragma @code{TASK_STORAGE} in the same way as HP Ada.
25814 Both HP Ada and GNAT supply the pragmas @code{PASSIVE},
25815 @code{SUPPRESS}, and @code{VOLATILE}.
25816 @end itemize
25817 @node Scheduling and Task Priority
25818 @subsection Scheduling and Task Priority
25819
25820 @noindent
25821 HP Ada implements the Ada language requirement that
25822 when two tasks are eligible for execution and they have
25823 different priorities, the lower priority task does not
25824 execute while the higher priority task is waiting. The HP
25825 Ada Run-Time Library keeps a task running until either the
25826 task is suspended or a higher priority task becomes ready.
25827
25828 On OpenVMS Alpha systems, the default strategy is round-
25829 robin with preemption. Tasks of equal priority take turns
25830 at the processor. A task is run for a certain period of
25831 time and then placed at the tail of the ready queue for
25832 its priority level.
25833
25834 HP Ada provides the implementation-defined pragma @code{TIME_SLICE},
25835 which can be used to enable or disable round-robin
25836 scheduling of tasks with the same priority.
25837 See the relevant HP Ada run-time reference manual for
25838 information on using the pragmas to control HP Ada task
25839 scheduling.
25840
25841 GNAT follows the scheduling rules of Annex D (Real-Time
25842 Annex) of the @cite{Ada Reference Manual}. In general, this
25843 scheduling strategy is fully compatible with HP Ada
25844 although it provides some additional constraints (as
25845 fully documented in Annex D).
25846 GNAT implements time slicing control in a manner compatible with
25847 HP Ada 83, by means of the pragma @code{Time_Slice}, whose semantics
25848 are identical to the HP Ada 83 pragma of the same name.
25849 Note that it is not possible to mix GNAT tasking and
25850 HP Ada 83 tasking in the same program, since the two run-time
25851 libraries are not compatible.
25852
25853 @node The Task Stack
25854 @subsection The Task Stack
25855
25856 @noindent
25857 In HP Ada, a task stack is allocated each time a
25858 non-passive task is activated. As soon as the task is
25859 terminated, the storage for the task stack is deallocated.
25860 If you specify a size of zero (bytes) with @code{T'STORAGE_SIZE},
25861 a default stack size is used. Also, regardless of the size
25862 specified, some additional space is allocated for task
25863 management purposes. On OpenVMS Alpha systems, at least
25864 one page is allocated.
25865
25866 GNAT handles task stacks in a similar manner. In accordance with
25867 the Ada rules, it provides the pragma @code{STORAGE_SIZE} as
25868 an alternative method for controlling the task stack size.
25869 The specification of the attribute @code{T'STORAGE_SIZE} is also
25870 supported in a manner compatible with HP Ada.
25871
25872 @node External Interrupts
25873 @subsection External Interrupts
25874
25875 @noindent
25876 On HP Ada, external interrupts can be associated with task entries.
25877 GNAT is compatible with HP Ada in its handling of external interrupts.
25878
25879 @node Pragmas and Pragma-Related Features
25880 @section Pragmas and Pragma-Related Features
25881
25882 @noindent
25883 Both HP Ada and GNAT supply all language-defined pragmas
25884 as specified by the Ada 83 standard. GNAT also supplies all
25885 language-defined pragmas introduced by Ada 95 and Ada 2005.
25886 In addition, GNAT implements the implementation-defined pragmas
25887 from HP Ada 83.
25888
25889 @itemize @bullet
25890 @item  @code{AST_ENTRY}
25891
25892 @item  @code{COMMON_OBJECT}
25893
25894 @item  @code{COMPONENT_ALIGNMENT}
25895
25896 @item  @code{EXPORT_EXCEPTION}
25897
25898 @item  @code{EXPORT_FUNCTION}
25899
25900 @item  @code{EXPORT_OBJECT}
25901
25902 @item  @code{EXPORT_PROCEDURE}
25903
25904 @item  @code{EXPORT_VALUED_PROCEDURE}
25905
25906 @item  @code{FLOAT_REPRESENTATION}
25907
25908 @item  @code{IDENT}
25909
25910 @item  @code{IMPORT_EXCEPTION}
25911
25912 @item  @code{IMPORT_FUNCTION}
25913
25914 @item  @code{IMPORT_OBJECT}
25915
25916 @item  @code{IMPORT_PROCEDURE}
25917
25918 @item  @code{IMPORT_VALUED_PROCEDURE}
25919
25920 @item  @code{INLINE_GENERIC}
25921
25922 @item  @code{INTERFACE_NAME}
25923
25924 @item  @code{LONG_FLOAT}
25925
25926 @item  @code{MAIN_STORAGE}
25927
25928 @item  @code{PASSIVE}
25929
25930 @item  @code{PSECT_OBJECT}
25931
25932 @item  @code{SHARE_GENERIC}
25933
25934 @item  @code{SUPPRESS_ALL}
25935
25936 @item  @code{TASK_STORAGE}
25937
25938 @item  @code{TIME_SLICE}
25939
25940 @item  @code{TITLE}
25941 @end itemize
25942
25943 @noindent
25944 These pragmas are all fully implemented, with the exception of @code{TITLE},
25945 @code{PASSIVE}, and @code{SHARE_GENERIC}, which are
25946 recognized, but which have no
25947 effect in GNAT. The effect of @code{PASSIVE} may be obtained by the
25948 use of Ada protected objects. In GNAT, all generics are inlined.
25949
25950 Unlike HP Ada, the GNAT ``@code{EXPORT_}@i{subprogram}'' pragmas require
25951 a separate subprogram specification which must appear before the
25952 subprogram body.
25953
25954 GNAT also supplies a number of implementation-defined pragmas as follows:
25955 @itemize @bullet
25956 @item  @code{ABORT_DEFER}
25957
25958 @item  @code{ADA_83}
25959
25960 @item  @code{ADA_95}
25961
25962 @item  @code{ADA_05}
25963
25964 @item  @code{ANNOTATE}
25965
25966 @item  @code{ASSERT}
25967
25968 @item  @code{C_PASS_BY_COPY}
25969
25970 @item  @code{CPP_CLASS}
25971
25972 @item  @code{CPP_CONSTRUCTOR}
25973
25974 @item  @code{CPP_DESTRUCTOR}
25975
25976 @item  @code{DEBUG}
25977
25978 @item  @code{EXTEND_SYSTEM}
25979
25980 @item  @code{LINKER_ALIAS}
25981
25982 @item  @code{LINKER_SECTION}
25983
25984 @item  @code{MACHINE_ATTRIBUTE}
25985
25986 @item  @code{NO_RETURN}
25987
25988 @item  @code{PURE_FUNCTION}
25989
25990 @item  @code{SOURCE_FILE_NAME}
25991
25992 @item  @code{SOURCE_REFERENCE}
25993
25994 @item  @code{TASK_INFO}
25995
25996 @item  @code{UNCHECKED_UNION}
25997
25998 @item  @code{UNIMPLEMENTED_UNIT}
25999
26000 @item  @code{UNIVERSAL_DATA}
26001
26002 @item  @code{UNSUPPRESS}
26003
26004 @item  @code{WARNINGS}
26005
26006 @item  @code{WEAK_EXTERNAL}
26007 @end itemize
26008
26009 @noindent
26010 For full details on these GNAT implementation-defined pragmas,
26011 see @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference
26012 Manual}.
26013
26014 @menu
26015 * Restrictions on the Pragma INLINE::
26016 * Restrictions on the Pragma INTERFACE::
26017 * Restrictions on the Pragma SYSTEM_NAME::
26018 @end menu
26019
26020 @node Restrictions on the Pragma INLINE
26021 @subsection Restrictions on Pragma @code{INLINE}
26022
26023 @noindent
26024 HP Ada enforces the following restrictions on the pragma @code{INLINE}:
26025 @itemize @bullet
26026 @item  Parameters cannot have a task type.
26027
26028 @item  Function results cannot be task types, unconstrained
26029 array types, or unconstrained types with discriminants.
26030
26031 @item  Bodies cannot declare the following:
26032 @itemize @bullet
26033 @item  Subprogram body or stub (imported subprogram is allowed)
26034
26035 @item  Tasks
26036
26037 @item  Generic declarations
26038
26039 @item  Instantiations
26040
26041 @item  Exceptions
26042
26043 @item  Access types (types derived from access types allowed)
26044
26045 @item  Array or record types
26046
26047 @item  Dependent tasks
26048
26049 @item  Direct recursive calls of subprogram or containing
26050 subprogram, directly or via a renaming
26051
26052 @end itemize
26053 @end itemize
26054
26055 @noindent
26056 In GNAT, the only restriction on pragma @code{INLINE} is that the
26057 body must occur before the call if both are in the same
26058 unit, and the size must be appropriately small. There are
26059 no other specific restrictions which cause subprograms to
26060 be incapable of being inlined.
26061
26062 @node  Restrictions on the Pragma INTERFACE
26063 @subsection  Restrictions on Pragma @code{INTERFACE}
26064
26065 @noindent
26066 The following restrictions on pragma @code{INTERFACE}
26067 are enforced by both HP Ada and GNAT:
26068 @itemize @bullet
26069 @item  Languages accepted: Ada, Bliss, C, Fortran, Default.
26070 Default is the default on OpenVMS Alpha systems.
26071
26072 @item  Parameter passing: Language specifies default
26073 mechanisms but can be overridden with an @code{EXPORT} pragma.
26074
26075 @itemize @bullet
26076 @item  Ada: Use internal Ada rules.
26077
26078 @item  Bliss, C: Parameters must be mode @code{in}; cannot be
26079 record or task type. Result cannot be a string, an
26080 array, or a record.
26081
26082 @item  Fortran: Parameters cannot have a task type. Result cannot
26083 be a string, an array, or a record.
26084 @end itemize
26085 @end itemize
26086
26087 @noindent
26088 GNAT is entirely upwards compatible with HP Ada, and in addition allows
26089 record parameters for all languages.
26090
26091 @node  Restrictions on the Pragma SYSTEM_NAME
26092 @subsection  Restrictions on Pragma @code{SYSTEM_NAME}
26093
26094 @noindent
26095 For HP Ada for OpenVMS Alpha, the enumeration literal
26096 for the type @code{NAME} is @code{OPENVMS_AXP}.
26097 In GNAT, the enumeration
26098 literal for the type @code{NAME} is @code{SYSTEM_NAME_GNAT}.
26099
26100 @node  Library of Predefined Units
26101 @section  Library of Predefined Units
26102
26103 @noindent
26104 A library of predefined units is provided as part of the
26105 HP Ada and GNAT implementations. HP Ada does not provide
26106 the package @code{MACHINE_CODE} but instead recommends importing
26107 assembler code.
26108
26109 The GNAT versions of the HP Ada Run-Time Library (@code{ADA$PREDEFINED:})
26110 units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
26111 version.
26112 The HP Ada Predefined Library units are modified to remove post-Ada 83
26113 incompatibilities and to make them interoperable with GNAT
26114 (@pxref{Changes to DECLIB}, for details).
26115 The units are located in the @file{DECLIB} directory.
26116
26117 The GNAT RTL is contained in
26118 the @file{ADALIB} directory, and
26119 the default search path is set up to find @code{DECLIB} units in preference
26120 to @code{ADALIB} units with the same name (@code{TEXT_IO},
26121 @code{SEQUENTIAL_IO}, and @code{DIRECT_IO}, for example).
26122
26123 @menu
26124 * Changes to DECLIB::
26125 @end menu
26126
26127 @node Changes to DECLIB
26128 @subsection Changes to @code{DECLIB}
26129
26130 @noindent
26131 The changes made to the HP Ada predefined library for GNAT and post-Ada 83
26132 compatibility are minor and include the following:
26133
26134 @itemize @bullet
26135 @item  Adjusting the location of pragmas and record representation
26136 clauses to obey Ada 95 (and thus Ada 2005) rules
26137
26138 @item  Adding the proper notation to generic formal parameters
26139 that take unconstrained types in instantiation
26140
26141 @item  Adding pragma @code{ELABORATE_BODY} to package specs
26142 that have package bodies not otherwise allowed
26143
26144 @item  Replacing occurrences of the identifier ``@code{PROTECTED}'' by
26145 ``@code{PROTECTD}''.
26146 Currently these are found only in the @code{STARLET} package spec.
26147
26148 @item Changing @code{SYSTEM.ADDRESS} to @code{SYSTEM.SHORT_ADDRESS}
26149 where the address size is constrained to 32 bits.
26150 @end itemize
26151
26152 @noindent
26153 None of the above changes is visible to users.
26154
26155 @node Bindings
26156 @section Bindings
26157
26158 @noindent
26159 On OpenVMS Alpha, HP Ada provides the following strongly-typed bindings:
26160 @itemize @bullet
26161
26162 @item  Command Language Interpreter (CLI interface)
26163
26164 @item  DECtalk Run-Time Library (DTK interface)
26165
26166 @item  Librarian utility routines (LBR interface)
26167
26168 @item  General Purpose Run-Time Library (LIB interface)
26169
26170 @item  Math Run-Time Library (MTH interface)
26171
26172 @item  National Character Set Run-Time Library (NCS interface)
26173
26174 @item  Compiled Code Support Run-Time Library (OTS interface)
26175
26176 @item  Parallel Processing Run-Time Library (PPL interface)
26177
26178 @item  Screen Management Run-Time Library (SMG interface)
26179
26180 @item  Sort Run-Time Library (SOR interface)
26181
26182 @item  String Run-Time Library (STR interface)
26183
26184 @item STARLET System Library
26185 @findex Starlet
26186
26187 @item  X Window System Version 11R4 and 11R5 (X, XLIB interface)
26188
26189 @item  X Windows Toolkit (XT interface)
26190
26191 @item  X/Motif Version 1.1.3 and 1.2 (XM interface)
26192 @end itemize
26193
26194 @noindent
26195 GNAT provides implementations of these HP bindings in the @code{DECLIB}
26196 directory, on both the Alpha and I64 OpenVMS platforms.
26197
26198 The X/Motif bindings used to build @code{DECLIB} are whatever versions are
26199 in the
26200 HP Ada @file{ADA$PREDEFINED} directory with extension @file{.ADC}.
26201 A pragma @code{Linker_Options} has been added to packages @code{Xm},
26202 @code{Xt}, and @code{X_Lib}
26203 causing the default X/Motif sharable image libraries to be linked in. This
26204 is done via options files named @file{xm.opt}, @file{xt.opt}, and
26205 @file{x_lib.opt} (also located in the @file{DECLIB} directory).
26206
26207 It may be necessary to edit these options files to update or correct the
26208 library names if, for example, the newer X/Motif bindings from
26209 @file{ADA$EXAMPLES}
26210 had been (previous to installing GNAT) copied and renamed to supersede the
26211 default @file{ADA$PREDEFINED} versions.
26212
26213 @menu
26214 * Shared Libraries and Options Files::
26215 * Interfaces to C::
26216 @end menu
26217
26218 @node Shared Libraries and Options Files
26219 @subsection Shared Libraries and Options Files
26220
26221 @noindent
26222 When using the HP Ada
26223 predefined X and Motif bindings, the linking with their sharable images is
26224 done automatically by @command{GNAT LINK}.
26225 When using other X and Motif bindings, you need
26226 to add the corresponding sharable images to the command line for
26227 @code{GNAT LINK}. When linking with shared libraries, or with
26228 @file{.OPT} files, you must
26229 also add them to the command line for @command{GNAT LINK}.
26230
26231 A shared library to be used with GNAT is built in the same way as other
26232 libraries under VMS. The VMS Link command can be used in standard fashion.
26233
26234 @node Interfaces to C
26235 @subsection Interfaces to C
26236
26237 @noindent
26238 HP Ada
26239 provides the following Ada types and operations:
26240
26241 @itemize @bullet
26242 @item C types package (@code{C_TYPES})
26243
26244 @item C strings (@code{C_TYPES.NULL_TERMINATED})
26245
26246 @item Other_types (@code{SHORT_INT})
26247 @end itemize
26248
26249 @noindent
26250 Interfacing to C with GNAT, you can use the above approach
26251 described for HP Ada or the facilities of Annex B of
26252 the @cite{Ada Reference Manual} (packages @code{INTERFACES.C},
26253 @code{INTERFACES.C.STRINGS} and @code{INTERFACES.C.POINTERS}). For more
26254 information, see @ref{Interfacing to C,,, gnat_rm, GNAT Reference Manual}.
26255
26256 The @option{-gnatF} qualifier forces default and explicit
26257 @code{External_Name} parameters in pragmas @code{Import} and @code{Export}
26258 to be uppercased for compatibility with the default behavior
26259 of HP C. The qualifier has no effect on @code{Link_Name} parameters.
26260
26261 @node Main Program Definition
26262 @section Main Program Definition
26263
26264 @noindent
26265 The following section discusses differences in the
26266 definition of main programs on HP Ada and GNAT.
26267 On HP Ada, main programs are defined to meet the
26268 following conditions:
26269 @itemize @bullet
26270 @item  Procedure with no formal parameters (returns @code{0} upon
26271 normal completion)
26272
26273 @item  Procedure with no formal parameters (returns @code{42} when
26274 an unhandled exception is raised)
26275
26276 @item  Function with no formal parameters whose returned value
26277 is of a discrete type
26278
26279 @item  Procedure with one @code{out} formal of a discrete type for
26280 which a specification of pragma @code{EXPORT_VALUED_PROCEDURE} is given.
26281
26282 @end itemize
26283
26284 @noindent
26285 When declared with the pragma @code{EXPORT_VALUED_PROCEDURE},
26286 a main function or main procedure returns a discrete
26287 value whose size is less than 64 bits (32 on VAX systems),
26288 the value is zero- or sign-extended as appropriate.
26289 On GNAT, main programs are defined as follows:
26290 @itemize @bullet
26291 @item  Must be a non-generic, parameterless subprogram that
26292 is either a procedure or function returning an Ada
26293 @code{STANDARD.INTEGER} (the predefined type)
26294
26295 @item  Cannot be a generic subprogram or an instantiation of a
26296 generic subprogram
26297 @end itemize
26298
26299 @node Implementation-Defined Attributes
26300 @section Implementation-Defined Attributes
26301
26302 @noindent
26303 GNAT provides all HP Ada implementation-defined
26304 attributes.
26305
26306 @node Compiler and Run-Time Interfacing
26307 @section Compiler and Run-Time Interfacing
26308
26309 @noindent
26310 HP Ada provides the following qualifiers to pass options to the linker
26311 (ACS LINK):
26312 @itemize @bullet
26313 @item  @option{/WAIT} and @option{/SUBMIT}
26314
26315 @item  @option{/COMMAND}
26316
26317 @item  @option{/@r{[}NO@r{]}MAP}
26318
26319 @item  @option{/OUTPUT=@var{file-spec}}
26320
26321 @item  @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
26322 @end itemize
26323
26324 @noindent
26325 To pass options to the linker, GNAT provides the following
26326 switches:
26327
26328 @itemize @bullet
26329 @item   @option{/EXECUTABLE=@var{exec-name}}
26330
26331 @item   @option{/VERBOSE}
26332
26333 @item   @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
26334 @end itemize
26335
26336 @noindent
26337 For more information on these switches, see
26338 @ref{Switches for gnatlink}.
26339 In HP Ada, the command-line switch @option{/OPTIMIZE} is available
26340 to control optimization. HP Ada also supplies the
26341 following pragmas:
26342 @itemize @bullet
26343 @item  @code{OPTIMIZE}
26344
26345 @item  @code{INLINE}
26346
26347 @item  @code{INLINE_GENERIC}
26348
26349 @item  @code{SUPPRESS_ALL}
26350
26351 @item  @code{PASSIVE}
26352 @end itemize
26353
26354 @noindent
26355 In GNAT, optimization is controlled strictly by command
26356 line parameters, as described in the corresponding section of this guide.
26357 The HP pragmas for control of optimization are
26358 recognized but ignored.
26359
26360 Note that in GNAT, the default is optimization off, whereas in HP Ada
26361 the default is that optimization is turned on.
26362
26363 @node Program Compilation and Library Management
26364 @section Program Compilation and Library Management
26365
26366 @noindent
26367 HP Ada and GNAT provide a comparable set of commands to
26368 build programs. HP Ada also provides a program library,
26369 which is a concept that does not exist on GNAT. Instead,
26370 GNAT provides directories of sources that are compiled as
26371 needed.
26372
26373 The following table summarizes
26374 the HP Ada commands and provides
26375 equivalent GNAT commands. In this table, some GNAT
26376 equivalents reflect the fact that GNAT does not use the
26377 concept of a program library. Instead, it uses a model
26378 in which collections of source and object files are used
26379 in a manner consistent with other languages like C and
26380 Fortran. Therefore, standard system file commands are used
26381 to manipulate these elements. Those GNAT commands are marked with
26382 an asterisk.
26383 Note that, unlike HP Ada, none of the GNAT commands accepts wild cards.
26384
26385 @need 1500
26386 @multitable @columnfractions .35 .65
26387
26388 @item @emph{HP Ada Command}
26389 @tab @emph{GNAT Equivalent / Description}
26390
26391 @item @command{ADA}
26392 @tab @command{GNAT COMPILE}@*
26393 Invokes the compiler to compile one or more Ada source files.
26394
26395 @item @command{ACS ATTACH}@*
26396 @tab [No equivalent]@*
26397 Switches control of terminal from current process running the program
26398 library manager.
26399
26400 @item @command{ACS CHECK}
26401 @tab @command{GNAT MAKE /DEPENDENCY_LIST}@*
26402 Forms the execution closure of one
26403 or more compiled units and checks completeness and currency.
26404
26405 @item @command{ACS COMPILE}
26406 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
26407 Forms the execution closure of one or
26408 more specified units, checks completeness and currency,
26409 identifies units that have revised source files, compiles same,
26410 and recompiles units that are or will become obsolete.
26411 Also completes incomplete generic instantiations.
26412
26413 @item @command{ACS COPY FOREIGN}
26414 @tab Copy (*)@*
26415 Copies a foreign object file into the program library as a
26416 library unit body.
26417
26418 @item @command{ACS COPY UNIT}
26419 @tab Copy (*)@*
26420 Copies a compiled unit from one program library to another.
26421
26422 @item @command{ACS CREATE LIBRARY}
26423 @tab Create /directory (*)@*
26424 Creates a program library.
26425
26426 @item @command{ACS CREATE SUBLIBRARY}
26427 @tab Create /directory (*)@*
26428 Creates a program sublibrary.
26429
26430 @item @command{ACS DELETE LIBRARY}
26431 @tab @*
26432 Deletes a program library and its contents.
26433
26434 @item @command{ACS DELETE SUBLIBRARY}
26435 @tab @*
26436 Deletes a program sublibrary and its contents.
26437
26438 @item @command{ACS DELETE UNIT}
26439 @tab Delete file (*)@*
26440 On OpenVMS systems, deletes one or more compiled units from
26441 the current program library.
26442
26443 @item @command{ACS DIRECTORY}
26444 @tab Directory (*)@*
26445 On OpenVMS systems, lists units contained in the current
26446 program library.
26447
26448 @item @command{ACS ENTER FOREIGN}
26449 @tab Copy (*)@*
26450 Allows the import of a foreign body as an Ada library
26451 spec and enters a reference to a pointer.
26452
26453 @item @command{ACS ENTER UNIT}
26454 @tab Copy (*)@*
26455 Enters a reference (pointer) from the current program library to
26456 a unit compiled into another program library.
26457
26458 @item @command{ACS EXIT}
26459 @tab [No equivalent]@*
26460 Exits from the program library manager.
26461
26462 @item @command{ACS EXPORT}
26463 @tab Copy (*)@*
26464 Creates an object file that contains system-specific object code
26465 for one or more units. With GNAT, object files can simply be copied
26466 into the desired directory.
26467
26468 @item @command{ACS EXTRACT SOURCE}
26469 @tab Copy (*)@*
26470 Allows access to the copied source file for each Ada compilation unit
26471
26472 @item @command{ACS HELP}
26473 @tab @command{HELP GNAT}@*
26474 Provides online help.
26475
26476 @item @command{ACS LINK}
26477 @tab @command{GNAT LINK}@*
26478 Links an object file containing Ada units into an executable file.
26479
26480 @item @command{ACS LOAD}
26481 @tab Copy (*)@*
26482 Loads (partially compiles) Ada units into the program library.
26483 Allows loading a program from a collection of files into a library
26484 without knowing the relationship among units.
26485
26486 @item @command{ACS MERGE}
26487 @tab Copy (*)@*
26488 Merges into the current program library, one or more units from
26489 another library where they were modified.
26490
26491 @item @command{ACS RECOMPILE}
26492 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
26493 Recompiles from   external or copied source files any obsolete
26494 unit in the closure. Also, completes any incomplete generic
26495 instantiations.
26496
26497 @item @command{ACS REENTER}
26498 @tab @command{GNAT MAKE}@*
26499 Reenters current references to units compiled after last entered
26500 with the @command{ACS ENTER UNIT} command.
26501
26502 @item @command{ACS SET LIBRARY}
26503 @tab Set default (*)@*
26504 Defines a program library to be the compilation context as well
26505 as the target library for compiler output and commands in general.
26506
26507 @item @command{ACS SET PRAGMA}
26508 @tab Edit @file{gnat.adc} (*)@*
26509 Redefines specified  values of the library characteristics
26510 @code{LONG_ FLOAT}, @code{MEMORY_SIZE}, @code{SYSTEM_NAME},
26511 and @code{Float_Representation}.
26512
26513 @item @command{ACS SET SOURCE}
26514 @tab Define @code{ADA_INCLUDE_PATH} path (*)@*
26515 Defines the source file search list for the @command{ACS COMPILE} command.
26516
26517 @item @command{ACS SHOW LIBRARY}
26518 @tab Directory (*)@*
26519 Lists information about one or more program libraries.
26520
26521 @item @command{ACS SHOW PROGRAM}
26522 @tab [No equivalent]@*
26523 Lists information about the execution closure of one or
26524 more units in the program library.
26525
26526 @item @command{ACS SHOW SOURCE}
26527 @tab Show logical @code{ADA_INCLUDE_PATH}@*
26528 Shows the source file search used when compiling units.
26529
26530 @item @command{ACS SHOW VERSION}
26531 @tab Compile with @option{VERBOSE} option
26532 Displays the version number of the compiler and program library
26533 manager used.
26534
26535 @item @command{ACS SPAWN}
26536 @tab [No equivalent]@*
26537 Creates a subprocess of the current process (same as @command{DCL SPAWN}
26538 command).
26539
26540 @item @command{ACS VERIFY}
26541 @tab [No equivalent]@*
26542 Performs a series of consistency checks on a program library to
26543 determine whether the library structure and library files are in
26544 valid form.
26545 @end multitable
26546
26547 @noindent
26548
26549 @node Input-Output
26550 @section Input-Output
26551
26552 @noindent
26553 On OpenVMS Alpha systems, HP Ada uses OpenVMS Record
26554 Management Services (RMS) to perform operations on
26555 external files.
26556
26557 @noindent
26558 HP Ada and GNAT predefine an identical set of input-
26559 output packages. To make the use of the
26560 generic @code{TEXT_IO} operations more convenient, HP Ada
26561 provides predefined library packages that instantiate the
26562 integer and floating-point operations for the predefined
26563 integer and floating-point types as shown in the following table.
26564
26565 @multitable @columnfractions .45 .55
26566 @item @emph{Package Name} @tab Instantiation
26567
26568 @item @code{INTEGER_TEXT_IO}
26569 @tab @code{INTEGER_IO(INTEGER)}
26570
26571 @item @code{SHORT_INTEGER_TEXT_IO}
26572 @tab @code{INTEGER_IO(SHORT_INTEGER)}
26573
26574 @item @code{SHORT_SHORT_INTEGER_TEXT_IO}
26575 @tab @code{INTEGER_IO(SHORT_SHORT_INTEGER)}
26576
26577 @item @code{FLOAT_TEXT_IO}
26578 @tab @code{FLOAT_IO(FLOAT)}
26579
26580 @item @code{LONG_FLOAT_TEXT_IO}
26581 @tab @code{FLOAT_IO(LONG_FLOAT)}
26582 @end multitable
26583
26584 @noindent
26585 The HP Ada predefined packages and their operations
26586 are implemented using OpenVMS Alpha files and input-output
26587 facilities. HP Ada supports asynchronous input-output on OpenVMS Alpha.
26588 Familiarity with the following is recommended:
26589 @itemize @bullet
26590 @item  RMS file organizations and access methods
26591
26592 @item  OpenVMS file specifications and directories
26593
26594 @item  OpenVMS File Definition Language (FDL)
26595 @end itemize
26596
26597 @noindent
26598 GNAT provides I/O facilities that are completely
26599 compatible with HP Ada. The distribution includes the
26600 standard HP Ada versions of all I/O packages, operating
26601 in a manner compatible with HP Ada. In particular, the
26602 following packages are by default the HP Ada (Ada 83)
26603 versions of these packages rather than the renamings
26604 suggested in Annex J of the Ada Reference Manual:
26605 @itemize @bullet
26606 @item  @code{TEXT_IO}
26607
26608 @item  @code{SEQUENTIAL_IO}
26609
26610 @item  @code{DIRECT_IO}
26611 @end itemize
26612
26613 @noindent
26614 The use of the standard child package syntax (for
26615 example, @code{ADA.TEXT_IO}) retrieves the post-Ada 83 versions of these
26616 packages.
26617 GNAT provides HP-compatible predefined instantiations
26618 of the @code{TEXT_IO} packages, and also
26619 provides the standard predefined instantiations required
26620 by the @cite{Ada Reference Manual}.
26621
26622 For further information on how GNAT interfaces to the file
26623 system or how I/O is implemented in programs written in
26624 mixed languages, see @ref{Implementation of the Standard I/O,,,
26625 gnat_rm, GNAT Reference Manual}.
26626 This chapter covers the following:
26627 @itemize @bullet
26628 @item  Standard I/O packages
26629
26630 @item  @code{FORM} strings
26631
26632 @item  @code{ADA.DIRECT_IO}
26633
26634 @item  @code{ADA.SEQUENTIAL_IO}
26635
26636 @item  @code{ADA.TEXT_IO}
26637
26638 @item  Stream pointer positioning
26639
26640 @item  Reading and writing non-regular files
26641
26642 @item  @code{GET_IMMEDIATE}
26643
26644 @item  Treating @code{TEXT_IO} files as streams
26645
26646 @item  Shared files
26647
26648 @item  Open modes
26649 @end itemize
26650
26651 @node Implementation Limits
26652 @section Implementation Limits
26653
26654 @noindent
26655 The following table lists implementation limits for HP Ada
26656 and GNAT systems.
26657 @multitable @columnfractions .60 .20 .20
26658 @sp 1
26659 @item  @emph{Compilation Parameter}
26660 @tab   @emph{HP Ada}
26661 @tab   @emph{GNAT}
26662 @sp 1
26663
26664 @item  In a subprogram or entry  declaration, maximum number of
26665 formal parameters that are of an unconstrained record type
26666 @tab   32
26667 @tab   No set limit
26668 @sp 1
26669
26670 @item  Maximum identifier length (number of characters)
26671 @tab   255
26672 @tab   32766
26673 @sp 1
26674
26675 @item  Maximum number of characters in a source line
26676 @tab   255
26677 @tab   32766
26678 @sp 1
26679
26680 @item  Maximum collection size   (number of bytes)
26681 @tab   2**31-1
26682 @tab   2**31-1
26683 @sp 1
26684
26685 @item  Maximum number of discriminants for a record type
26686 @tab   245
26687 @tab   No set limit
26688 @sp 1
26689
26690 @item  Maximum number of formal parameters in an entry or
26691 subprogram declaration
26692 @tab   246
26693 @tab    No set limit
26694 @sp 1
26695
26696 @item  Maximum number of dimensions in an array type
26697 @tab   255
26698 @tab   No set limit
26699 @sp 1
26700
26701 @item  Maximum number of library  units and subunits in a compilation.
26702 @tab   4095
26703 @tab   No set limit
26704 @sp 1
26705
26706 @item  Maximum number of library units and subunits in an execution.
26707 @tab   16383
26708 @tab   No set limit
26709 @sp 1
26710
26711 @item  Maximum number of objects declared with the pragma @code{COMMON_OBJECT}
26712 or @code{PSECT_OBJECT}
26713 @tab   32757
26714 @tab   No set limit
26715 @sp 1
26716
26717 @item  Maximum number of enumeration literals in an enumeration type
26718 definition
26719 @tab   65535
26720 @tab   No set limit
26721 @sp 1
26722
26723 @item  Maximum number of lines in a source file
26724 @tab   65534
26725 @tab   No set limit
26726 @sp 1
26727
26728 @item  Maximum number of bits in any object
26729 @tab   2**31-1
26730 @tab   2**31-1
26731 @sp 1
26732
26733 @item  Maximum size of the static portion of a stack frame (approximate)
26734 @tab   2**31-1
26735 @tab   2**31-1
26736 @end multitable
26737
26738 @node Tools and Utilities
26739 @section Tools and Utilities
26740
26741 @noindent
26742 The following table lists some of the OpenVMS development tools
26743 available for HP Ada, and the corresponding tools for
26744 use with @value{EDITION} on Alpha and I64 platforms.
26745 Aside from the debugger, all the OpenVMS tools identified are part
26746 of the DECset package.
26747
26748 @iftex
26749 @c Specify table in TeX since Texinfo does a poor job
26750 @tex
26751 \smallskip
26752 \smallskip
26753 \settabs\+Language-Sensitive Editor\quad
26754    &Product with HP Ada\quad
26755    &\cr
26756 \+\it Tool
26757    &\it Product with HP Ada
26758    & \it Product with GNAT Pro\cr
26759 \smallskip
26760 \+Code Management System
26761    &HP CMS
26762    & HP CMS\cr
26763 \smallskip
26764 \+Language-Sensitive Editor
26765    &HP LSE
26766    & emacs or HP LSE (Alpha)\cr
26767 \+
26768    &
26769    & HP LSE (I64)\cr
26770 \smallskip
26771 \+Debugger
26772    &OpenVMS Debug
26773    & gdb (Alpha),\cr
26774 \+
26775    &
26776    & OpenVMS Debug (I64)\cr
26777 \smallskip
26778 \+Source Code Analyzer /
26779    &HP SCA
26780    & GNAT XREF\cr
26781 \+Cross Referencer
26782    &
26783    &\cr
26784 \smallskip
26785 \+Test Manager
26786    &HP Digital Test
26787    & HP DTM\cr
26788 \+
26789    &Manager (DTM)
26790    &\cr
26791 \smallskip
26792 \+Performance and
26793    & HP PCA
26794    & HP PCA\cr
26795 \+Coverage Analyzer
26796    &
26797    &\cr
26798 \smallskip
26799 \+Module Management
26800    & HP MMS
26801    & Not applicable\cr
26802 \+ System
26803    &
26804    &\cr
26805 \smallskip
26806 \smallskip
26807 @end tex
26808 @end iftex
26809
26810 @ifnottex
26811 @c This is the Texinfo version of the table.  It renders poorly in pdf, hence
26812 @c the TeX version above for the printed version
26813 @flushleft
26814 @c @multitable @columnfractions .3 .4 .4
26815 @multitable {Source Code Analyzer /}{Tool with HP Ada}{Tool with GNAT Pro}
26816 @item @i{Tool}
26817 @tab @i{Tool with HP Ada}
26818 @tab @i{Tool with @value{EDITION}}
26819 @item Code Management@*System
26820 @tab HP CMS
26821 @tab HP CMS
26822 @item Language-Sensitive@*Editor
26823 @tab HP LSE
26824 @tab emacs or HP LSE (Alpha)
26825 @item
26826 @tab
26827 @tab HP LSE (I64)
26828 @item Debugger
26829 @tab OpenVMS Debug
26830 @tab gdb (Alpha),
26831 @item
26832 @tab
26833 @tab OpenVMS Debug (I64)
26834 @item Source Code Analyzer /@*Cross Referencer
26835 @tab HP SCA
26836 @tab GNAT XREF
26837 @item Test Manager
26838 @tab HP Digital Test@*Manager (DTM)
26839 @tab HP DTM
26840 @item Performance and@*Coverage Analyzer
26841 @tab HP PCA
26842 @tab HP PCA
26843 @item Module Management@*System
26844 @tab HP MMS
26845 @tab Not applicable
26846 @end multitable
26847 @end flushleft
26848 @end ifnottex
26849
26850 @end ifset
26851
26852 @c **************************************
26853 @node Platform-Specific Information for the Run-Time Libraries
26854 @appendix Platform-Specific Information for the Run-Time Libraries
26855 @cindex Tasking and threads libraries
26856 @cindex Threads libraries and tasking
26857 @cindex Run-time libraries (platform-specific information)
26858
26859 @noindent
26860 The GNAT run-time implementation may vary with respect to both the
26861 underlying threads library and the exception handling scheme.
26862 For threads support, one or more of the following are supplied:
26863 @itemize @bullet
26864 @item @b{native threads library}, a binding to the thread package from
26865 the underlying operating system
26866
26867 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
26868 POSIX thread package
26869 @end itemize
26870
26871 @noindent
26872 For exception handling, either or both of two models are supplied:
26873 @itemize @bullet
26874 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
26875 Most programs should experience a substantial speed improvement by
26876 being compiled with a ZCX run-time.
26877 This is especially true for
26878 tasking applications or applications with many exception handlers.}
26879 @cindex Zero-Cost Exceptions
26880 @cindex ZCX (Zero-Cost Exceptions)
26881 which uses binder-generated tables that
26882 are interrogated at run time to locate a handler
26883
26884 @item @b{setjmp / longjmp} (``SJLJ''),
26885 @cindex setjmp/longjmp Exception Model
26886 @cindex SJLJ (setjmp/longjmp Exception Model)
26887 which uses dynamically-set data to establish
26888 the set of handlers
26889 @end itemize
26890
26891 @noindent
26892 This appendix summarizes which combinations of threads and exception support
26893 are supplied on various GNAT platforms.
26894 It then shows how to select a particular library either
26895 permanently or temporarily,
26896 explains the properties of (and tradeoffs among) the various threads
26897 libraries, and provides some additional
26898 information about several specific platforms.
26899
26900 @menu
26901 * Summary of Run-Time Configurations::
26902 * Specifying a Run-Time Library::
26903 * Choosing the Scheduling Policy::
26904 * Solaris-Specific Considerations::
26905 * Linux-Specific Considerations::
26906 * AIX-Specific Considerations::
26907 * Irix-Specific Considerations::
26908 * RTX-Specific Considerations::
26909 @end menu
26910
26911 @node Summary of Run-Time Configurations
26912 @section Summary of Run-Time Configurations
26913
26914 @multitable @columnfractions .30 .70
26915 @item @b{alpha-openvms}
26916 @item @code{@ @ }@i{rts-native (default)}
26917 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
26918 @item @code{@ @ @ @ }Exceptions @tab ZCX
26919 @*
26920 @item @b{alpha-tru64}
26921 @item @code{@ @ }@i{rts-native (default)}
26922 @item @code{@ @ @ @ }Tasking    @tab native TRU64 threads
26923 @item @code{@ @ @ @ }Exceptions @tab ZCX
26924 @*
26925 @item @code{@ @ }@i{rts-sjlj}
26926 @item @code{@ @ @ @ }Tasking    @tab native TRU64 threads
26927 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26928 @*
26929 @item @b{ia64-hp_linux}
26930 @item @code{@ @ }@i{rts-native (default)}
26931 @item @code{@ @ @ @ }Tasking    @tab pthread library
26932 @item @code{@ @ @ @ }Exceptions @tab ZCX
26933 @*
26934 @item @b{ia64-hpux}
26935 @item @code{@ @ }@i{rts-native (default)}
26936 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
26937 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26938 @*
26939 @item @b{ia64-openvms}
26940 @item @code{@ @ }@i{rts-native (default)}
26941 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
26942 @item @code{@ @ @ @ }Exceptions @tab ZCX
26943 @*
26944 @item @b{ia64-sgi_linux}
26945 @item @code{@ @ }@i{rts-native (default)}
26946 @item @code{@ @ @ @ }Tasking    @tab pthread library
26947 @item @code{@ @ @ @ }Exceptions @tab ZCX
26948 @*
26949 @item @b{mips-irix}
26950 @item @code{@ @ }@i{rts-native (default)}
26951 @item @code{@ @ @ @ }Tasking    @tab native IRIX threads
26952 @item @code{@ @ @ @ }Exceptions @tab ZCX
26953 @*
26954 @item @b{pa-hpux}
26955 @item @code{@ @ }@i{rts-native (default)}
26956 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
26957 @item @code{@ @ @ @ }Exceptions @tab ZCX
26958 @*
26959 @item @code{@ @ }@i{rts-sjlj}
26960 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
26961 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26962 @*
26963 @item @b{ppc-aix}
26964 @item @code{@ @ }@i{rts-native (default)}
26965 @item @code{@ @ @ @ }Tasking    @tab native AIX threads
26966 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26967 @*
26968 @item @b{ppc-darwin}
26969 @item @code{@ @ }@i{rts-native (default)}
26970 @item @code{@ @ @ @ }Tasking    @tab native MacOS threads
26971 @item @code{@ @ @ @ }Exceptions @tab ZCX
26972 @*
26973 @item @b{sparc-solaris}  @tab
26974 @item @code{@ @ }@i{rts-native (default)}
26975 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
26976 @item @code{@ @ @ @ }Exceptions @tab ZCX
26977 @*
26978 @item @code{@ @ }@i{rts-pthread}
26979 @item @code{@ @ @ @ }Tasking    @tab pthread library
26980 @item @code{@ @ @ @ }Exceptions @tab ZCX
26981 @*
26982 @item @code{@ @ }@i{rts-sjlj}
26983 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
26984 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26985 @*
26986 @item @b{sparc64-solaris}  @tab
26987 @item @code{@ @ }@i{rts-native (default)}
26988 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
26989 @item @code{@ @ @ @ }Exceptions @tab ZCX
26990 @*
26991 @item @b{x86-linux}
26992 @item @code{@ @ }@i{rts-native (default)}
26993 @item @code{@ @ @ @ }Tasking    @tab pthread library
26994 @item @code{@ @ @ @ }Exceptions @tab ZCX
26995 @*
26996 @item @code{@ @ }@i{rts-sjlj}
26997 @item @code{@ @ @ @ }Tasking    @tab pthread library
26998 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26999 @*
27000 @item @b{x86-lynx}
27001 @item @code{@ @ }@i{rts-native (default)}
27002 @item @code{@ @ @ @ }Tasking    @tab native LynxOS threads
27003 @item @code{@ @ @ @ }Exceptions @tab SJLJ
27004 @*
27005 @item @b{x86-solaris}
27006 @item @code{@ @ }@i{rts-native (default)}
27007 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads
27008 @item @code{@ @ @ @ }Exceptions @tab SJLJ
27009 @*
27010 @item @b{x86-windows}
27011 @item @code{@ @ }@i{rts-native (default)}
27012 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
27013 @item @code{@ @ @ @ }Exceptions @tab ZCX
27014 @*
27015 @item @code{@ @ }@i{rts-sjlj (default)}
27016 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
27017 @item @code{@ @ @ @ }Exceptions @tab SJLJ
27018 @*
27019 @item @b{x86-windows-rtx}
27020 @item @code{@ @ }@i{rts-rtx-rtss (default)}
27021 @item @code{@ @ @ @ }Tasking    @tab RTX real-time subsystem RTSS threads (kernel mode)
27022 @item @code{@ @ @ @ }Exceptions @tab SJLJ
27023 @*
27024 @item @code{@ @ }@i{rts-rtx-w32}
27025 @item @code{@ @ @ @ }Tasking    @tab RTX Win32 threads (user mode)
27026 @item @code{@ @ @ @ }Exceptions @tab ZCX
27027 @*
27028 @item @b{x86_64-linux}
27029 @item @code{@ @ }@i{rts-native (default)}
27030 @item @code{@ @ @ @ }Tasking    @tab pthread library
27031 @item @code{@ @ @ @ }Exceptions @tab ZCX
27032 @*
27033 @item @code{@ @ }@i{rts-sjlj}
27034 @item @code{@ @ @ @ }Tasking    @tab pthread library
27035 @item @code{@ @ @ @ }Exceptions @tab SJLJ
27036 @*
27037 @end multitable
27038
27039 @node Specifying a Run-Time Library
27040 @section Specifying a Run-Time Library
27041
27042 @noindent
27043 The @file{adainclude} subdirectory containing the sources of the GNAT
27044 run-time library, and the @file{adalib} subdirectory containing the
27045 @file{ALI} files and the static and/or shared GNAT library, are located
27046 in the gcc target-dependent area:
27047
27048 @smallexample
27049 target=$prefix/lib/gcc/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
27050 @end smallexample
27051
27052 @noindent
27053 As indicated above, on some platforms several run-time libraries are supplied.
27054 These libraries are installed in the target dependent area and
27055 contain a complete source and binary subdirectory. The detailed description
27056 below explains the differences between the different libraries in terms of
27057 their thread support.
27058
27059 The default run-time library (when GNAT is installed) is @emph{rts-native}.
27060 This default run time is selected by the means of soft links.
27061 For example on x86-linux:
27062
27063 @smallexample
27064 @group
27065  $(target-dir)
27066      |
27067      +--- adainclude----------+
27068      |                        |
27069      +--- adalib-----------+  |
27070      |                     |  |
27071      +--- rts-native       |  |
27072      |    |                |  |
27073      |    +--- adainclude <---+
27074      |    |                |
27075      |    +--- adalib <----+
27076      |
27077      +--- rts-sjlj
27078           |
27079           +--- adainclude
27080           |
27081           +--- adalib
27082 @end group
27083 @end smallexample
27084
27085 @noindent
27086 If the @i{rts-sjlj} library is to be selected on a permanent basis,
27087 these soft links can be modified with the following commands:
27088
27089 @smallexample
27090 $ cd $target
27091 $ rm -f adainclude adalib
27092 $ ln -s rts-sjlj/adainclude adainclude
27093 $ ln -s rts-sjlj/adalib adalib
27094 @end smallexample
27095
27096 @noindent
27097 Alternatively, you can specify @file{rts-sjlj/adainclude} in the file
27098 @file{$target/ada_source_path} and @file{rts-sjlj/adalib} in
27099 @file{$target/ada_object_path}.
27100
27101 Selecting another run-time library temporarily can be
27102 achieved by using the @option{--RTS} switch, e.g., @option{--RTS=sjlj}
27103 @cindex @option{--RTS} option
27104
27105 @node Choosing the Scheduling Policy
27106 @section Choosing the Scheduling Policy
27107
27108 @noindent
27109 When using a POSIX threads implementation, you have a choice of several
27110 scheduling policies: @code{SCHED_FIFO},
27111 @cindex @code{SCHED_FIFO} scheduling policy
27112 @code{SCHED_RR}
27113 @cindex @code{SCHED_RR} scheduling policy
27114 and @code{SCHED_OTHER}.
27115 @cindex @code{SCHED_OTHER} scheduling policy
27116 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
27117 or @code{SCHED_RR} requires special (e.g., root) privileges.
27118
27119 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
27120 @code{SCHED_FIFO},
27121 @cindex @code{SCHED_FIFO} scheduling policy
27122 you can use one of the following:
27123
27124 @itemize @bullet
27125 @item
27126 @code{pragma Time_Slice (0.0)}
27127 @cindex pragma Time_Slice
27128 @item
27129 the corresponding binder option @option{-T0}
27130 @cindex @option{-T0} option
27131 @item
27132 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
27133 @cindex pragma Task_Dispatching_Policy
27134 @end itemize
27135
27136 @noindent
27137 To specify @code{SCHED_RR},
27138 @cindex @code{SCHED_RR} scheduling policy
27139 you should use @code{pragma Time_Slice} with a
27140 value greater than @code{0.0}, or else use the corresponding @option{-T}
27141 binder option.
27142
27143 @node Solaris-Specific Considerations
27144 @section Solaris-Specific Considerations
27145 @cindex Solaris Sparc threads libraries
27146
27147 @noindent
27148 This section addresses some topics related to the various threads libraries
27149 on Sparc Solaris.
27150
27151 @menu
27152 * Solaris Threads Issues::
27153 @end menu
27154
27155 @node Solaris Threads Issues
27156 @subsection Solaris Threads Issues
27157
27158 @noindent
27159 GNAT under Solaris/Sparc 32 bits comes with an alternate tasking run-time
27160 library based on POSIX threads --- @emph{rts-pthread}.
27161 @cindex rts-pthread threads library
27162 This run-time library has the advantage of being mostly shared across all
27163 POSIX-compliant thread implementations, and it also provides under
27164 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
27165 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
27166 and @code{PTHREAD_PRIO_PROTECT}
27167 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
27168 semantics that can be selected using the predefined pragma
27169 @code{Locking_Policy}
27170 @cindex pragma Locking_Policy (under rts-pthread)
27171 with respectively
27172 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
27173 @cindex @code{Inheritance_Locking} (under rts-pthread)
27174 @cindex @code{Ceiling_Locking} (under rts-pthread)
27175
27176 As explained above, the native run-time library is based on the Solaris thread
27177 library (@code{libthread}) and is the default library.
27178
27179 When the Solaris threads library is used (this is the default), programs
27180 compiled with GNAT can automatically take advantage of
27181 and can thus execute on multiple processors.
27182 The user can alternatively specify a processor on which the program should run
27183 to emulate a single-processor system. The multiprocessor / uniprocessor choice
27184 is made by
27185 setting the environment variable @env{GNAT_PROCESSOR}
27186 @cindex @env{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
27187 to one of the following:
27188
27189 @table @code
27190 @item -2
27191 Use the default configuration (run the program on all
27192 available processors) - this is the same as having @code{GNAT_PROCESSOR}
27193 unset
27194
27195 @item -1
27196 Let the run-time implementation choose one processor and run the program on
27197 that processor
27198
27199 @item 0 .. Last_Proc
27200 Run the program on the specified processor.
27201 @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
27202 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
27203 @end table
27204
27205 @node Linux-Specific Considerations
27206 @section Linux-Specific Considerations
27207 @cindex Linux threads libraries
27208
27209 @noindent
27210 On GNU/Linux without NPTL support (usually system with GNU C Library
27211 older than 2.3), the signal model is not POSIX compliant, which means
27212 that to send a signal to the process, you need to send the signal to all
27213 threads, e.g.@: by using @code{killpg()}.
27214
27215 @node AIX-Specific Considerations
27216 @section AIX-Specific Considerations
27217 @cindex AIX resolver library
27218
27219 @noindent
27220 On AIX, the resolver library initializes some internal structure on
27221 the first call to @code{get*by*} functions, which are used to implement
27222 @code{GNAT.Sockets.Get_Host_By_Name} and
27223 @code{GNAT.Sockets.Get_Host_By_Address}.
27224 If such initialization occurs within an Ada task, and the stack size for
27225 the task is the default size, a stack overflow may occur.
27226
27227 To avoid this overflow, the user should either ensure that the first call
27228 to @code{GNAT.Sockets.Get_Host_By_Name} or
27229 @code{GNAT.Sockets.Get_Host_By_Addrss}
27230 occurs in the environment task, or use @code{pragma Storage_Size} to
27231 specify a sufficiently large size for the stack of the task that contains
27232 this call.
27233
27234 @node Irix-Specific Considerations
27235 @section Irix-Specific Considerations
27236 @cindex Irix libraries
27237
27238 @noindent
27239 The GCC support libraries coming with the Irix compiler have moved to
27240 their canonical place with respect to the general Irix ABI related
27241 conventions. Running applications built with the default shared GNAT
27242 run-time now requires the LD_LIBRARY_PATH environment variable to
27243 include this location. A possible way to achieve this is to issue the
27244 following command line on a bash prompt:
27245
27246 @smallexample
27247 @group
27248 $  LD_LIBRARY_PATH=$LD_LIBRARY_PATH:`dirname \`gcc --print-file-name=libgcc_s.so\``
27249 @end group
27250 @end smallexample
27251
27252 @node RTX-Specific Considerations
27253 @section RTX-Specific Considerations
27254 @cindex RTX libraries
27255
27256 @noindent
27257 The Real-time Extension (RTX) to Windows is based on the Windows Win32
27258 API. Applications can be built to work in two different modes:
27259
27260 @itemize @bullet
27261 @item
27262 Windows executables that run in Ring 3 to utilize memory protection
27263 (@emph{rts-rtx-w32}).
27264
27265 @item
27266 Real-time subsystem (RTSS) executables that run in Ring 0, where
27267 performance can be optimized with RTSS applications taking precedent
27268 over all Windows applications (@emph{rts-rtx-rtss}).
27269
27270 @end itemize
27271
27272 @c *******************************
27273 @node Example of Binder Output File
27274 @appendix Example of Binder Output File
27275
27276 @noindent
27277 This Appendix displays the source code for @command{gnatbind}'s output
27278 file generated for a simple ``Hello World'' program.
27279 Comments have been added for clarification purposes.
27280
27281 @smallexample @c adanocomment
27282 @iftex
27283 @leftskip=0cm
27284 @end iftex
27285 --  The package is called Ada_Main unless this name is actually used
27286 --  as a unit name in the partition, in which case some other unique
27287 --  name is used.
27288
27289 with System;
27290 package ada_main is
27291
27292    Elab_Final_Code : Integer;
27293    pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
27294
27295    --  The main program saves the parameters (argument count,
27296    --  argument values, environment pointer) in global variables
27297    --  for later access by other units including
27298    --  Ada.Command_Line.
27299
27300    gnat_argc : Integer;
27301    gnat_argv : System.Address;
27302    gnat_envp : System.Address;
27303
27304    --  The actual variables are stored in a library routine. This
27305    --  is useful for some shared library situations, where there
27306    --  are problems if variables are not in the library.
27307
27308    pragma Import (C, gnat_argc);
27309    pragma Import (C, gnat_argv);
27310    pragma Import (C, gnat_envp);
27311
27312    --  The exit status is similarly an external location
27313
27314    gnat_exit_status : Integer;
27315    pragma Import (C, gnat_exit_status);
27316
27317    GNAT_Version : constant String :=
27318                     "GNAT Version: 6.0.0w (20061115)";
27319    pragma Export (C, GNAT_Version, "__gnat_version");
27320
27321    --  This is the generated adafinal routine that performs
27322    --  finalization at the end of execution. In the case where
27323    --  Ada is the main program, this main program makes a call
27324    --  to adafinal at program termination.
27325
27326    procedure adafinal;
27327    pragma Export (C, adafinal, "adafinal");
27328
27329    --  This is the generated adainit routine that performs
27330    --  initialization at the start of execution. In the case
27331    --  where Ada is the main program, this main program makes
27332    --  a call to adainit at program startup.
27333
27334    procedure adainit;
27335    pragma Export (C, adainit, "adainit");
27336
27337    --  This routine is called at the start of execution. It is
27338    --  a dummy routine that is used by the debugger to breakpoint
27339    --  at the start of execution.
27340
27341    procedure Break_Start;
27342    pragma Import (C, Break_Start, "__gnat_break_start");
27343
27344    --  This is the actual generated main program (it would be
27345    --  suppressed if the no main program switch were used). As
27346    --  required by standard system conventions, this program has
27347    --  the external name main.
27348
27349    function main
27350      (argc : Integer;
27351       argv : System.Address;
27352       envp : System.Address)
27353       return Integer;
27354    pragma Export (C, main, "main");
27355
27356    --  The following set of constants give the version
27357    --  identification values for every unit in the bound
27358    --  partition. This identification is computed from all
27359    --  dependent semantic units, and corresponds to the
27360    --  string that would be returned by use of the
27361    --  Body_Version or Version attributes.
27362
27363    type Version_32 is mod 2 ** 32;
27364    u00001 : constant Version_32 := 16#7880BEB3#;
27365    u00002 : constant Version_32 := 16#0D24CBD0#;
27366    u00003 : constant Version_32 := 16#3283DBEB#;
27367    u00004 : constant Version_32 := 16#2359F9ED#;
27368    u00005 : constant Version_32 := 16#664FB847#;
27369    u00006 : constant Version_32 := 16#68E803DF#;
27370    u00007 : constant Version_32 := 16#5572E604#;
27371    u00008 : constant Version_32 := 16#46B173D8#;
27372    u00009 : constant Version_32 := 16#156A40CF#;
27373    u00010 : constant Version_32 := 16#033DABE0#;
27374    u00011 : constant Version_32 := 16#6AB38FEA#;
27375    u00012 : constant Version_32 := 16#22B6217D#;
27376    u00013 : constant Version_32 := 16#68A22947#;
27377    u00014 : constant Version_32 := 16#18CC4A56#;
27378    u00015 : constant Version_32 := 16#08258E1B#;
27379    u00016 : constant Version_32 := 16#367D5222#;
27380    u00017 : constant Version_32 := 16#20C9ECA4#;
27381    u00018 : constant Version_32 := 16#50D32CB6#;
27382    u00019 : constant Version_32 := 16#39A8BB77#;
27383    u00020 : constant Version_32 := 16#5CF8FA2B#;
27384    u00021 : constant Version_32 := 16#2F1EB794#;
27385    u00022 : constant Version_32 := 16#31AB6444#;
27386    u00023 : constant Version_32 := 16#1574B6E9#;
27387    u00024 : constant Version_32 := 16#5109C189#;
27388    u00025 : constant Version_32 := 16#56D770CD#;
27389    u00026 : constant Version_32 := 16#02F9DE3D#;
27390    u00027 : constant Version_32 := 16#08AB6B2C#;
27391    u00028 : constant Version_32 := 16#3FA37670#;
27392    u00029 : constant Version_32 := 16#476457A0#;
27393    u00030 : constant Version_32 := 16#731E1B6E#;
27394    u00031 : constant Version_32 := 16#23C2E789#;
27395    u00032 : constant Version_32 := 16#0F1BD6A1#;
27396    u00033 : constant Version_32 := 16#7C25DE96#;
27397    u00034 : constant Version_32 := 16#39ADFFA2#;
27398    u00035 : constant Version_32 := 16#571DE3E7#;
27399    u00036 : constant Version_32 := 16#5EB646AB#;
27400    u00037 : constant Version_32 := 16#4249379B#;
27401    u00038 : constant Version_32 := 16#0357E00A#;
27402    u00039 : constant Version_32 := 16#3784FB72#;
27403    u00040 : constant Version_32 := 16#2E723019#;
27404    u00041 : constant Version_32 := 16#623358EA#;
27405    u00042 : constant Version_32 := 16#107F9465#;
27406    u00043 : constant Version_32 := 16#6843F68A#;
27407    u00044 : constant Version_32 := 16#63305874#;
27408    u00045 : constant Version_32 := 16#31E56CE1#;
27409    u00046 : constant Version_32 := 16#02917970#;
27410    u00047 : constant Version_32 := 16#6CCBA70E#;
27411    u00048 : constant Version_32 := 16#41CD4204#;
27412    u00049 : constant Version_32 := 16#572E3F58#;
27413    u00050 : constant Version_32 := 16#20729FF5#;
27414    u00051 : constant Version_32 := 16#1D4F93E8#;
27415    u00052 : constant Version_32 := 16#30B2EC3D#;
27416    u00053 : constant Version_32 := 16#34054F96#;
27417    u00054 : constant Version_32 := 16#5A199860#;
27418    u00055 : constant Version_32 := 16#0E7F912B#;
27419    u00056 : constant Version_32 := 16#5760634A#;
27420    u00057 : constant Version_32 := 16#5D851835#;
27421
27422    --  The following Export pragmas export the version numbers
27423    --  with symbolic names ending in B (for body) or S
27424    --  (for spec) so that they can be located in a link. The
27425    --  information provided here is sufficient to track down
27426    --  the exact versions of units used in a given build.
27427
27428    pragma Export (C, u00001, "helloB");
27429    pragma Export (C, u00002, "system__standard_libraryB");
27430    pragma Export (C, u00003, "system__standard_libraryS");
27431    pragma Export (C, u00004, "adaS");
27432    pragma Export (C, u00005, "ada__text_ioB");
27433    pragma Export (C, u00006, "ada__text_ioS");
27434    pragma Export (C, u00007, "ada__exceptionsB");
27435    pragma Export (C, u00008, "ada__exceptionsS");
27436    pragma Export (C, u00009, "gnatS");
27437    pragma Export (C, u00010, "gnat__heap_sort_aB");
27438    pragma Export (C, u00011, "gnat__heap_sort_aS");
27439    pragma Export (C, u00012, "systemS");
27440    pragma Export (C, u00013, "system__exception_tableB");
27441    pragma Export (C, u00014, "system__exception_tableS");
27442    pragma Export (C, u00015, "gnat__htableB");
27443    pragma Export (C, u00016, "gnat__htableS");
27444    pragma Export (C, u00017, "system__exceptionsS");
27445    pragma Export (C, u00018, "system__machine_state_operationsB");
27446    pragma Export (C, u00019, "system__machine_state_operationsS");
27447    pragma Export (C, u00020, "system__machine_codeS");
27448    pragma Export (C, u00021, "system__storage_elementsB");
27449    pragma Export (C, u00022, "system__storage_elementsS");
27450    pragma Export (C, u00023, "system__secondary_stackB");
27451    pragma Export (C, u00024, "system__secondary_stackS");
27452    pragma Export (C, u00025, "system__parametersB");
27453    pragma Export (C, u00026, "system__parametersS");
27454    pragma Export (C, u00027, "system__soft_linksB");
27455    pragma Export (C, u00028, "system__soft_linksS");
27456    pragma Export (C, u00029, "system__stack_checkingB");
27457    pragma Export (C, u00030, "system__stack_checkingS");
27458    pragma Export (C, u00031, "system__tracebackB");
27459    pragma Export (C, u00032, "system__tracebackS");
27460    pragma Export (C, u00033, "ada__streamsS");
27461    pragma Export (C, u00034, "ada__tagsB");
27462    pragma Export (C, u00035, "ada__tagsS");
27463    pragma Export (C, u00036, "system__string_opsB");
27464    pragma Export (C, u00037, "system__string_opsS");
27465    pragma Export (C, u00038, "interfacesS");
27466    pragma Export (C, u00039, "interfaces__c_streamsB");
27467    pragma Export (C, u00040, "interfaces__c_streamsS");
27468    pragma Export (C, u00041, "system__file_ioB");
27469    pragma Export (C, u00042, "system__file_ioS");
27470    pragma Export (C, u00043, "ada__finalizationB");
27471    pragma Export (C, u00044, "ada__finalizationS");
27472    pragma Export (C, u00045, "system__finalization_rootB");
27473    pragma Export (C, u00046, "system__finalization_rootS");
27474    pragma Export (C, u00047, "system__finalization_implementationB");
27475    pragma Export (C, u00048, "system__finalization_implementationS");
27476    pragma Export (C, u00049, "system__string_ops_concat_3B");
27477    pragma Export (C, u00050, "system__string_ops_concat_3S");
27478    pragma Export (C, u00051, "system__stream_attributesB");
27479    pragma Export (C, u00052, "system__stream_attributesS");
27480    pragma Export (C, u00053, "ada__io_exceptionsS");
27481    pragma Export (C, u00054, "system__unsigned_typesS");
27482    pragma Export (C, u00055, "system__file_control_blockS");
27483    pragma Export (C, u00056, "ada__finalization__list_controllerB");
27484    pragma Export (C, u00057, "ada__finalization__list_controllerS");
27485
27486    -- BEGIN ELABORATION ORDER
27487    -- ada (spec)
27488    -- gnat (spec)
27489    -- gnat.heap_sort_a (spec)
27490    -- gnat.heap_sort_a (body)
27491    -- gnat.htable (spec)
27492    -- gnat.htable (body)
27493    -- interfaces (spec)
27494    -- system (spec)
27495    -- system.machine_code (spec)
27496    -- system.parameters (spec)
27497    -- system.parameters (body)
27498    -- interfaces.c_streams (spec)
27499    -- interfaces.c_streams (body)
27500    -- system.standard_library (spec)
27501    -- ada.exceptions (spec)
27502    -- system.exception_table (spec)
27503    -- system.exception_table (body)
27504    -- ada.io_exceptions (spec)
27505    -- system.exceptions (spec)
27506    -- system.storage_elements (spec)
27507    -- system.storage_elements (body)
27508    -- system.machine_state_operations (spec)
27509    -- system.machine_state_operations (body)
27510    -- system.secondary_stack (spec)
27511    -- system.stack_checking (spec)
27512    -- system.soft_links (spec)
27513    -- system.soft_links (body)
27514    -- system.stack_checking (body)
27515    -- system.secondary_stack (body)
27516    -- system.standard_library (body)
27517    -- system.string_ops (spec)
27518    -- system.string_ops (body)
27519    -- ada.tags (spec)
27520    -- ada.tags (body)
27521    -- ada.streams (spec)
27522    -- system.finalization_root (spec)
27523    -- system.finalization_root (body)
27524    -- system.string_ops_concat_3 (spec)
27525    -- system.string_ops_concat_3 (body)
27526    -- system.traceback (spec)
27527    -- system.traceback (body)
27528    -- ada.exceptions (body)
27529    -- system.unsigned_types (spec)
27530    -- system.stream_attributes (spec)
27531    -- system.stream_attributes (body)
27532    -- system.finalization_implementation (spec)
27533    -- system.finalization_implementation (body)
27534    -- ada.finalization (spec)
27535    -- ada.finalization (body)
27536    -- ada.finalization.list_controller (spec)
27537    -- ada.finalization.list_controller (body)
27538    -- system.file_control_block (spec)
27539    -- system.file_io (spec)
27540    -- system.file_io (body)
27541    -- ada.text_io (spec)
27542    -- ada.text_io (body)
27543    -- hello (body)
27544    -- END ELABORATION ORDER
27545
27546 end ada_main;
27547
27548 --  The following source file name pragmas allow the generated file
27549 --  names to be unique for different main programs. They are needed
27550 --  since the package name will always be Ada_Main.
27551
27552 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
27553 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
27554
27555 --  Generated package body for Ada_Main starts here
27556
27557 package body ada_main is
27558
27559    --  The actual finalization is performed by calling the
27560    --  library routine in System.Standard_Library.Adafinal
27561
27562    procedure Do_Finalize;
27563    pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
27564
27565    -------------
27566    -- adainit --
27567    -------------
27568
27569 @findex adainit
27570    procedure adainit is
27571
27572       --  These booleans are set to True once the associated unit has
27573       --  been elaborated. It is also used to avoid elaborating the
27574       --  same unit twice.
27575
27576       E040 : Boolean;
27577       pragma Import (Ada, E040, "interfaces__c_streams_E");
27578
27579       E008 : Boolean;
27580       pragma Import (Ada, E008, "ada__exceptions_E");
27581
27582       E014 : Boolean;
27583       pragma Import (Ada, E014, "system__exception_table_E");
27584
27585       E053 : Boolean;
27586       pragma Import (Ada, E053, "ada__io_exceptions_E");
27587
27588       E017 : Boolean;
27589       pragma Import (Ada, E017, "system__exceptions_E");
27590
27591       E024 : Boolean;
27592       pragma Import (Ada, E024, "system__secondary_stack_E");
27593
27594       E030 : Boolean;
27595       pragma Import (Ada, E030, "system__stack_checking_E");
27596
27597       E028 : Boolean;
27598       pragma Import (Ada, E028, "system__soft_links_E");
27599
27600       E035 : Boolean;
27601       pragma Import (Ada, E035, "ada__tags_E");
27602
27603       E033 : Boolean;
27604       pragma Import (Ada, E033, "ada__streams_E");
27605
27606       E046 : Boolean;
27607       pragma Import (Ada, E046, "system__finalization_root_E");
27608
27609       E048 : Boolean;
27610       pragma Import (Ada, E048, "system__finalization_implementation_E");
27611
27612       E044 : Boolean;
27613       pragma Import (Ada, E044, "ada__finalization_E");
27614
27615       E057 : Boolean;
27616       pragma Import (Ada, E057, "ada__finalization__list_controller_E");
27617
27618       E055 : Boolean;
27619       pragma Import (Ada, E055, "system__file_control_block_E");
27620
27621       E042 : Boolean;
27622       pragma Import (Ada, E042, "system__file_io_E");
27623
27624       E006 : Boolean;
27625       pragma Import (Ada, E006, "ada__text_io_E");
27626
27627       --  Set_Globals is a library routine that stores away the
27628       --  value of the indicated set of global values in global
27629       --  variables within the library.
27630
27631       procedure Set_Globals
27632         (Main_Priority            : Integer;
27633          Time_Slice_Value         : Integer;
27634          WC_Encoding              : Character;
27635          Locking_Policy           : Character;
27636          Queuing_Policy           : Character;
27637          Task_Dispatching_Policy  : Character;
27638          Adafinal                 : System.Address;
27639          Unreserve_All_Interrupts : Integer;
27640          Exception_Tracebacks     : Integer);
27641 @findex __gnat_set_globals
27642       pragma Import (C, Set_Globals, "__gnat_set_globals");
27643
27644       --  SDP_Table_Build is a library routine used to build the
27645       --  exception tables. See unit Ada.Exceptions in files
27646       --  a-except.ads/adb for full details of how zero cost
27647       --  exception handling works. This procedure, the call to
27648       --  it, and the two following tables are all omitted if the
27649       --  build is in longjmp/setjmp exception mode.
27650
27651 @findex SDP_Table_Build
27652 @findex Zero Cost Exceptions
27653       procedure SDP_Table_Build
27654         (SDP_Addresses   : System.Address;
27655          SDP_Count       : Natural;
27656          Elab_Addresses  : System.Address;
27657          Elab_Addr_Count : Natural);
27658       pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
27659
27660       --  Table of Unit_Exception_Table addresses. Used for zero
27661       --  cost exception handling to build the top level table.
27662
27663       ST : aliased constant array (1 .. 23) of System.Address := (
27664         Hello'UET_Address,
27665         Ada.Text_Io'UET_Address,
27666         Ada.Exceptions'UET_Address,
27667         Gnat.Heap_Sort_A'UET_Address,
27668         System.Exception_Table'UET_Address,
27669         System.Machine_State_Operations'UET_Address,
27670         System.Secondary_Stack'UET_Address,
27671         System.Parameters'UET_Address,
27672         System.Soft_Links'UET_Address,
27673         System.Stack_Checking'UET_Address,
27674         System.Traceback'UET_Address,
27675         Ada.Streams'UET_Address,
27676         Ada.Tags'UET_Address,
27677         System.String_Ops'UET_Address,
27678         Interfaces.C_Streams'UET_Address,
27679         System.File_Io'UET_Address,
27680         Ada.Finalization'UET_Address,
27681         System.Finalization_Root'UET_Address,
27682         System.Finalization_Implementation'UET_Address,
27683         System.String_Ops_Concat_3'UET_Address,
27684         System.Stream_Attributes'UET_Address,
27685         System.File_Control_Block'UET_Address,
27686         Ada.Finalization.List_Controller'UET_Address);
27687
27688       --  Table of addresses of elaboration routines. Used for
27689       --  zero cost exception handling to make sure these
27690       --  addresses are included in the top level procedure
27691       --  address table.
27692
27693       EA : aliased constant array (1 .. 23) of System.Address := (
27694         adainit'Code_Address,
27695         Do_Finalize'Code_Address,
27696         Ada.Exceptions'Elab_Spec'Address,
27697         System.Exceptions'Elab_Spec'Address,
27698         Interfaces.C_Streams'Elab_Spec'Address,
27699         System.Exception_Table'Elab_Body'Address,
27700         Ada.Io_Exceptions'Elab_Spec'Address,
27701         System.Stack_Checking'Elab_Spec'Address,
27702         System.Soft_Links'Elab_Body'Address,
27703         System.Secondary_Stack'Elab_Body'Address,
27704         Ada.Tags'Elab_Spec'Address,
27705         Ada.Tags'Elab_Body'Address,
27706         Ada.Streams'Elab_Spec'Address,
27707         System.Finalization_Root'Elab_Spec'Address,
27708         Ada.Exceptions'Elab_Body'Address,
27709         System.Finalization_Implementation'Elab_Spec'Address,
27710         System.Finalization_Implementation'Elab_Body'Address,
27711         Ada.Finalization'Elab_Spec'Address,
27712         Ada.Finalization.List_Controller'Elab_Spec'Address,
27713         System.File_Control_Block'Elab_Spec'Address,
27714         System.File_Io'Elab_Body'Address,
27715         Ada.Text_Io'Elab_Spec'Address,
27716         Ada.Text_Io'Elab_Body'Address);
27717
27718    --  Start of processing for adainit
27719
27720    begin
27721
27722       --  Call SDP_Table_Build to build the top level procedure
27723       --  table for zero cost exception handling (omitted in
27724       --  longjmp/setjmp mode).
27725
27726       SDP_Table_Build (ST'Address, 23, EA'Address, 23);
27727
27728       --  Call Set_Globals to record various information for
27729       --  this partition.  The values are derived by the binder
27730       --  from information stored in the ali files by the compiler.
27731
27732 @findex __gnat_set_globals
27733       Set_Globals
27734         (Main_Priority            => -1,
27735          --  Priority of main program, -1 if no pragma Priority used
27736
27737          Time_Slice_Value         => -1,
27738          --  Time slice from Time_Slice pragma, -1 if none used
27739
27740          WC_Encoding              => 'b',
27741          --  Wide_Character encoding used, default is brackets
27742
27743          Locking_Policy           => ' ',
27744          --  Locking_Policy used, default of space means not
27745          --  specified, otherwise it is the first character of
27746          --  the policy name.
27747
27748          Queuing_Policy           => ' ',
27749          --  Queuing_Policy used, default of space means not
27750          --  specified, otherwise it is the first character of
27751          --  the policy name.
27752
27753          Task_Dispatching_Policy  => ' ',
27754          --  Task_Dispatching_Policy used, default of space means
27755          --  not specified, otherwise first character of the
27756          --  policy name.
27757
27758          Adafinal                 => System.Null_Address,
27759          --  Address of Adafinal routine, not used anymore
27760
27761          Unreserve_All_Interrupts => 0,
27762          --  Set true if pragma Unreserve_All_Interrupts was used
27763
27764          Exception_Tracebacks     => 0);
27765          --  Indicates if exception tracebacks are enabled
27766
27767       Elab_Final_Code := 1;
27768
27769       --  Now we have the elaboration calls for all units in the partition.
27770       --  The Elab_Spec and Elab_Body attributes generate references to the
27771       --  implicit elaboration procedures generated by the compiler for
27772       --  each unit that requires elaboration.
27773
27774       if not E040 then
27775          Interfaces.C_Streams'Elab_Spec;
27776       end if;
27777       E040 := True;
27778       if not E008 then
27779          Ada.Exceptions'Elab_Spec;
27780       end if;
27781       if not E014 then
27782          System.Exception_Table'Elab_Body;
27783          E014 := True;
27784       end if;
27785       if not E053 then
27786          Ada.Io_Exceptions'Elab_Spec;
27787          E053 := True;
27788       end if;
27789       if not E017 then
27790          System.Exceptions'Elab_Spec;
27791          E017 := True;
27792       end if;
27793       if not E030 then
27794          System.Stack_Checking'Elab_Spec;
27795       end if;
27796       if not E028 then
27797          System.Soft_Links'Elab_Body;
27798          E028 := True;
27799       end if;
27800       E030 := True;
27801       if not E024 then
27802          System.Secondary_Stack'Elab_Body;
27803          E024 := True;
27804       end if;
27805       if not E035 then
27806          Ada.Tags'Elab_Spec;
27807       end if;
27808       if not E035 then
27809          Ada.Tags'Elab_Body;
27810          E035 := True;
27811       end if;
27812       if not E033 then
27813          Ada.Streams'Elab_Spec;
27814          E033 := True;
27815       end if;
27816       if not E046 then
27817          System.Finalization_Root'Elab_Spec;
27818       end if;
27819       E046 := True;
27820       if not E008 then
27821          Ada.Exceptions'Elab_Body;
27822          E008 := True;
27823       end if;
27824       if not E048 then
27825          System.Finalization_Implementation'Elab_Spec;
27826       end if;
27827       if not E048 then
27828          System.Finalization_Implementation'Elab_Body;
27829          E048 := True;
27830       end if;
27831       if not E044 then
27832          Ada.Finalization'Elab_Spec;
27833       end if;
27834       E044 := True;
27835       if not E057 then
27836          Ada.Finalization.List_Controller'Elab_Spec;
27837       end if;
27838       E057 := True;
27839       if not E055 then
27840          System.File_Control_Block'Elab_Spec;
27841          E055 := True;
27842       end if;
27843       if not E042 then
27844          System.File_Io'Elab_Body;
27845          E042 := True;
27846       end if;
27847       if not E006 then
27848          Ada.Text_Io'Elab_Spec;
27849       end if;
27850       if not E006 then
27851          Ada.Text_Io'Elab_Body;
27852          E006 := True;
27853       end if;
27854
27855       Elab_Final_Code := 0;
27856    end adainit;
27857
27858    --------------
27859    -- adafinal --
27860    --------------
27861
27862 @findex adafinal
27863    procedure adafinal is
27864    begin
27865       Do_Finalize;
27866    end adafinal;
27867
27868    ----------
27869    -- main --
27870    ----------
27871
27872    --  main is actually a function, as in the ANSI C standard,
27873    --  defined to return the exit status. The three parameters
27874    --  are the argument count, argument values and environment
27875    --  pointer.
27876
27877 @findex Main Program
27878    function main
27879      (argc : Integer;
27880       argv : System.Address;
27881       envp : System.Address)
27882       return Integer
27883    is
27884       --  The initialize routine performs low level system
27885       --  initialization using a standard library routine which
27886       --  sets up signal handling and performs any other
27887       --  required setup. The routine can be found in file
27888       --  a-init.c.
27889
27890 @findex __gnat_initialize
27891       procedure initialize;
27892       pragma Import (C, initialize, "__gnat_initialize");
27893
27894       --  The finalize routine performs low level system
27895       --  finalization using a standard library routine. The
27896       --  routine is found in file a-final.c and in the standard
27897       --  distribution is a dummy routine that does nothing, so
27898       --  really this is a hook for special user finalization.
27899
27900 @findex __gnat_finalize
27901       procedure finalize;
27902       pragma Import (C, finalize, "__gnat_finalize");
27903
27904       --  We get to the main program of the partition by using
27905       --  pragma Import because if we try to with the unit and
27906       --  call it Ada style, then not only do we waste time
27907       --  recompiling it, but also, we don't really know the right
27908       --  switches (e.g.@: identifier character set) to be used
27909       --  to compile it.
27910
27911       procedure Ada_Main_Program;
27912       pragma Import (Ada, Ada_Main_Program, "_ada_hello");
27913
27914    --  Start of processing for main
27915
27916    begin
27917       --  Save global variables
27918
27919       gnat_argc := argc;
27920       gnat_argv := argv;
27921       gnat_envp := envp;
27922
27923       --  Call low level system initialization
27924
27925       Initialize;
27926
27927       --  Call our generated Ada initialization routine
27928
27929       adainit;
27930
27931       --  This is the point at which we want the debugger to get
27932       --  control
27933
27934       Break_Start;
27935
27936       --  Now we call the main program of the partition
27937
27938       Ada_Main_Program;
27939
27940       --  Perform Ada finalization
27941
27942       adafinal;
27943
27944       --  Perform low level system finalization
27945
27946       Finalize;
27947
27948       --  Return the proper exit status
27949       return (gnat_exit_status);
27950    end;
27951
27952 --  This section is entirely comments, so it has no effect on the
27953 --  compilation of the Ada_Main package. It provides the list of
27954 --  object files and linker options, as well as some standard
27955 --  libraries needed for the link. The gnatlink utility parses
27956 --  this b~hello.adb file to read these comment lines to generate
27957 --  the appropriate command line arguments for the call to the
27958 --  system linker. The BEGIN/END lines are used for sentinels for
27959 --  this parsing operation.
27960
27961 --  The exact file names will of course depend on the environment,
27962 --  host/target and location of files on the host system.
27963
27964 @findex Object file list
27965 -- BEGIN Object file/option list
27966    --   ./hello.o
27967    --   -L./
27968    --   -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
27969    --   /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
27970 -- END Object file/option list
27971
27972 end ada_main;
27973 @end smallexample
27974
27975 @noindent
27976 The Ada code in the above example is exactly what is generated by the
27977 binder. We have added comments to more clearly indicate the function
27978 of each part of the generated @code{Ada_Main} package.
27979
27980 The code is standard Ada in all respects, and can be processed by any
27981 tools that handle Ada. In particular, it is possible to use the debugger
27982 in Ada mode to debug the generated @code{Ada_Main} package. For example,
27983 suppose that for reasons that you do not understand, your program is crashing
27984 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
27985 you can place a breakpoint on the call:
27986
27987 @smallexample @c ada
27988 Ada.Text_Io'Elab_Body;
27989 @end smallexample
27990
27991 @noindent
27992 and trace the elaboration routine for this package to find out where
27993 the problem might be (more usually of course you would be debugging
27994 elaboration code in your own application).
27995
27996 @node Elaboration Order Handling in GNAT
27997 @appendix Elaboration Order Handling in GNAT
27998 @cindex Order of elaboration
27999 @cindex Elaboration control
28000
28001 @menu
28002 * Elaboration Code::
28003 * Checking the Elaboration Order::
28004 * Controlling the Elaboration Order::
28005 * Controlling Elaboration in GNAT - Internal Calls::
28006 * Controlling Elaboration in GNAT - External Calls::
28007 * Default Behavior in GNAT - Ensuring Safety::
28008 * Treatment of Pragma Elaborate::
28009 * Elaboration Issues for Library Tasks::
28010 * Mixing Elaboration Models::
28011 * What to Do If the Default Elaboration Behavior Fails::
28012 * Elaboration for Access-to-Subprogram Values::
28013 * Summary of Procedures for Elaboration Control::
28014 * Other Elaboration Order Considerations::
28015 @end menu
28016
28017 @noindent
28018 This chapter describes the handling of elaboration code in Ada and
28019 in GNAT, and discusses how the order of elaboration of program units can
28020 be controlled in GNAT, either automatically or with explicit programming
28021 features.
28022
28023 @node Elaboration Code
28024 @section Elaboration Code
28025
28026 @noindent
28027 Ada provides rather general mechanisms for executing code at elaboration
28028 time, that is to say before the main program starts executing. Such code arises
28029 in three contexts:
28030
28031 @table @asis
28032 @item Initializers for variables.
28033 Variables declared at the library level, in package specs or bodies, can
28034 require initialization that is performed at elaboration time, as in:
28035 @smallexample @c ada
28036 @cartouche
28037 Sqrt_Half : Float := Sqrt (0.5);
28038 @end cartouche
28039 @end smallexample
28040
28041 @item Package initialization code
28042 Code in a @code{BEGIN-END} section at the outer level of a package body is
28043 executed as part of the package body elaboration code.
28044
28045 @item Library level task allocators
28046 Tasks that are declared using task allocators at the library level
28047 start executing immediately and hence can execute at elaboration time.
28048 @end table
28049
28050 @noindent
28051 Subprogram calls are possible in any of these contexts, which means that
28052 any arbitrary part of the program may be executed as part of the elaboration
28053 code. It is even possible to write a program which does all its work at
28054 elaboration time, with a null main program, although stylistically this
28055 would usually be considered an inappropriate way to structure
28056 a program.
28057
28058 An important concern arises in the context of elaboration code:
28059 we have to be sure that it is executed in an appropriate order. What we
28060 have is a series of elaboration code sections, potentially one section
28061 for each unit in the program. It is important that these execute
28062 in the correct order. Correctness here means that, taking the above
28063 example of the declaration of @code{Sqrt_Half},
28064 if some other piece of
28065 elaboration code references @code{Sqrt_Half},
28066 then it must run after the
28067 section of elaboration code that contains the declaration of
28068 @code{Sqrt_Half}.
28069
28070 There would never be any order of elaboration problem if we made a rule
28071 that whenever you @code{with} a unit, you must elaborate both the spec and body
28072 of that unit before elaborating the unit doing the @code{with}'ing:
28073
28074 @smallexample @c ada
28075 @group
28076 @cartouche
28077 with Unit_1;
28078 package Unit_2 is @dots{}
28079 @end cartouche
28080 @end group
28081 @end smallexample
28082
28083 @noindent
28084 would require that both the body and spec of @code{Unit_1} be elaborated
28085 before the spec of @code{Unit_2}. However, a rule like that would be far too
28086 restrictive. In particular, it would make it impossible to have routines
28087 in separate packages that were mutually recursive.
28088
28089 You might think that a clever enough compiler could look at the actual
28090 elaboration code and determine an appropriate correct order of elaboration,
28091 but in the general case, this is not possible. Consider the following
28092 example.
28093
28094 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
28095 that references
28096 the variable @code{Sqrt_1}, which is declared in the elaboration code
28097 of the body of @code{Unit_1}:
28098
28099 @smallexample @c ada
28100 @cartouche
28101 Sqrt_1 : Float := Sqrt (0.1);
28102 @end cartouche
28103 @end smallexample
28104
28105 @noindent
28106 The elaboration code of the body of @code{Unit_1} also contains:
28107
28108 @smallexample @c ada
28109 @group
28110 @cartouche
28111 if expression_1 = 1 then
28112    Q := Unit_2.Func_2;
28113 end if;
28114 @end cartouche
28115 @end group
28116 @end smallexample
28117
28118 @noindent
28119 @code{Unit_2} is exactly parallel,
28120 it has a procedure @code{Func_2} that references
28121 the variable @code{Sqrt_2}, which is declared in the elaboration code of
28122 the body @code{Unit_2}:
28123
28124 @smallexample @c ada
28125 @cartouche
28126 Sqrt_2 : Float := Sqrt (0.1);
28127 @end cartouche
28128 @end smallexample
28129
28130 @noindent
28131 The elaboration code of the body of @code{Unit_2} also contains:
28132
28133 @smallexample @c ada
28134 @group
28135 @cartouche
28136 if expression_2 = 2 then
28137    Q := Unit_1.Func_1;
28138 end if;
28139 @end cartouche
28140 @end group
28141 @end smallexample
28142
28143 @noindent
28144 Now the question is, which of the following orders of elaboration is
28145 acceptable:
28146
28147 @smallexample
28148 @group
28149 Spec of Unit_1
28150 Spec of Unit_2
28151 Body of Unit_1
28152 Body of Unit_2
28153 @end group
28154 @end smallexample
28155
28156 @noindent
28157 or
28158
28159 @smallexample
28160 @group
28161 Spec of Unit_2
28162 Spec of Unit_1
28163 Body of Unit_2
28164 Body of Unit_1
28165 @end group
28166 @end smallexample
28167
28168 @noindent
28169 If you carefully analyze the flow here, you will see that you cannot tell
28170 at compile time the answer to this question.
28171 If @code{expression_1} is not equal to 1,
28172 and @code{expression_2} is not equal to 2,
28173 then either order is acceptable, because neither of the function calls is
28174 executed. If both tests evaluate to true, then neither order is acceptable
28175 and in fact there is no correct order.
28176
28177 If one of the two expressions is true, and the other is false, then one
28178 of the above orders is correct, and the other is incorrect. For example,
28179 if @code{expression_1} /= 1 and @code{expression_2} = 2,
28180 then the call to @code{Func_1}
28181 will occur, but not the call to @code{Func_2.}
28182 This means that it is essential
28183 to elaborate the body of @code{Unit_1} before
28184 the body of @code{Unit_2}, so the first
28185 order of elaboration is correct and the second is wrong.
28186
28187 By making @code{expression_1} and @code{expression_2}
28188 depend on input data, or perhaps
28189 the time of day, we can make it impossible for the compiler or binder
28190 to figure out which of these expressions will be true, and hence it
28191 is impossible to guarantee a safe order of elaboration at run time.
28192
28193 @node Checking the Elaboration Order
28194 @section Checking the Elaboration Order
28195
28196 @noindent
28197 In some languages that involve the same kind of elaboration problems,
28198 e.g.@: Java and C++, the programmer is expected to worry about these
28199 ordering problems himself, and it is common to
28200 write a program in which an incorrect elaboration order  gives
28201 surprising results, because it references variables before they
28202 are initialized.
28203 Ada is designed to be a safe language, and a programmer-beware approach is
28204 clearly not sufficient. Consequently, the language provides three lines
28205 of defense:
28206
28207 @table @asis
28208 @item Standard rules
28209 Some standard rules restrict the possible choice of elaboration
28210 order. In particular, if you @code{with} a unit, then its spec is always
28211 elaborated before the unit doing the @code{with}. Similarly, a parent
28212 spec is always elaborated before the child spec, and finally
28213 a spec is always elaborated before its corresponding body.
28214
28215 @item Dynamic elaboration checks
28216 @cindex Elaboration checks
28217 @cindex Checks, elaboration
28218 Dynamic checks are made at run time, so that if some entity is accessed
28219 before it is elaborated (typically  by means of a subprogram call)
28220 then the exception (@code{Program_Error}) is raised.
28221
28222 @item Elaboration control
28223 Facilities are provided for the programmer to specify the desired order
28224 of elaboration.
28225 @end table
28226
28227 Let's look at these facilities in more detail. First, the rules for
28228 dynamic checking. One possible rule would be simply to say that the
28229 exception is raised if you access a variable which has not yet been
28230 elaborated. The trouble with this approach is that it could require
28231 expensive checks on every variable reference. Instead Ada has two
28232 rules which are a little more restrictive, but easier to check, and
28233 easier to state:
28234
28235 @table @asis
28236 @item Restrictions on calls
28237 A subprogram can only be called at elaboration time if its body
28238 has been elaborated. The rules for elaboration given above guarantee
28239 that the spec of the subprogram has been elaborated before the
28240 call, but not the body. If this rule is violated, then the
28241 exception @code{Program_Error} is raised.
28242
28243 @item Restrictions on instantiations
28244 A generic unit can only be instantiated if the body of the generic
28245 unit has been elaborated. Again, the rules for elaboration given above
28246 guarantee that the spec of the generic unit has been elaborated
28247 before the instantiation, but not the body. If this rule is
28248 violated, then the exception @code{Program_Error} is raised.
28249 @end table
28250
28251 @noindent
28252 The idea is that if the body has been elaborated, then any variables
28253 it references must have been elaborated; by checking for the body being
28254 elaborated we guarantee that none of its references causes any
28255 trouble. As we noted above, this is a little too restrictive, because a
28256 subprogram that has no non-local references in its body may in fact be safe
28257 to call. However, it really would be unsafe to rely on this, because
28258 it would mean that the caller was aware of details of the implementation
28259 in the body. This goes against the basic tenets of Ada.
28260
28261 A plausible implementation can be described as follows.
28262 A Boolean variable is associated with each subprogram
28263 and each generic unit. This variable is initialized to False, and is set to
28264 True at the point body is elaborated. Every call or instantiation checks the
28265 variable, and raises @code{Program_Error} if the variable is False.
28266
28267 Note that one might think that it would be good enough to have one Boolean
28268 variable for each package, but that would not deal with cases of trying
28269 to call a body in the same package as the call
28270 that has not been elaborated yet.
28271 Of course a compiler may be able to do enough analysis to optimize away
28272 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
28273 does such optimizations, but still the easiest conceptual model is to
28274 think of there being one variable per subprogram.
28275
28276 @node Controlling the Elaboration Order
28277 @section Controlling the Elaboration Order
28278
28279 @noindent
28280 In the previous section we discussed the rules in Ada which ensure
28281 that @code{Program_Error} is raised if an incorrect elaboration order is
28282 chosen. This prevents erroneous executions, but we need mechanisms to
28283 specify a correct execution and avoid the exception altogether.
28284 To achieve this, Ada provides a number of features for controlling
28285 the order of elaboration. We discuss these features in this section.
28286
28287 First, there are several ways of indicating to the compiler that a given
28288 unit has no elaboration problems:
28289
28290 @table @asis
28291 @item packages that do not require a body
28292 A library package that does not require a body does not permit
28293 a body (this rule was introduced in Ada 95).
28294 Thus if we have a such a package, as in:
28295
28296 @smallexample @c ada
28297 @group
28298 @cartouche
28299 package Definitions is
28300    generic
28301       type m is new integer;
28302    package Subp is
28303       type a is array (1 .. 10) of m;
28304       type b is array (1 .. 20) of m;
28305    end Subp;
28306 end Definitions;
28307 @end cartouche
28308 @end group
28309 @end smallexample
28310
28311 @noindent
28312 A package that @code{with}'s @code{Definitions} may safely instantiate
28313 @code{Definitions.Subp} because the compiler can determine that there
28314 definitely is no package body to worry about in this case
28315
28316 @item pragma Pure
28317 @cindex pragma Pure
28318 @findex Pure
28319 Places sufficient restrictions on a unit to guarantee that
28320 no call to any subprogram in the unit can result in an
28321 elaboration problem. This means that the compiler does not need
28322 to worry about the point of elaboration of such units, and in
28323 particular, does not need to check any calls to any subprograms
28324 in this unit.
28325
28326 @item pragma Preelaborate
28327 @findex Preelaborate
28328 @cindex pragma Preelaborate
28329 This pragma places slightly less stringent restrictions on a unit than
28330 does pragma Pure,
28331 but these restrictions are still sufficient to ensure that there
28332 are no elaboration problems with any calls to the unit.
28333
28334 @item pragma Elaborate_Body
28335 @findex Elaborate_Body
28336 @cindex pragma Elaborate_Body
28337 This pragma requires that the body of a unit be elaborated immediately
28338 after its spec. Suppose a unit @code{A} has such a pragma,
28339 and unit @code{B} does
28340 a @code{with} of unit @code{A}. Recall that the standard rules require
28341 the spec of unit @code{A}
28342 to be elaborated before the @code{with}'ing unit; given the pragma in
28343 @code{A}, we also know that the body of @code{A}
28344 will be elaborated before @code{B}, so
28345 that calls to @code{A} are safe and do not need a check.
28346 @end table
28347
28348 @noindent
28349 Note that,
28350 unlike pragma @code{Pure} and pragma @code{Preelaborate},
28351 the use of
28352 @code{Elaborate_Body} does not guarantee that the program is
28353 free of elaboration problems, because it may not be possible
28354 to satisfy the requested elaboration order.
28355 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
28356 If a programmer
28357 marks @code{Unit_1} as @code{Elaborate_Body},
28358 and not @code{Unit_2,} then the order of
28359 elaboration will be:
28360
28361 @smallexample
28362 @group
28363 Spec of Unit_2
28364 Spec of Unit_1
28365 Body of Unit_1
28366 Body of Unit_2
28367 @end group
28368 @end smallexample
28369
28370 @noindent
28371 Now that means that the call to @code{Func_1} in @code{Unit_2}
28372 need not be checked,
28373 it must be safe. But the call to @code{Func_2} in
28374 @code{Unit_1} may still fail if
28375 @code{Expression_1} is equal to 1,
28376 and the programmer must still take
28377 responsibility for this not being the case.
28378
28379 If all units carry a pragma @code{Elaborate_Body}, then all problems are
28380 eliminated, except for calls entirely within a body, which are
28381 in any case fully under programmer control. However, using the pragma
28382 everywhere is not always possible.
28383 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
28384 we marked both of them as having pragma @code{Elaborate_Body}, then
28385 clearly there would be no possible elaboration order.
28386
28387 The above pragmas allow a server to guarantee safe use by clients, and
28388 clearly this is the preferable approach. Consequently a good rule
28389 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
28390 and if this is not possible,
28391 mark them as @code{Elaborate_Body} if possible.
28392 As we have seen, there are situations where neither of these
28393 three pragmas can be used.
28394 So we also provide methods for clients to control the
28395 order of elaboration of the servers on which they depend:
28396
28397 @table @asis
28398 @item pragma Elaborate (unit)
28399 @findex Elaborate
28400 @cindex pragma Elaborate
28401 This pragma is placed in the context clause, after a @code{with} clause,
28402 and it requires that the body of the named unit be elaborated before
28403 the unit in which the pragma occurs. The idea is to use this pragma
28404 if the current unit calls at elaboration time, directly or indirectly,
28405 some subprogram in the named unit.
28406
28407 @item pragma Elaborate_All (unit)
28408 @findex Elaborate_All
28409 @cindex pragma Elaborate_All
28410 This is a stronger version of the Elaborate pragma. Consider the
28411 following example:
28412
28413 @smallexample
28414 Unit A @code{with}'s unit B and calls B.Func in elab code
28415 Unit B @code{with}'s unit C, and B.Func calls C.Func
28416 @end smallexample
28417
28418 @noindent
28419 Now if we put a pragma @code{Elaborate (B)}
28420 in unit @code{A}, this ensures that the
28421 body of @code{B} is elaborated before the call, but not the
28422 body of @code{C}, so
28423 the call to @code{C.Func} could still cause @code{Program_Error} to
28424 be raised.
28425
28426 The effect of a pragma @code{Elaborate_All} is stronger, it requires
28427 not only that the body of the named unit be elaborated before the
28428 unit doing the @code{with}, but also the bodies of all units that the
28429 named unit uses, following @code{with} links transitively. For example,
28430 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
28431 then it requires
28432 not only that the body of @code{B} be elaborated before @code{A},
28433 but also the
28434 body of @code{C}, because @code{B} @code{with}'s @code{C}.
28435 @end table
28436
28437 @noindent
28438 We are now in a position to give a usage rule in Ada for avoiding
28439 elaboration problems, at least if dynamic dispatching and access to
28440 subprogram values are not used. We will handle these cases separately
28441 later.
28442
28443 The rule is simple. If a unit has elaboration code that can directly or
28444 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
28445 a generic package in a @code{with}'ed unit,
28446 then if the @code{with}'ed unit does not have
28447 pragma @code{Pure} or @code{Preelaborate}, then the client should have
28448 a pragma @code{Elaborate_All}
28449 for the @code{with}'ed unit. By following this rule a client is
28450 assured that calls can be made without risk of an exception.
28451
28452 For generic subprogram instantiations, the rule can be relaxed to
28453 require only a pragma @code{Elaborate} since elaborating the body
28454 of a subprogram cannot cause any transitive elaboration (we are
28455 not calling the subprogram in this case, just elaborating its
28456 declaration).
28457
28458 If this rule is not followed, then a program may be in one of four
28459 states:
28460
28461 @table @asis
28462 @item No order exists
28463 No order of elaboration exists which follows the rules, taking into
28464 account any @code{Elaborate}, @code{Elaborate_All},
28465 or @code{Elaborate_Body} pragmas. In
28466 this case, an Ada compiler must diagnose the situation at bind
28467 time, and refuse to build an executable program.
28468
28469 @item One or more orders exist, all incorrect
28470 One or more acceptable elaboration orders exist, and all of them
28471 generate an elaboration order problem. In this case, the binder
28472 can build an executable program, but @code{Program_Error} will be raised
28473 when the program is run.
28474
28475 @item Several orders exist, some right, some incorrect
28476 One or more acceptable elaboration orders exists, and some of them
28477 work, and some do not. The programmer has not controlled
28478 the order of elaboration, so the binder may or may not pick one of
28479 the correct orders, and the program may or may not raise an
28480 exception when it is run. This is the worst case, because it means
28481 that the program may fail when moved to another compiler, or even
28482 another version of the same compiler.
28483
28484 @item One or more orders exists, all correct
28485 One ore more acceptable elaboration orders exist, and all of them
28486 work. In this case the program runs successfully. This state of
28487 affairs can be guaranteed by following the rule we gave above, but
28488 may be true even if the rule is not followed.
28489 @end table
28490
28491 @noindent
28492 Note that one additional advantage of following our rules on the use
28493 of @code{Elaborate} and @code{Elaborate_All}
28494 is that the program continues to stay in the ideal (all orders OK) state
28495 even if maintenance
28496 changes some bodies of some units. Conversely, if a program that does
28497 not follow this rule happens to be safe at some point, this state of affairs
28498 may deteriorate silently as a result of maintenance changes.
28499
28500 You may have noticed that the above discussion did not mention
28501 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
28502 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
28503 code in the body makes calls to some other unit, so it is still necessary
28504 to use @code{Elaborate_All} on such units.
28505
28506 @node Controlling Elaboration in GNAT - Internal Calls
28507 @section Controlling Elaboration in GNAT - Internal Calls
28508
28509 @noindent
28510 In the case of internal calls, i.e., calls within a single package, the
28511 programmer has full control over the order of elaboration, and it is up
28512 to the programmer to elaborate declarations in an appropriate order. For
28513 example writing:
28514
28515 @smallexample @c ada
28516 @group
28517 @cartouche
28518 function One return Float;
28519
28520 Q : Float := One;
28521
28522 function One return Float is
28523 begin
28524      return 1.0;
28525 end One;
28526 @end cartouche
28527 @end group
28528 @end smallexample
28529
28530 @noindent
28531 will obviously raise @code{Program_Error} at run time, because function
28532 One will be called before its body is elaborated. In this case GNAT will
28533 generate a warning that the call will raise @code{Program_Error}:
28534
28535 @smallexample
28536 @group
28537 @cartouche
28538  1. procedure y is
28539  2.    function One return Float;
28540  3.
28541  4.    Q : Float := One;
28542                     |
28543     >>> warning: cannot call "One" before body is elaborated
28544     >>> warning: Program_Error will be raised at run time
28545
28546  5.
28547  6.    function One return Float is
28548  7.    begin
28549  8.         return 1.0;
28550  9.    end One;
28551 10.
28552 11. begin
28553 12.    null;
28554 13. end;
28555 @end cartouche
28556 @end group
28557 @end smallexample
28558
28559 @noindent
28560 Note that in this particular case, it is likely that the call is safe, because
28561 the function @code{One} does not access any global variables.
28562 Nevertheless in Ada, we do not want the validity of the check to depend on
28563 the contents of the body (think about the separate compilation case), so this
28564 is still wrong, as we discussed in the previous sections.
28565
28566 The error is easily corrected by rearranging the declarations so that the
28567 body of @code{One} appears before the declaration containing the call
28568 (note that in Ada 95 and Ada 2005,
28569 declarations can appear in any order, so there is no restriction that
28570 would prevent this reordering, and if we write:
28571
28572 @smallexample @c ada
28573 @group
28574 @cartouche
28575 function One return Float;
28576
28577 function One return Float is
28578 begin
28579      return 1.0;
28580 end One;
28581
28582 Q : Float := One;
28583 @end cartouche
28584 @end group
28585 @end smallexample
28586
28587 @noindent
28588 then all is well, no warning is generated, and no
28589 @code{Program_Error} exception
28590 will be raised.
28591 Things are more complicated when a chain of subprograms is executed:
28592
28593 @smallexample @c ada
28594 @group
28595 @cartouche
28596 function A return Integer;
28597 function B return Integer;
28598 function C return Integer;
28599
28600 function B return Integer is begin return A; end;
28601 function C return Integer is begin return B; end;
28602
28603 X : Integer := C;
28604
28605 function A return Integer is begin return 1; end;
28606 @end cartouche
28607 @end group
28608 @end smallexample
28609
28610 @noindent
28611 Now the call to @code{C}
28612 at elaboration time in the declaration of @code{X} is correct, because
28613 the body of @code{C} is already elaborated,
28614 and the call to @code{B} within the body of
28615 @code{C} is correct, but the call
28616 to @code{A} within the body of @code{B} is incorrect, because the body
28617 of @code{A} has not been elaborated, so @code{Program_Error}
28618 will be raised on the call to @code{A}.
28619 In this case GNAT will generate a
28620 warning that @code{Program_Error} may be
28621 raised at the point of the call. Let's look at the warning:
28622
28623 @smallexample
28624 @group
28625 @cartouche
28626  1. procedure x is
28627  2.    function A return Integer;
28628  3.    function B return Integer;
28629  4.    function C return Integer;
28630  5.
28631  6.    function B return Integer is begin return A; end;
28632                                                     |
28633     >>> warning: call to "A" before body is elaborated may
28634                  raise Program_Error
28635     >>> warning: "B" called at line 7
28636     >>> warning: "C" called at line 9
28637
28638  7.    function C return Integer is begin return B; end;
28639  8.
28640  9.    X : Integer := C;
28641 10.
28642 11.    function A return Integer is begin return 1; end;
28643 12.
28644 13. begin
28645 14.    null;
28646 15. end;
28647 @end cartouche
28648 @end group
28649 @end smallexample
28650
28651 @noindent
28652 Note that the message here says ``may raise'', instead of the direct case,
28653 where the message says ``will be raised''. That's because whether
28654 @code{A} is
28655 actually called depends in general on run-time flow of control.
28656 For example, if the body of @code{B} said
28657
28658 @smallexample @c ada
28659 @group
28660 @cartouche
28661 function B return Integer is
28662 begin
28663    if some-condition-depending-on-input-data then
28664       return A;
28665    else
28666       return 1;
28667    end if;
28668 end B;
28669 @end cartouche
28670 @end group
28671 @end smallexample
28672
28673 @noindent
28674 then we could not know until run time whether the incorrect call to A would
28675 actually occur, so @code{Program_Error} might
28676 or might not be raised. It is possible for a compiler to
28677 do a better job of analyzing bodies, to
28678 determine whether or not @code{Program_Error}
28679 might be raised, but it certainly
28680 couldn't do a perfect job (that would require solving the halting problem
28681 and is provably impossible), and because this is a warning anyway, it does
28682 not seem worth the effort to do the analysis. Cases in which it
28683 would be relevant are rare.
28684
28685 In practice, warnings of either of the forms given
28686 above will usually correspond to
28687 real errors, and should be examined carefully and eliminated.
28688 In the rare case where a warning is bogus, it can be suppressed by any of
28689 the following methods:
28690
28691 @itemize @bullet
28692 @item
28693 Compile with the @option{-gnatws} switch set
28694
28695 @item
28696 Suppress @code{Elaboration_Check} for the called subprogram
28697
28698 @item
28699 Use pragma @code{Warnings_Off} to turn warnings off for the call
28700 @end itemize
28701
28702 @noindent
28703 For the internal elaboration check case,
28704 GNAT by default generates the
28705 necessary run-time checks to ensure
28706 that @code{Program_Error} is raised if any
28707 call fails an elaboration check. Of course this can only happen if a
28708 warning has been issued as described above. The use of pragma
28709 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
28710 some of these checks, meaning that it may be possible (but is not
28711 guaranteed) for a program to be able to call a subprogram whose body
28712 is not yet elaborated, without raising a @code{Program_Error} exception.
28713
28714 @node Controlling Elaboration in GNAT - External Calls
28715 @section Controlling Elaboration in GNAT - External Calls
28716
28717 @noindent
28718 The previous section discussed the case in which the execution of a
28719 particular thread of elaboration code occurred entirely within a
28720 single unit. This is the easy case to handle, because a programmer
28721 has direct and total control over the order of elaboration, and
28722 furthermore, checks need only be generated in cases which are rare
28723 and which the compiler can easily detect.
28724 The situation is more complex when separate compilation is taken into account.
28725 Consider the following:
28726
28727 @smallexample @c ada
28728 @cartouche
28729 @group
28730 package Math is
28731    function Sqrt (Arg : Float) return Float;
28732 end Math;
28733
28734 package body Math is
28735    function Sqrt (Arg : Float) return Float is
28736    begin
28737          @dots{}
28738    end Sqrt;
28739 end Math;
28740 @end group
28741 @group
28742 with Math;
28743 package Stuff is
28744    X : Float := Math.Sqrt (0.5);
28745 end Stuff;
28746
28747 with Stuff;
28748 procedure Main is
28749 begin
28750    @dots{}
28751 end Main;
28752 @end group
28753 @end cartouche
28754 @end smallexample
28755
28756 @noindent
28757 where @code{Main} is the main program. When this program is executed, the
28758 elaboration code must first be executed, and one of the jobs of the
28759 binder is to determine the order in which the units of a program are
28760 to be elaborated. In this case we have four units: the spec and body
28761 of @code{Math},
28762 the spec of @code{Stuff} and the body of @code{Main}).
28763 In what order should the four separate sections of elaboration code
28764 be executed?
28765
28766 There are some restrictions in the order of elaboration that the binder
28767 can choose. In particular, if unit U has a @code{with}
28768 for a package @code{X}, then you
28769 are assured that the spec of @code{X}
28770 is elaborated before U , but you are
28771 not assured that the body of @code{X}
28772 is elaborated before U.
28773 This means that in the above case, the binder is allowed to choose the
28774 order:
28775
28776 @smallexample
28777 spec of Math
28778 spec of Stuff
28779 body of Math
28780 body of Main
28781 @end smallexample
28782
28783 @noindent
28784 but that's not good, because now the call to @code{Math.Sqrt}
28785 that happens during
28786 the elaboration of the @code{Stuff}
28787 spec happens before the body of @code{Math.Sqrt} is
28788 elaborated, and hence causes @code{Program_Error} exception to be raised.
28789 At first glance, one might say that the binder is misbehaving, because
28790 obviously you want to elaborate the body of something you @code{with}
28791 first, but
28792 that is not a general rule that can be followed in all cases. Consider
28793
28794 @smallexample @c ada
28795 @group
28796 @cartouche
28797 package X is @dots{}
28798
28799 package Y is @dots{}
28800
28801 with X;
28802 package body Y is @dots{}
28803
28804 with Y;
28805 package body X is @dots{}
28806 @end cartouche
28807 @end group
28808 @end smallexample
28809
28810 @noindent
28811 This is a common arrangement, and, apart from the order of elaboration
28812 problems that might arise in connection with elaboration code, this works fine.
28813 A rule that says that you must first elaborate the body of anything you
28814 @code{with} cannot work in this case:
28815 the body of @code{X} @code{with}'s @code{Y},
28816 which means you would have to
28817 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
28818 which means
28819 you have to elaborate the body of @code{X} first, but @dots{} and we have a
28820 loop that cannot be broken.
28821
28822 It is true that the binder can in many cases guess an order of elaboration
28823 that is unlikely to cause a @code{Program_Error}
28824 exception to be raised, and it tries to do so (in the
28825 above example of @code{Math/Stuff/Spec}, the GNAT binder will
28826 by default
28827 elaborate the body of @code{Math} right after its spec, so all will be well).
28828
28829 However, a program that blindly relies on the binder to be helpful can
28830 get into trouble, as we discussed in the previous sections, so
28831 GNAT
28832 provides a number of facilities for assisting the programmer in
28833 developing programs that are robust with respect to elaboration order.
28834
28835 @node Default Behavior in GNAT - Ensuring Safety
28836 @section Default Behavior in GNAT - Ensuring Safety
28837
28838 @noindent
28839 The default behavior in GNAT ensures elaboration safety. In its
28840 default mode GNAT implements the
28841 rule we previously described as the right approach. Let's restate it:
28842
28843 @itemize
28844 @item
28845 @emph{If a unit has elaboration code that can directly or indirectly make a
28846 call to a subprogram in a @code{with}'ed unit, or instantiate a generic
28847 package in a @code{with}'ed unit, then if the @code{with}'ed unit
28848 does not have pragma @code{Pure} or
28849 @code{Preelaborate}, then the client should have an
28850 @code{Elaborate_All} pragma for the @code{with}'ed unit.}
28851
28852 @emph{In the case of instantiating a generic subprogram, it is always
28853 sufficient to have only an @code{Elaborate} pragma for the
28854 @code{with}'ed unit.}
28855 @end itemize
28856
28857 @noindent
28858 By following this rule a client is assured that calls and instantiations
28859 can be made without risk of an exception.
28860
28861 In this mode GNAT traces all calls that are potentially made from
28862 elaboration code, and puts in any missing implicit @code{Elaborate}
28863 and @code{Elaborate_All} pragmas.
28864 The advantage of this approach is that no elaboration problems
28865 are possible if the binder can find an elaboration order that is
28866 consistent with these implicit @code{Elaborate} and
28867 @code{Elaborate_All} pragmas. The
28868 disadvantage of this approach is that no such order may exist.
28869
28870 If the binder does not generate any diagnostics, then it means that it has
28871 found an elaboration order that is guaranteed to be safe. However, the binder
28872 may still be relying on implicitly generated @code{Elaborate} and
28873 @code{Elaborate_All} pragmas so portability to other compilers than GNAT is not
28874 guaranteed.
28875
28876 If it is important to guarantee portability, then the compilations should
28877 use the
28878 @option{-gnatwl}
28879 (warn on elaboration problems) switch. This will cause warning messages
28880 to be generated indicating the missing @code{Elaborate} and
28881 @code{Elaborate_All} pragmas.
28882 Consider the following source program:
28883
28884 @smallexample @c ada
28885 @group
28886 @cartouche
28887 with k;
28888 package j is
28889   m : integer := k.r;
28890 end;
28891 @end cartouche
28892 @end group
28893 @end smallexample
28894
28895 @noindent
28896 where it is clear that there
28897 should be a pragma @code{Elaborate_All}
28898 for unit @code{k}. An implicit pragma will be generated, and it is
28899 likely that the binder will be able to honor it. However, if you want
28900 to port this program to some other Ada compiler than GNAT.
28901 it is safer to include the pragma explicitly in the source. If this
28902 unit is compiled with the
28903 @option{-gnatwl}
28904 switch, then the compiler outputs a warning:
28905
28906 @smallexample
28907 @group
28908 @cartouche
28909 1. with k;
28910 2. package j is
28911 3.   m : integer := k.r;
28912                      |
28913    >>> warning: call to "r" may raise Program_Error
28914    >>> warning: missing pragma Elaborate_All for "k"
28915
28916 4. end;
28917 @end cartouche
28918 @end group
28919 @end smallexample
28920
28921 @noindent
28922 and these warnings can be used as a guide for supplying manually
28923 the missing pragmas. It is usually a bad idea to use this warning
28924 option during development. That's because it will warn you when
28925 you need to put in a pragma, but cannot warn you when it is time
28926 to take it out. So the use of pragma @code{Elaborate_All} may lead to
28927 unnecessary dependencies and even false circularities.
28928
28929 This default mode is more restrictive than the Ada Reference
28930 Manual, and it is possible to construct programs which will compile
28931 using the dynamic model described there, but will run into a
28932 circularity using the safer static model we have described.
28933
28934 Of course any Ada compiler must be able to operate in a mode
28935 consistent with the requirements of the Ada Reference Manual,
28936 and in particular must have the capability of implementing the
28937 standard dynamic model of elaboration with run-time checks.
28938
28939 In GNAT, this standard mode can be achieved either by the use of
28940 the @option{-gnatE} switch on the compiler (@command{gcc} or
28941 @command{gnatmake}) command, or by the use of the configuration pragma:
28942
28943 @smallexample @c ada
28944 pragma Elaboration_Checks (DYNAMIC);
28945 @end smallexample
28946
28947 @noindent
28948 Either approach will cause the unit affected to be compiled using the
28949 standard dynamic run-time elaboration checks described in the Ada
28950 Reference Manual. The static model is generally preferable, since it
28951 is clearly safer to rely on compile and link time checks rather than
28952 run-time checks. However, in the case of legacy code, it may be
28953 difficult to meet the requirements of the static model. This
28954 issue is further discussed in
28955 @ref{What to Do If the Default Elaboration Behavior Fails}.
28956
28957 Note that the static model provides a strict subset of the allowed
28958 behavior and programs of the Ada Reference Manual, so if you do
28959 adhere to the static model and no circularities exist,
28960 then you are assured that your program will
28961 work using the dynamic model, providing that you remove any
28962 pragma Elaborate statements from the source.
28963
28964 @node Treatment of Pragma Elaborate
28965 @section Treatment of Pragma Elaborate
28966 @cindex Pragma Elaborate
28967
28968 @noindent
28969 The use of @code{pragma Elaborate}
28970 should generally be avoided in Ada 95 and Ada 2005 programs,
28971 since there is no guarantee that transitive calls
28972 will be properly handled. Indeed at one point, this pragma was placed
28973 in Annex J (Obsolescent Features), on the grounds that it is never useful.
28974
28975 Now that's a bit restrictive. In practice, the case in which
28976 @code{pragma Elaborate} is useful is when the caller knows that there
28977 are no transitive calls, or that the called unit contains all necessary
28978 transitive @code{pragma Elaborate} statements, and legacy code often
28979 contains such uses.
28980
28981 Strictly speaking the static mode in GNAT should ignore such pragmas,
28982 since there is no assurance at compile time that the necessary safety
28983 conditions are met. In practice, this would cause GNAT to be incompatible
28984 with correctly written Ada 83 code that had all necessary
28985 @code{pragma Elaborate} statements in place. Consequently, we made the
28986 decision that GNAT in its default mode will believe that if it encounters
28987 a @code{pragma Elaborate} then the programmer knows what they are doing,
28988 and it will trust that no elaboration errors can occur.
28989
28990 The result of this decision is two-fold. First to be safe using the
28991 static mode, you should remove all @code{pragma Elaborate} statements.
28992 Second, when fixing circularities in existing code, you can selectively
28993 use @code{pragma Elaborate} statements to convince the static mode of
28994 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
28995 statement.
28996
28997 When using the static mode with @option{-gnatwl}, any use of
28998 @code{pragma Elaborate} will generate a warning about possible
28999 problems.
29000
29001 @node Elaboration Issues for Library Tasks
29002 @section Elaboration Issues for Library Tasks
29003 @cindex Library tasks, elaboration issues
29004 @cindex Elaboration of library tasks
29005
29006 @noindent
29007 In this section we examine special elaboration issues that arise for
29008 programs that declare library level tasks.
29009
29010 Generally the model of execution of an Ada program is that all units are
29011 elaborated, and then execution of the program starts. However, the
29012 declaration of library tasks definitely does not fit this model. The
29013 reason for this is that library tasks start as soon as they are declared
29014 (more precisely, as soon as the statement part of the enclosing package
29015 body is reached), that is to say before elaboration
29016 of the program is complete. This means that if such a task calls a
29017 subprogram, or an entry in another task, the callee may or may not be
29018 elaborated yet, and in the standard
29019 Reference Manual model of dynamic elaboration checks, you can even
29020 get timing dependent Program_Error exceptions, since there can be
29021 a race between the elaboration code and the task code.
29022
29023 The static model of elaboration in GNAT seeks to avoid all such
29024 dynamic behavior, by being conservative, and the conservative
29025 approach in this particular case is to assume that all the code
29026 in a task body is potentially executed at elaboration time if
29027 a task is declared at the library level.
29028
29029 This can definitely result in unexpected circularities. Consider
29030 the following example
29031
29032 @smallexample @c ada
29033 package Decls is
29034   task Lib_Task is
29035      entry Start;
29036   end Lib_Task;
29037
29038   type My_Int is new Integer;
29039
29040   function Ident (M : My_Int) return My_Int;
29041 end Decls;
29042
29043 with Utils;
29044 package body Decls is
29045   task body Lib_Task is
29046   begin
29047      accept Start;
29048      Utils.Put_Val (2);
29049   end Lib_Task;
29050
29051   function Ident (M : My_Int) return My_Int is
29052   begin
29053      return M;
29054   end Ident;
29055 end Decls;
29056
29057 with Decls;
29058 package Utils is
29059   procedure Put_Val (Arg : Decls.My_Int);
29060 end Utils;
29061
29062 with Text_IO;
29063 package body Utils is
29064   procedure Put_Val (Arg : Decls.My_Int) is
29065   begin
29066      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
29067   end Put_Val;
29068 end Utils;
29069
29070 with Decls;
29071 procedure Main is
29072 begin
29073    Decls.Lib_Task.Start;
29074 end;
29075 @end smallexample
29076
29077 @noindent
29078 If the above example is compiled in the default static elaboration
29079 mode, then a circularity occurs. The circularity comes from the call
29080 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
29081 this call occurs in elaboration code, we need an implicit pragma
29082 @code{Elaborate_All} for @code{Utils}. This means that not only must
29083 the spec and body of @code{Utils} be elaborated before the body
29084 of @code{Decls}, but also the spec and body of any unit that is
29085 @code{with'ed} by the body of @code{Utils} must also be elaborated before
29086 the body of @code{Decls}. This is the transitive implication of
29087 pragma @code{Elaborate_All} and it makes sense, because in general
29088 the body of @code{Put_Val} might have a call to something in a
29089 @code{with'ed} unit.
29090
29091 In this case, the body of Utils (actually its spec) @code{with's}
29092 @code{Decls}. Unfortunately this means that the body of @code{Decls}
29093 must be elaborated before itself, in case there is a call from the
29094 body of @code{Utils}.
29095
29096 Here is the exact chain of events we are worrying about:
29097
29098 @enumerate
29099 @item
29100 In the body of @code{Decls} a call is made from within the body of a library
29101 task to a subprogram in the package @code{Utils}. Since this call may
29102 occur at elaboration time (given that the task is activated at elaboration
29103 time), we have to assume the worst, i.e., that the
29104 call does happen at elaboration time.
29105
29106 @item
29107 This means that the body and spec of @code{Util} must be elaborated before
29108 the body of @code{Decls} so that this call does not cause an access before
29109 elaboration.
29110
29111 @item
29112 Within the body of @code{Util}, specifically within the body of
29113 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
29114 by this package.
29115
29116 @item
29117 One such @code{with}'ed package is package @code{Decls}, so there
29118 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
29119 In fact there is such a call in this example, but we would have to
29120 assume that there was such a call even if it were not there, since
29121 we are not supposed to write the body of @code{Decls} knowing what
29122 is in the body of @code{Utils}; certainly in the case of the
29123 static elaboration model, the compiler does not know what is in
29124 other bodies and must assume the worst.
29125
29126 @item
29127 This means that the spec and body of @code{Decls} must also be
29128 elaborated before we elaborate the unit containing the call, but
29129 that unit is @code{Decls}! This means that the body of @code{Decls}
29130 must be elaborated before itself, and that's a circularity.
29131 @end enumerate
29132
29133 @noindent
29134 Indeed, if you add an explicit pragma @code{Elaborate_All} for @code{Utils} in
29135 the body of @code{Decls} you will get a true Ada Reference Manual
29136 circularity that makes the program illegal.
29137
29138 In practice, we have found that problems with the static model of
29139 elaboration in existing code often arise from library tasks, so
29140 we must address this particular situation.
29141
29142 Note that if we compile and run the program above, using the dynamic model of
29143 elaboration (that is to say use the @option{-gnatE} switch),
29144 then it compiles, binds,
29145 links, and runs, printing the expected result of 2. Therefore in some sense
29146 the circularity here is only apparent, and we need to capture
29147 the properties of this program that  distinguish it from other library-level
29148 tasks that have real elaboration problems.
29149
29150 We have four possible answers to this question:
29151
29152 @itemize @bullet
29153
29154 @item
29155 Use the dynamic model of elaboration.
29156
29157 If we use the @option{-gnatE} switch, then as noted above, the program works.
29158 Why is this? If we examine the task body, it is apparent that the task cannot
29159 proceed past the
29160 @code{accept} statement until after elaboration has been completed, because
29161 the corresponding entry call comes from the main program, not earlier.
29162 This is why the dynamic model works here. But that's really giving
29163 up on a precise analysis, and we prefer to take this approach only if we cannot
29164 solve the
29165 problem in any other manner. So let us examine two ways to reorganize
29166 the program to avoid the potential elaboration problem.
29167
29168 @item
29169 Split library tasks into separate packages.
29170
29171 Write separate packages, so that library tasks are isolated from
29172 other declarations as much as possible. Let us look at a variation on
29173 the above program.
29174
29175 @smallexample @c ada
29176 package Decls1 is
29177   task Lib_Task is
29178      entry Start;
29179   end Lib_Task;
29180 end Decls1;
29181
29182 with Utils;
29183 package body Decls1 is
29184   task body Lib_Task is
29185   begin
29186      accept Start;
29187      Utils.Put_Val (2);
29188   end Lib_Task;
29189 end Decls1;
29190
29191 package Decls2 is
29192   type My_Int is new Integer;
29193   function Ident (M : My_Int) return My_Int;
29194 end Decls2;
29195
29196 with Utils;
29197 package body Decls2 is
29198   function Ident (M : My_Int) return My_Int is
29199   begin
29200      return M;
29201   end Ident;
29202 end Decls2;
29203
29204 with Decls2;
29205 package Utils is
29206   procedure Put_Val (Arg : Decls2.My_Int);
29207 end Utils;
29208
29209 with Text_IO;
29210 package body Utils is
29211   procedure Put_Val (Arg : Decls2.My_Int) is
29212   begin
29213      Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
29214   end Put_Val;
29215 end Utils;
29216
29217 with Decls1;
29218 procedure Main is
29219 begin
29220    Decls1.Lib_Task.Start;
29221 end;
29222 @end smallexample
29223
29224 @noindent
29225 All we have done is to split @code{Decls} into two packages, one
29226 containing the library task, and one containing everything else. Now
29227 there is no cycle, and the program compiles, binds, links and executes
29228 using the default static model of elaboration.
29229
29230 @item
29231 Declare separate task types.
29232
29233 A significant part of the problem arises because of the use of the
29234 single task declaration form. This means that the elaboration of
29235 the task type, and the elaboration of the task itself (i.e.@: the
29236 creation of the task) happen at the same time. A good rule
29237 of style in Ada is to always create explicit task types. By
29238 following the additional step of placing task objects in separate
29239 packages from the task type declaration, many elaboration problems
29240 are avoided. Here is another modified example of the example program:
29241
29242 @smallexample @c ada
29243 package Decls is
29244   task type Lib_Task_Type is
29245      entry Start;
29246   end Lib_Task_Type;
29247
29248   type My_Int is new Integer;
29249
29250   function Ident (M : My_Int) return My_Int;
29251 end Decls;
29252
29253 with Utils;
29254 package body Decls is
29255   task body Lib_Task_Type is
29256   begin
29257      accept Start;
29258      Utils.Put_Val (2);
29259   end Lib_Task_Type;
29260
29261   function Ident (M : My_Int) return My_Int is
29262   begin
29263      return M;
29264   end Ident;
29265 end Decls;
29266
29267 with Decls;
29268 package Utils is
29269   procedure Put_Val (Arg : Decls.My_Int);
29270 end Utils;
29271
29272 with Text_IO;
29273 package body Utils is
29274   procedure Put_Val (Arg : Decls.My_Int) is
29275   begin
29276      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
29277   end Put_Val;
29278 end Utils;
29279
29280 with Decls;
29281 package Declst is
29282    Lib_Task : Decls.Lib_Task_Type;
29283 end Declst;
29284
29285 with Declst;
29286 procedure Main is
29287 begin
29288    Declst.Lib_Task.Start;
29289 end;
29290 @end smallexample
29291
29292 @noindent
29293 What we have done here is to replace the @code{task} declaration in
29294 package @code{Decls} with a @code{task type} declaration. Then we
29295 introduce a separate package @code{Declst} to contain the actual
29296 task object. This separates the elaboration issues for
29297 the @code{task type}
29298 declaration, which causes no trouble, from the elaboration issues
29299 of the task object, which is also unproblematic, since it is now independent
29300 of the elaboration of  @code{Utils}.
29301 This separation of concerns also corresponds to
29302 a generally sound engineering principle of separating declarations
29303 from instances. This version of the program also compiles, binds, links,
29304 and executes, generating the expected output.
29305
29306 @item
29307 Use No_Entry_Calls_In_Elaboration_Code restriction.
29308 @cindex No_Entry_Calls_In_Elaboration_Code
29309
29310 The previous two approaches described how a program can be restructured
29311 to avoid the special problems caused by library task bodies. in practice,
29312 however, such restructuring may be difficult to apply to existing legacy code,
29313 so we must consider solutions that do not require massive rewriting.
29314
29315 Let us consider more carefully why our original sample program works
29316 under the dynamic model of elaboration. The reason is that the code
29317 in the task body blocks immediately on the @code{accept}
29318 statement. Now of course there is nothing to prohibit elaboration
29319 code from making entry calls (for example from another library level task),
29320 so we cannot tell in isolation that
29321 the task will not execute the accept statement  during elaboration.
29322
29323 However, in practice it is very unusual to see elaboration code
29324 make any entry calls, and the pattern of tasks starting
29325 at elaboration time and then immediately blocking on @code{accept} or
29326 @code{select} statements is very common. What this means is that
29327 the compiler is being too pessimistic when it analyzes the
29328 whole package body as though it might be executed at elaboration
29329 time.
29330
29331 If we know that the elaboration code contains no entry calls, (a very safe
29332 assumption most of the time, that could almost be made the default
29333 behavior), then we can compile all units of the program under control
29334 of the following configuration pragma:
29335
29336 @smallexample
29337 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
29338 @end smallexample
29339
29340 @noindent
29341 This pragma can be placed in the @file{gnat.adc} file in the usual
29342 manner. If we take our original unmodified program and compile it
29343 in the presence of a @file{gnat.adc} containing the above pragma,
29344 then once again, we can compile, bind, link, and execute, obtaining
29345 the expected result. In the presence of this pragma, the compiler does
29346 not trace calls in a task body, that appear after the first @code{accept}
29347 or @code{select} statement, and therefore does not report a potential
29348 circularity in the original program.
29349
29350 The compiler will check to the extent it can that the above
29351 restriction is not violated, but it is not always possible to do a
29352 complete check at compile time, so it is important to use this
29353 pragma only if the stated restriction is in fact met, that is to say
29354 no task receives an entry call before elaboration of all units is completed.
29355
29356 @end itemize
29357
29358 @node Mixing Elaboration Models
29359 @section Mixing Elaboration Models
29360 @noindent
29361 So far, we have assumed that the entire program is either compiled
29362 using the dynamic model or static model, ensuring consistency. It
29363 is possible to mix the two models, but rules have to be followed
29364 if this mixing is done to ensure that elaboration checks are not
29365 omitted.
29366
29367 The basic rule is that @emph{a unit compiled with the static model cannot
29368 be @code{with'ed} by a unit compiled with the dynamic model}. The
29369 reason for this is that in the static model, a unit assumes that
29370 its clients guarantee to use (the equivalent of) pragma
29371 @code{Elaborate_All} so that no elaboration checks are required
29372 in inner subprograms, and this assumption is violated if the
29373 client is compiled with dynamic checks.
29374
29375 The precise rule is as follows. A unit that is compiled with dynamic
29376 checks can only @code{with} a unit that meets at least one of the
29377 following criteria:
29378
29379 @itemize @bullet
29380
29381 @item
29382 The @code{with'ed} unit is itself compiled with dynamic elaboration
29383 checks (that is with the @option{-gnatE} switch.
29384
29385 @item
29386 The @code{with'ed} unit is an internal GNAT implementation unit from
29387 the System, Interfaces, Ada, or GNAT hierarchies.
29388
29389 @item
29390 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
29391
29392 @item
29393 The @code{with'ing} unit (that is the client) has an explicit pragma
29394 @code{Elaborate_All} for the @code{with'ed} unit.
29395
29396 @end itemize
29397
29398 @noindent
29399 If this rule is violated, that is if a unit with dynamic elaboration
29400 checks @code{with's} a unit that does not meet one of the above four
29401 criteria, then the binder (@code{gnatbind}) will issue a warning
29402 similar to that in the following example:
29403
29404 @smallexample
29405 warning: "x.ads" has dynamic elaboration checks and with's
29406 warning:   "y.ads" which has static elaboration checks
29407 @end smallexample
29408
29409 @noindent
29410 These warnings indicate that the rule has been violated, and that as a result
29411 elaboration checks may be missed in the resulting executable file.
29412 This warning may be suppressed using the @option{-ws} binder switch
29413 in the usual manner.
29414
29415 One useful application of this mixing rule is in the case of a subsystem
29416 which does not itself @code{with} units from the remainder of the
29417 application. In this case, the entire subsystem can be compiled with
29418 dynamic checks to resolve a circularity in the subsystem, while
29419 allowing the main application that uses this subsystem to be compiled
29420 using the more reliable default static model.
29421
29422 @node What to Do If the Default Elaboration Behavior Fails
29423 @section What to Do If the Default Elaboration Behavior Fails
29424
29425 @noindent
29426 If the binder cannot find an acceptable order, it outputs detailed
29427 diagnostics. For example:
29428 @smallexample
29429 @group
29430 @iftex
29431 @leftskip=0cm
29432 @end iftex
29433 error: elaboration circularity detected
29434 info:   "proc (body)" must be elaborated before "pack (body)"
29435 info:     reason: Elaborate_All probably needed in unit "pack (body)"
29436 info:     recompile "pack (body)" with -gnatwl
29437 info:                             for full details
29438 info:       "proc (body)"
29439 info:         is needed by its spec:
29440 info:       "proc (spec)"
29441 info:         which is withed by:
29442 info:       "pack (body)"
29443 info:  "pack (body)" must be elaborated before "proc (body)"
29444 info:     reason: pragma Elaborate in unit "proc (body)"
29445 @end group
29446
29447 @end smallexample
29448
29449 @noindent
29450 In this case we have a cycle that the binder cannot break. On the one
29451 hand, there is an explicit pragma Elaborate in @code{proc} for
29452 @code{pack}. This means that the body of @code{pack} must be elaborated
29453 before the body of @code{proc}. On the other hand, there is elaboration
29454 code in @code{pack} that calls a subprogram in @code{proc}. This means
29455 that for maximum safety, there should really be a pragma
29456 Elaborate_All in @code{pack} for @code{proc} which would require that
29457 the body of @code{proc} be elaborated before the body of
29458 @code{pack}. Clearly both requirements cannot be satisfied.
29459 Faced with a circularity of this kind, you have three different options.
29460
29461 @table @asis
29462 @item Fix the program
29463 The most desirable option from the point of view of long-term maintenance
29464 is to rearrange the program so that the elaboration problems are avoided.
29465 One useful technique is to place the elaboration code into separate
29466 child packages. Another is to move some of the initialization code to
29467 explicitly called subprograms, where the program controls the order
29468 of initialization explicitly. Although this is the most desirable option,
29469 it may be impractical and involve too much modification, especially in
29470 the case of complex legacy code.
29471
29472 @item Perform dynamic checks
29473 If the compilations are done using the
29474 @option{-gnatE}
29475 (dynamic elaboration check) switch, then GNAT behaves in a quite different
29476 manner. Dynamic checks are generated for all calls that could possibly result
29477 in raising an exception. With this switch, the compiler does not generate
29478 implicit @code{Elaborate} or @code{Elaborate_All} pragmas. The behavior then is
29479 exactly as specified in the @cite{Ada Reference Manual}.
29480 The binder will generate
29481 an executable program that may or may not raise @code{Program_Error}, and then
29482 it is the programmer's job to ensure that it does not raise an exception. Note
29483 that it is important to compile all units with the switch, it cannot be used
29484 selectively.
29485
29486 @item Suppress checks
29487 The drawback of dynamic checks is that they generate a
29488 significant overhead at run time, both in space and time. If you
29489 are absolutely sure that your program cannot raise any elaboration
29490 exceptions, and you still want to use the dynamic elaboration model,
29491 then you can use the configuration pragma
29492 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
29493 example this pragma could be placed in the @file{gnat.adc} file.
29494
29495 @item Suppress checks selectively
29496 When you know that certain calls or instantiations in elaboration code cannot
29497 possibly lead to an elaboration error, and the binder nevertheless complains
29498 about implicit @code{Elaborate} and @code{Elaborate_All} pragmas that lead to
29499 elaboration circularities, it is possible to remove those warnings locally and
29500 obtain a program that will bind. Clearly this can be unsafe, and it is the
29501 responsibility of the programmer to make sure that the resulting program has no
29502 elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can be
29503 used with different granularity to suppress warnings and break elaboration
29504 circularities:
29505
29506 @itemize @bullet
29507 @item
29508 Place the pragma that names the called subprogram in the declarative part
29509 that contains the call.
29510
29511 @item
29512 Place the pragma in the declarative part, without naming an entity. This
29513 disables warnings on all calls in the corresponding  declarative region.
29514
29515 @item
29516 Place the pragma in the package spec that declares the called subprogram,
29517 and name the subprogram. This disables warnings on all elaboration calls to
29518 that subprogram.
29519
29520 @item
29521 Place the pragma in the package spec that declares the called subprogram,
29522 without naming any entity. This disables warnings on all elaboration calls to
29523 all subprograms declared in this spec.
29524
29525 @item Use Pragma Elaborate
29526 As previously described in section @xref{Treatment of Pragma Elaborate},
29527 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
29528 that no elaboration checks are required on calls to the designated unit.
29529 There may be cases in which the caller knows that no transitive calls
29530 can occur, so that a @code{pragma Elaborate} will be sufficient in a
29531 case where @code{pragma Elaborate_All} would cause a circularity.
29532 @end itemize
29533
29534 @noindent
29535 These five cases are listed in order of decreasing safety, and therefore
29536 require increasing programmer care in their application. Consider the
29537 following program:
29538
29539 @smallexample @c adanocomment
29540 package Pack1 is
29541   function F1 return Integer;
29542   X1 : Integer;
29543 end Pack1;
29544
29545 package Pack2 is
29546   function F2 return Integer;
29547   function Pure (x : integer) return integer;
29548   --  pragma Suppress (Elaboration_Check, On => Pure);  -- (3)
29549   --  pragma Suppress (Elaboration_Check);              -- (4)
29550 end Pack2;
29551
29552 with Pack2;
29553 package body Pack1 is
29554   function F1 return Integer is
29555   begin
29556     return 100;
29557   end F1;
29558   Val : integer := Pack2.Pure (11);    --  Elab. call (1)
29559 begin
29560   declare
29561     --  pragma Suppress(Elaboration_Check, Pack2.F2);   -- (1)
29562     --  pragma Suppress(Elaboration_Check);             -- (2)
29563   begin
29564     X1 := Pack2.F2 + 1;                --  Elab. call (2)
29565   end;
29566 end Pack1;
29567
29568 with Pack1;
29569 package body Pack2 is
29570   function F2 return Integer is
29571   begin
29572      return Pack1.F1;
29573   end F2;
29574   function Pure (x : integer) return integer is
29575   begin
29576      return x ** 3 - 3 * x;
29577   end;
29578 end Pack2;
29579
29580 with Pack1, Ada.Text_IO;
29581 procedure Proc3 is
29582 begin
29583   Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
29584 end Proc3;
29585 @end smallexample
29586 In the absence of any pragmas, an attempt to bind this program produces
29587 the following diagnostics:
29588 @smallexample
29589 @group
29590 @iftex
29591 @leftskip=.5cm
29592 @end iftex
29593 error: elaboration circularity detected
29594 info:    "pack1 (body)" must be elaborated before "pack1 (body)"
29595 info:       reason: Elaborate_All probably needed in unit "pack1 (body)"
29596 info:       recompile "pack1 (body)" with -gnatwl for full details
29597 info:          "pack1 (body)"
29598 info:             must be elaborated along with its spec:
29599 info:          "pack1 (spec)"
29600 info:             which is withed by:
29601 info:          "pack2 (body)"
29602 info:             which must be elaborated along with its spec:
29603 info:          "pack2 (spec)"
29604 info:             which is withed by:
29605 info:          "pack1 (body)"
29606 @end group
29607 @end smallexample
29608 The sources of the circularity are the two calls to @code{Pack2.Pure} and
29609 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
29610 F2 is safe, even though F2 calls F1, because the call appears after the
29611 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
29612 remove the warning on the call. It is also possible to use pragma (2)
29613 because there are no other potentially unsafe calls in the block.
29614
29615 @noindent
29616 The call to @code{Pure} is safe because this function does not depend on the
29617 state of @code{Pack2}. Therefore any call to this function is safe, and it
29618 is correct to place pragma (3) in the corresponding package spec.
29619
29620 @noindent
29621 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
29622 warnings on all calls to functions declared therein. Note that this is not
29623 necessarily safe, and requires more detailed examination of the subprogram
29624 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
29625 be already elaborated.
29626 @end table
29627
29628 @noindent
29629 It is hard to generalize on which of these four approaches should be
29630 taken. Obviously if it is possible to fix the program so that the default
29631 treatment works, this is preferable, but this may not always be practical.
29632 It is certainly simple enough to use
29633 @option{-gnatE}
29634 but the danger in this case is that, even if the GNAT binder
29635 finds a correct elaboration order, it may not always do so,
29636 and certainly a binder from another Ada compiler might not. A
29637 combination of testing and analysis (for which the warnings generated
29638 with the
29639 @option{-gnatwl}
29640 switch can be useful) must be used to ensure that the program is free
29641 of errors. One switch that is useful in this testing is the
29642 @option{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
29643 switch for
29644 @code{gnatbind}.
29645 Normally the binder tries to find an order that has the best chance
29646 of avoiding elaboration problems. However, if this switch is used, the binder
29647 plays a devil's advocate role, and tries to choose the order that
29648 has the best chance of failing. If your program works even with this
29649 switch, then it has a better chance of being error free, but this is still
29650 not a guarantee.
29651
29652 For an example of this approach in action, consider the C-tests (executable
29653 tests) from the ACVC suite. If these are compiled and run with the default
29654 treatment, then all but one of them succeed without generating any error
29655 diagnostics from the binder. However, there is one test that fails, and
29656 this is not surprising, because the whole point of this test is to ensure
29657 that the compiler can handle cases where it is impossible to determine
29658 a correct order statically, and it checks that an exception is indeed
29659 raised at run time.
29660
29661 This one test must be compiled and run using the
29662 @option{-gnatE}
29663 switch, and then it passes. Alternatively, the entire suite can
29664 be run using this switch. It is never wrong to run with the dynamic
29665 elaboration switch if your code is correct, and we assume that the
29666 C-tests are indeed correct (it is less efficient, but efficiency is
29667 not a factor in running the ACVC tests.)
29668
29669 @node Elaboration for Access-to-Subprogram Values
29670 @section Elaboration for Access-to-Subprogram Values
29671 @cindex Access-to-subprogram
29672
29673 @noindent
29674 Access-to-subprogram types (introduced in Ada 95) complicate
29675 the handling of elaboration. The trouble is that it becomes
29676 impossible to tell at compile time which procedure
29677 is being called. This means that it is not possible for the binder
29678 to analyze the elaboration requirements in this case.
29679
29680 If at the point at which the access value is created
29681 (i.e., the evaluation of @code{P'Access} for a subprogram @code{P}),
29682 the body of the subprogram is
29683 known to have been elaborated, then the access value is safe, and its use
29684 does not require a check. This may be achieved by appropriate arrangement
29685 of the order of declarations if the subprogram is in the current unit,
29686 or, if the subprogram is in another unit, by using pragma
29687 @code{Pure}, @code{Preelaborate}, or @code{Elaborate_Body}
29688 on the referenced unit.
29689
29690 If the referenced body is not known to have been elaborated at the point
29691 the access value is created, then any use of the access value must do a
29692 dynamic check, and this dynamic check will fail and raise a
29693 @code{Program_Error} exception if the body has not been elaborated yet.
29694 GNAT will generate the necessary checks, and in addition, if the
29695 @option{-gnatwl}
29696 switch is set, will generate warnings that such checks are required.
29697
29698 The use of dynamic dispatching for tagged types similarly generates
29699 a requirement for dynamic checks, and premature calls to any primitive
29700 operation of a tagged type before the body of the operation has been
29701 elaborated, will result in the raising of @code{Program_Error}.
29702
29703 @node Summary of Procedures for Elaboration Control
29704 @section Summary of Procedures for Elaboration Control
29705 @cindex Elaboration control
29706
29707 @noindent
29708 First, compile your program with the default options, using none of
29709 the special elaboration control switches. If the binder successfully
29710 binds your program, then you can be confident that, apart from issues
29711 raised by the use of access-to-subprogram types and dynamic dispatching,
29712 the program is free of elaboration errors. If it is important that the
29713 program be portable, then use the
29714 @option{-gnatwl}
29715 switch to generate warnings about missing @code{Elaborate} or
29716 @code{Elaborate_All} pragmas, and supply the missing pragmas.
29717
29718 If the program fails to bind using the default static elaboration
29719 handling, then you can fix the program to eliminate the binder
29720 message, or recompile the entire program with the
29721 @option{-gnatE} switch to generate dynamic elaboration checks,
29722 and, if you are sure there really are no elaboration problems,
29723 use a global pragma @code{Suppress (Elaboration_Check)}.
29724
29725 @node Other Elaboration Order Considerations
29726 @section Other Elaboration Order Considerations
29727 @noindent
29728 This section has been entirely concerned with the issue of finding a valid
29729 elaboration order, as defined by the Ada Reference Manual. In a case
29730 where several elaboration orders are valid, the task is to find one
29731 of the possible valid elaboration orders (and the static model in GNAT
29732 will ensure that this is achieved).
29733
29734 The purpose of the elaboration rules in the Ada Reference Manual is to
29735 make sure that no entity is accessed before it has been elaborated. For
29736 a subprogram, this means that the spec and body must have been elaborated
29737 before the subprogram is called. For an object, this means that the object
29738 must have been elaborated before its value is read or written. A violation
29739 of either of these two requirements is an access before elaboration order,
29740 and this section has been all about avoiding such errors.
29741
29742 In the case where more than one order of elaboration is possible, in the
29743 sense that access before elaboration errors are avoided, then any one of
29744 the orders is ``correct'' in the sense that it meets the requirements of
29745 the Ada Reference Manual, and no such error occurs.
29746
29747 However, it may be the case for a given program, that there are
29748 constraints on the order of elaboration that come not from consideration
29749 of avoiding elaboration errors, but rather from extra-lingual logic
29750 requirements. Consider this example:
29751
29752 @smallexample @c ada
29753 with Init_Constants;
29754 package Constants is
29755    X : Integer := 0;
29756    Y : Integer := 0;
29757 end Constants;
29758
29759 package Init_Constants is
29760    procedure P; -- require a body
29761 end Init_Constants;
29762
29763 with Constants;
29764 package body Init_Constants is
29765    procedure P is begin null; end;
29766 begin
29767    Constants.X := 3;
29768    Constants.Y := 4;
29769 end Init_Constants;
29770
29771 with Constants;
29772 package Calc is
29773    Z : Integer := Constants.X + Constants.Y;
29774 end Calc;
29775
29776 with Calc;
29777 with Text_IO; use Text_IO;
29778 procedure Main is
29779 begin
29780    Put_Line (Calc.Z'Img);
29781 end Main;
29782 @end smallexample
29783
29784 @noindent
29785 In this example, there is more than one valid order of elaboration. For
29786 example both the following are correct orders:
29787
29788 @smallexample
29789 Init_Constants spec
29790 Constants spec
29791 Calc spec
29792 Init_Constants body
29793 Main body
29794
29795   and
29796
29797 Init_Constants spec
29798 Init_Constants body
29799 Constants spec
29800 Calc spec
29801 Main body
29802 @end smallexample
29803
29804 @noindent
29805 There is no language rule to prefer one or the other, both are correct
29806 from an order of elaboration point of view. But the programmatic effects
29807 of the two orders are very different. In the first, the elaboration routine
29808 of @code{Calc} initializes @code{Z} to zero, and then the main program
29809 runs with this value of zero. But in the second order, the elaboration
29810 routine of @code{Calc} runs after the body of Init_Constants has set
29811 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
29812 runs.
29813
29814 One could perhaps by applying pretty clever non-artificial intelligence
29815 to the situation guess that it is more likely that the second order of
29816 elaboration is the one desired, but there is no formal linguistic reason
29817 to prefer one over the other. In fact in this particular case, GNAT will
29818 prefer the second order, because of the rule that bodies are elaborated
29819 as soon as possible, but it's just luck that this is what was wanted
29820 (if indeed the second order was preferred).
29821
29822 If the program cares about the order of elaboration routines in a case like
29823 this, it is important to specify the order required. In this particular
29824 case, that could have been achieved by adding to the spec of Calc:
29825
29826 @smallexample @c ada
29827 pragma Elaborate_All (Constants);
29828 @end smallexample
29829
29830 @noindent
29831 which requires that the body (if any) and spec of @code{Constants},
29832 as well as the body and spec of any unit @code{with}'ed by
29833 @code{Constants} be elaborated before @code{Calc} is elaborated.
29834
29835 Clearly no automatic method can always guess which alternative you require,
29836 and if you are working with legacy code that had constraints of this kind
29837 which were not properly specified by adding @code{Elaborate} or
29838 @code{Elaborate_All} pragmas, then indeed it is possible that two different
29839 compilers can choose different orders.
29840
29841 However, GNAT does attempt to diagnose the common situation where there
29842 are uninitialized variables in the visible part of a package spec, and the
29843 corresponding package body has an elaboration block that directly or
29844 indirectly initialized one or more of these variables. This is the situation
29845 in which a pragma Elaborate_Body is usually desirable, and GNAT will generate
29846 a warning that suggests this addition if it detects this situation.
29847
29848 The @code{gnatbind}
29849 @option{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
29850 out problems. This switch causes bodies to be elaborated as late as possible
29851 instead of as early as possible. In the example above, it would have forced
29852 the choice of the first elaboration order. If you get different results
29853 when using this switch, and particularly if one set of results is right,
29854 and one is wrong as far as you are concerned, it shows that you have some
29855 missing @code{Elaborate} pragmas. For the example above, we have the
29856 following output:
29857
29858 @smallexample
29859 gnatmake -f -q main
29860 main
29861  7
29862 gnatmake -f -q main -bargs -p
29863 main
29864  0
29865 @end smallexample
29866
29867 @noindent
29868 It is of course quite unlikely that both these results are correct, so
29869 it is up to you in a case like this to investigate the source of the
29870 difference, by looking at the two elaboration orders that are chosen,
29871 and figuring out which is correct, and then adding the necessary
29872 @code{Elaborate} or @code{Elaborate_All} pragmas to ensure the desired order.
29873
29874
29875
29876 @c *******************************
29877 @node Conditional Compilation
29878 @appendix Conditional Compilation
29879 @c *******************************
29880 @cindex Conditional compilation
29881
29882 @noindent
29883 It is often necessary to arrange for a single source program
29884 to serve multiple purposes, where it is compiled in different
29885 ways to achieve these different goals. Some examples of the
29886 need for this feature are
29887
29888 @itemize @bullet
29889 @item  Adapting a program to a different hardware environment
29890 @item  Adapting a program to a different target architecture
29891 @item  Turning debugging features on and off
29892 @item  Arranging for a program to compile with different compilers
29893 @end itemize
29894
29895 @noindent
29896 In C, or C++, the typical approach would be to use the preprocessor
29897 that is defined as part of the language. The Ada language does not
29898 contain such a feature. This is not an oversight, but rather a very
29899 deliberate design decision, based on the experience that overuse of
29900 the preprocessing features in C and C++ can result in programs that
29901 are extremely difficult to maintain. For example, if we have ten
29902 switches that can be on or off, this means that there are a thousand
29903 separate programs, any one of which might not even be syntactically
29904 correct, and even if syntactically correct, the resulting program
29905 might not work correctly. Testing all combinations can quickly become
29906 impossible.
29907
29908 Nevertheless, the need to tailor programs certainly exists, and in
29909 this Appendix we will discuss how this can
29910 be achieved using Ada in general, and GNAT in particular.
29911
29912 @menu
29913 * Use of Boolean Constants::
29914 * Debugging - A Special Case::
29915 * Conditionalizing Declarations::
29916 * Use of Alternative Implementations::
29917 * Preprocessing::
29918 @end menu
29919
29920 @node Use of Boolean Constants
29921 @section Use of Boolean Constants
29922
29923 @noindent
29924 In the case where the difference is simply which code
29925 sequence is executed, the cleanest solution is to use Boolean
29926 constants to control which code is executed.
29927
29928 @smallexample @c ada
29929 @group
29930 FP_Initialize_Required : constant Boolean := True;
29931 @dots{}
29932 if FP_Initialize_Required then
29933 @dots{}
29934 end if;
29935 @end group
29936 @end smallexample
29937
29938 @noindent
29939 Not only will the code inside the @code{if} statement not be executed if
29940 the constant Boolean is @code{False}, but it will also be completely
29941 deleted from the program.
29942 However, the code is only deleted after the @code{if} statement
29943 has been checked for syntactic and semantic correctness.
29944 (In contrast, with preprocessors the code is deleted before the
29945 compiler ever gets to see it, so it is not checked until the switch
29946 is turned on.)
29947 @cindex Preprocessors (contrasted with conditional compilation)
29948
29949 Typically the Boolean constants will be in a separate package,
29950 something like:
29951
29952 @smallexample @c ada
29953 @group
29954 package Config is
29955    FP_Initialize_Required : constant Boolean := True;
29956    Reset_Available        : constant Boolean := False;
29957    @dots{}
29958 end Config;
29959 @end group
29960 @end smallexample
29961
29962 @noindent
29963 The @code{Config} package exists in multiple forms for the various targets,
29964 with an appropriate script selecting the version of @code{Config} needed.
29965 Then any other unit requiring conditional compilation can do a @code{with}
29966 of @code{Config} to make the constants visible.
29967
29968
29969 @node Debugging - A Special Case
29970 @section Debugging - A Special Case
29971
29972 @noindent
29973 A common use of conditional code is to execute statements (for example
29974 dynamic checks, or output of intermediate results) under control of a
29975 debug switch, so that the debugging behavior can be turned on and off.
29976 This can be done using a Boolean constant to control whether the code
29977 is active:
29978
29979 @smallexample @c ada
29980 @group
29981 if Debugging then
29982    Put_Line ("got to the first stage!");
29983 end if;
29984 @end group
29985 @end smallexample
29986
29987 @noindent
29988 or
29989
29990 @smallexample @c ada
29991 @group
29992 if Debugging and then Temperature > 999.0 then
29993    raise Temperature_Crazy;
29994 end if;
29995 @end group
29996 @end smallexample
29997
29998 @noindent
29999 Since this is a common case, there are special features to deal with
30000 this in a convenient manner. For the case of tests, Ada 2005 has added
30001 a pragma @code{Assert} that can be used for such tests. This pragma is modeled
30002 @cindex pragma @code{Assert}
30003 on the @code{Assert} pragma that has always been available in GNAT, so this
30004 feature may be used with GNAT even if you are not using Ada 2005 features.
30005 The use of pragma @code{Assert} is described in
30006 @ref{Pragma Assert,,, gnat_rm, GNAT Reference Manual}, but as an
30007 example, the last test could be written:
30008
30009 @smallexample @c ada
30010 pragma Assert (Temperature <= 999.0, "Temperature Crazy");
30011 @end smallexample
30012
30013 @noindent
30014 or simply
30015
30016 @smallexample @c ada
30017 pragma Assert (Temperature <= 999.0);
30018 @end smallexample
30019
30020 @noindent
30021 In both cases, if assertions are active and the temperature is excessive,
30022 the exception @code{Assert_Failure} will be raised, with the given string in
30023 the first case or a string indicating the location of the pragma in the second
30024 case used as the exception message.
30025
30026 You can turn assertions on and off by using the @code{Assertion_Policy}
30027 pragma.
30028 @cindex pragma @code{Assertion_Policy}
30029 This is an Ada 2005 pragma which is implemented in all modes by
30030 GNAT, but only in the latest versions of GNAT which include Ada 2005
30031 capability. Alternatively, you can use the @option{-gnata} switch
30032 @cindex @option{-gnata} switch
30033 to enable assertions from the command line (this is recognized by all versions
30034 of GNAT).
30035
30036 For the example above with the @code{Put_Line}, the GNAT-specific pragma
30037 @code{Debug} can be used:
30038 @cindex pragma @code{Debug}
30039
30040 @smallexample @c ada
30041 pragma Debug (Put_Line ("got to the first stage!"));
30042 @end smallexample
30043
30044 @noindent
30045 If debug pragmas are enabled, the argument, which must be of the form of
30046 a procedure call, is executed (in this case, @code{Put_Line} will be called).
30047 Only one call can be present, but of course a special debugging procedure
30048 containing any code you like can be included in the program and then
30049 called in a pragma @code{Debug} argument as needed.
30050
30051 One advantage of pragma @code{Debug} over the @code{if Debugging then}
30052 construct is that pragma @code{Debug} can appear in declarative contexts,
30053 such as at the very beginning of a procedure, before local declarations have
30054 been elaborated.
30055
30056 Debug pragmas are enabled using either the @option{-gnata} switch that also
30057 controls assertions, or with a separate Debug_Policy pragma.
30058 @cindex pragma @code{Debug_Policy}
30059 The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
30060 in Ada 95 and Ada 83 programs as well), and is analogous to
30061 pragma @code{Assertion_Policy} to control assertions.
30062
30063 @code{Assertion_Policy} and @code{Debug_Policy} are configuration pragmas,
30064 and thus they can appear in @file{gnat.adc} if you are not using a
30065 project file, or in the file designated to contain configuration pragmas
30066 in a project file.
30067 They then apply to all subsequent compilations. In practice the use of
30068 the @option{-gnata} switch is often the most convenient method of controlling
30069 the status of these pragmas.
30070
30071 Note that a pragma is not a statement, so in contexts where a statement
30072 sequence is required, you can't just write a pragma on its own. You have
30073 to add a @code{null} statement.
30074
30075 @smallexample @c ada
30076 @group
30077 if @dots{} then
30078    @dots{} -- some statements
30079 else
30080    pragma Assert (Num_Cases < 10);
30081    null;
30082 end if;
30083 @end group
30084 @end smallexample
30085
30086
30087 @node Conditionalizing Declarations
30088 @section Conditionalizing Declarations
30089
30090 @noindent
30091 In some cases, it may be necessary to conditionalize declarations to meet
30092 different requirements. For example we might want a bit string whose length
30093 is set to meet some hardware message requirement.
30094
30095 In some cases, it may be possible to do this using declare blocks controlled
30096 by conditional constants:
30097
30098 @smallexample @c ada
30099 @group
30100 if Small_Machine then
30101    declare
30102       X : Bit_String (1 .. 10);
30103    begin
30104       @dots{}
30105    end;
30106 else
30107    declare
30108       X : Large_Bit_String (1 .. 1000);
30109    begin
30110       @dots{}
30111    end;
30112 end if;
30113 @end group
30114 @end smallexample
30115
30116 @noindent
30117 Note that in this approach, both declarations are analyzed by the
30118 compiler so this can only be used where both declarations are legal,
30119 even though one of them will not be used.
30120
30121 Another approach is to define integer constants, e.g.@: @code{Bits_Per_Word}, or
30122 Boolean constants, e.g.@: @code{Little_Endian}, and then write declarations
30123 that are parameterized by these constants. For example
30124
30125 @smallexample @c ada
30126 @group
30127 for Rec use
30128   Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
30129 end record;
30130 @end group
30131 @end smallexample
30132
30133 @noindent
30134 If @code{Bits_Per_Word} is set to 32, this generates either
30135
30136 @smallexample @c ada
30137 @group
30138 for Rec use
30139   Field1 at 0 range 0 .. 32;
30140 end record;
30141 @end group
30142 @end smallexample
30143
30144 @noindent
30145 for the big endian case, or
30146
30147 @smallexample @c ada
30148 @group
30149 for Rec use record
30150   Field1 at 0 range 10 .. 32;
30151 end record;
30152 @end group
30153 @end smallexample
30154
30155 @noindent
30156 for the little endian case. Since a powerful subset of Ada expression
30157 notation is usable for creating static constants, clever use of this
30158 feature can often solve quite difficult problems in conditionalizing
30159 compilation (note incidentally that in Ada 95, the little endian
30160 constant was introduced as @code{System.Default_Bit_Order}, so you do not
30161 need to define this one yourself).
30162
30163
30164 @node Use of Alternative Implementations
30165 @section Use of Alternative Implementations
30166
30167 @noindent
30168 In some cases, none of the approaches described above are adequate. This
30169 can occur for example if the set of declarations required is radically
30170 different for two different configurations.
30171
30172 In this situation, the official Ada way of dealing with conditionalizing
30173 such code is to write separate units for the different cases. As long as
30174 this does not result in excessive duplication of code, this can be done
30175 without creating maintenance problems. The approach is to share common
30176 code as far as possible, and then isolate the code and declarations
30177 that are different. Subunits are often a convenient method for breaking
30178 out a piece of a unit that is to be conditionalized, with separate files
30179 for different versions of the subunit for different targets, where the
30180 build script selects the right one to give to the compiler.
30181 @cindex Subunits (and conditional compilation)
30182
30183 As an example, consider a situation where a new feature in Ada 2005
30184 allows something to be done in a really nice way. But your code must be able
30185 to compile with an Ada 95 compiler. Conceptually you want to say:
30186
30187 @smallexample @c ada
30188 @group
30189 if Ada_2005 then
30190    @dots{} neat Ada 2005 code
30191 else
30192    @dots{} not quite as neat Ada 95 code
30193 end if;
30194 @end group
30195 @end smallexample
30196
30197 @noindent
30198 where @code{Ada_2005} is a Boolean constant.
30199
30200 But this won't work when @code{Ada_2005} is set to @code{False},
30201 since the @code{then} clause will be illegal for an Ada 95 compiler.
30202 (Recall that although such unreachable code would eventually be deleted
30203 by the compiler, it still needs to be legal.  If it uses features
30204 introduced in Ada 2005, it will be illegal in Ada 95.)
30205
30206 So instead we write
30207
30208 @smallexample @c ada
30209 procedure Insert is separate;
30210 @end smallexample
30211
30212 @noindent
30213 Then we have two files for the subunit @code{Insert}, with the two sets of
30214 code.
30215 If the package containing this is called @code{File_Queries}, then we might
30216 have two files
30217
30218 @itemize @bullet
30219 @item    @file{file_queries-insert-2005.adb}
30220 @item    @file{file_queries-insert-95.adb}
30221 @end itemize
30222
30223 @noindent
30224 and the build script renames the appropriate file to
30225
30226 @smallexample
30227 file_queries-insert.adb
30228 @end smallexample
30229
30230 @noindent
30231 and then carries out the compilation.
30232
30233 This can also be done with project files' naming schemes. For example:
30234
30235 @smallexample @c project
30236 For Body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
30237 @end smallexample
30238
30239 @noindent
30240 Note also that with project files it is desirable to use a different extension
30241 than @file{ads} / @file{adb} for alternative versions. Otherwise a naming
30242 conflict may arise through another commonly used feature: to declare as part
30243 of the project a set of directories containing all the sources obeying the
30244 default naming scheme.
30245
30246 The use of alternative units is certainly feasible in all situations,
30247 and for example the Ada part of the GNAT run-time is conditionalized
30248 based on the target architecture using this approach. As a specific example,
30249 consider the implementation of the AST feature in VMS. There is one
30250 spec:
30251
30252 @smallexample
30253 s-asthan.ads
30254 @end smallexample
30255
30256 @noindent
30257 which is the same for all architectures, and three bodies:
30258
30259 @table @file
30260 @item    s-asthan.adb
30261 used for all non-VMS operating systems
30262 @item    s-asthan-vms-alpha.adb
30263 used for VMS on the Alpha
30264 @item    s-asthan-vms-ia64.adb
30265 used for VMS on the ia64
30266 @end table
30267
30268 @noindent
30269 The dummy version @file{s-asthan.adb} simply raises exceptions noting that
30270 this operating system feature is not available, and the two remaining
30271 versions interface with the corresponding versions of VMS to provide
30272 VMS-compatible AST handling. The GNAT build script knows the architecture
30273 and operating system, and automatically selects the right version,
30274 renaming it if necessary to @file{s-asthan.adb} before the run-time build.
30275
30276 Another style for arranging alternative implementations is through Ada's
30277 access-to-subprogram facility.
30278 In case some functionality is to be conditionally included,
30279 you can declare an access-to-procedure variable @code{Ref} that is initialized
30280 to designate a ``do nothing'' procedure, and then invoke @code{Ref.all}
30281 when appropriate.
30282 In some library package, set @code{Ref} to @code{Proc'Access} for some
30283 procedure @code{Proc} that performs the relevant processing.
30284 The initialization only occurs if the library package is included in the
30285 program.
30286 The same idea can also be implemented using tagged types and dispatching
30287 calls.
30288
30289
30290 @node Preprocessing
30291 @section Preprocessing
30292 @cindex Preprocessing
30293
30294 @noindent
30295 Although it is quite possible to conditionalize code without the use of
30296 C-style preprocessing, as described earlier in this section, it is
30297 nevertheless convenient in some cases to use the C approach. Moreover,
30298 older Ada compilers have often provided some preprocessing capability,
30299 so legacy code may depend on this approach, even though it is not
30300 standard.
30301
30302 To accommodate such use, GNAT provides a preprocessor (modeled to a large
30303 extent on the various preprocessors that have been used
30304 with legacy code on other compilers, to enable easier transition).
30305
30306 The preprocessor may be used in two separate modes. It can be used quite
30307 separately from the compiler, to generate a separate output source file
30308 that is then fed to the compiler as a separate step. This is the
30309 @code{gnatprep} utility, whose use is fully described in
30310 @ref{Preprocessing Using gnatprep}.
30311 @cindex @code{gnatprep}
30312
30313 The preprocessing language allows such constructs as
30314
30315 @smallexample
30316 @group
30317 #if DEBUG or PRIORITY > 4 then
30318    bunch of declarations
30319 #else
30320    completely different bunch of declarations
30321 #end if;
30322 @end group
30323 @end smallexample
30324
30325 @noindent
30326 The values of the symbols @code{DEBUG} and @code{PRIORITY} can be
30327 defined either on the command line or in a separate file.
30328
30329 The other way of running the preprocessor is even closer to the C style and
30330 often more convenient. In this approach the preprocessing is integrated into
30331 the compilation process. The compiler is fed the preprocessor input which
30332 includes @code{#if} lines etc, and then the compiler carries out the
30333 preprocessing internally and processes the resulting output.
30334 For more details on this approach, see @ref{Integrated Preprocessing}.
30335
30336
30337 @c *******************************
30338 @node Inline Assembler
30339 @appendix Inline Assembler
30340 @c *******************************
30341
30342 @noindent
30343 If you need to write low-level software that interacts directly
30344 with the hardware, Ada provides two ways to incorporate assembly
30345 language code into your program.  First, you can import and invoke
30346 external routines written in assembly language, an Ada feature fully
30347 supported by GNAT@.  However, for small sections of code it may be simpler
30348 or more efficient to include assembly language statements directly
30349 in your Ada source program, using the facilities of the implementation-defined
30350 package @code{System.Machine_Code}, which incorporates the gcc
30351 Inline Assembler.  The Inline Assembler approach offers a number of advantages,
30352 including the following:
30353
30354 @itemize @bullet
30355 @item No need to use non-Ada tools
30356 @item Consistent interface over different targets
30357 @item Automatic usage of the proper calling conventions
30358 @item Access to Ada constants and variables
30359 @item Definition of intrinsic routines
30360 @item Possibility of inlining a subprogram comprising assembler code
30361 @item Code optimizer can take Inline Assembler code into account
30362 @end itemize
30363
30364 This chapter presents a series of examples to show you how to use
30365 the Inline Assembler.  Although it focuses on the Intel x86,
30366 the general approach applies also to other processors.
30367 It is assumed that you are familiar with Ada
30368 and with assembly language programming.
30369
30370 @menu
30371 * Basic Assembler Syntax::
30372 * A Simple Example of Inline Assembler::
30373 * Output Variables in Inline Assembler::
30374 * Input Variables in Inline Assembler::
30375 * Inlining Inline Assembler Code::
30376 * Other Asm Functionality::
30377 @end menu
30378
30379 @c ---------------------------------------------------------------------------
30380 @node Basic Assembler Syntax
30381 @section Basic Assembler Syntax
30382
30383 @noindent
30384 The assembler used by GNAT and gcc is based not on the Intel assembly
30385 language, but rather on a language that descends from the AT&T Unix
30386 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
30387 The following table summarizes the main features of @emph{as} syntax
30388 and points out the differences from the Intel conventions.
30389 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
30390 pre-processor) documentation for further information.
30391
30392 @table @asis
30393 @item Register names
30394 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
30395 @*
30396 Intel: No extra punctuation; for example @code{eax}
30397
30398 @item Immediate operand
30399 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
30400 @*
30401 Intel: No extra punctuation; for example @code{4}
30402
30403 @item Address
30404 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
30405 @*
30406 Intel: No extra punctuation; for example @code{loc}
30407
30408 @item Memory contents
30409 gcc / @emph{as}: No extra punctuation; for example @code{loc}
30410 @*
30411 Intel: Square brackets; for example @code{[loc]}
30412
30413 @item Register contents
30414 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
30415 @*
30416 Intel: Square brackets; for example @code{[eax]}
30417
30418 @item Hexadecimal numbers
30419 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
30420 @*
30421 Intel: Trailing ``h''; for example @code{A0h}
30422
30423 @item Operand size
30424 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
30425 a 16-bit word
30426 @*
30427 Intel: Implicit, deduced by assembler; for example @code{mov}
30428
30429 @item Instruction repetition
30430 gcc / @emph{as}: Split into two lines; for example
30431 @*
30432 @code{rep}
30433 @*
30434 @code{stosl}
30435 @*
30436 Intel: Keep on one line; for example @code{rep stosl}
30437
30438 @item Order of operands
30439 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
30440 @*
30441 Intel: Destination first; for example @code{mov eax, 4}
30442 @end table
30443
30444 @c ---------------------------------------------------------------------------
30445 @node A Simple Example of Inline Assembler
30446 @section A Simple Example of Inline Assembler
30447
30448 @noindent
30449 The following example will generate a single assembly language statement,
30450 @code{nop}, which does nothing.  Despite its lack of run-time effect,
30451 the example will be useful in illustrating the basics of
30452 the Inline Assembler facility.
30453
30454 @smallexample @c ada
30455 @group
30456 with System.Machine_Code; use System.Machine_Code;
30457 procedure Nothing is
30458 begin
30459    Asm ("nop");
30460 end Nothing;
30461 @end group
30462 @end smallexample
30463
30464 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
30465 here it takes one parameter, a @emph{template string} that must be a static
30466 expression and that will form the generated instruction.
30467 @code{Asm} may be regarded as a compile-time procedure that parses
30468 the template string and additional parameters (none here),
30469 from which it generates a sequence of assembly language instructions.
30470
30471 The examples in this chapter will illustrate several of the forms
30472 for invoking @code{Asm}; a complete specification of the syntax
30473 is found in @ref{Machine Code Insertions,,, gnat_rm, GNAT Reference
30474 Manual}.
30475
30476 Under the standard GNAT conventions, the @code{Nothing} procedure
30477 should be in a file named @file{nothing.adb}.
30478 You can build the executable in the usual way:
30479 @smallexample
30480 gnatmake nothing
30481 @end smallexample
30482 However, the interesting aspect of this example is not its run-time behavior
30483 but rather the generated assembly code.
30484 To see this output, invoke the compiler as follows:
30485 @smallexample
30486    gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
30487 @end smallexample
30488 where the options are:
30489
30490 @table @code
30491 @item -c
30492 compile only (no bind or link)
30493 @item -S
30494 generate assembler listing
30495 @item -fomit-frame-pointer
30496 do not set up separate stack frames
30497 @item -gnatp
30498 do not add runtime checks
30499 @end table
30500
30501 This gives a human-readable assembler version of the code. The resulting
30502 file will have the same name as the Ada source file, but with a @code{.s}
30503 extension. In our example, the file @file{nothing.s} has the following
30504 contents:
30505
30506 @smallexample
30507 @group
30508 .file "nothing.adb"
30509 gcc2_compiled.:
30510 ___gnu_compiled_ada:
30511 .text
30512    .align 4
30513 .globl __ada_nothing
30514 __ada_nothing:
30515 #APP
30516    nop
30517 #NO_APP
30518    jmp L1
30519    .align 2,0x90
30520 L1:
30521    ret
30522 @end group
30523 @end smallexample
30524
30525 The assembly code you included is clearly indicated by
30526 the compiler, between the @code{#APP} and @code{#NO_APP}
30527 delimiters. The character before the 'APP' and 'NOAPP'
30528 can differ on different targets. For example, GNU/Linux uses '#APP' while
30529 on NT you will see '/APP'.
30530
30531 If you make a mistake in your assembler code (such as using the
30532 wrong size modifier, or using a wrong operand for the instruction) GNAT
30533 will report this error in a temporary file, which will be deleted when
30534 the compilation is finished.  Generating an assembler file will help
30535 in such cases, since you can assemble this file separately using the
30536 @emph{as} assembler that comes with gcc.
30537
30538 Assembling the file using the command
30539
30540 @smallexample
30541 as @file{nothing.s}
30542 @end smallexample
30543 @noindent
30544 will give you error messages whose lines correspond to the assembler
30545 input file, so you can easily find and correct any mistakes you made.
30546 If there are no errors, @emph{as} will generate an object file
30547 @file{nothing.out}.
30548
30549 @c ---------------------------------------------------------------------------
30550 @node Output Variables in Inline Assembler
30551 @section Output Variables in Inline Assembler
30552
30553 @noindent
30554 The examples in this section, showing how to access the processor flags,
30555 illustrate how to specify the destination operands for assembly language
30556 statements.
30557
30558 @smallexample @c ada
30559 @group
30560 with Interfaces; use Interfaces;
30561 with Ada.Text_IO; use Ada.Text_IO;
30562 with System.Machine_Code; use System.Machine_Code;
30563 procedure Get_Flags is
30564    Flags : Unsigned_32;
30565    use ASCII;
30566 begin
30567    Asm ("pushfl"          & LF & HT & -- push flags on stack
30568         "popl %%eax"      & LF & HT & -- load eax with flags
30569         "movl %%eax, %0",             -- store flags in variable
30570         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
30571    Put_Line ("Flags register:" & Flags'Img);
30572 end Get_Flags;
30573 @end group
30574 @end smallexample
30575
30576 In order to have a nicely aligned assembly listing, we have separated
30577 multiple assembler statements in the Asm template string with linefeed
30578 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
30579 The resulting section of the assembly output file is:
30580
30581 @smallexample
30582 @group
30583 #APP
30584    pushfl
30585    popl %eax
30586    movl %eax, -40(%ebp)
30587 #NO_APP
30588 @end group
30589 @end smallexample
30590
30591 It would have been legal to write the Asm invocation as:
30592
30593 @smallexample
30594 Asm ("pushfl popl %%eax movl %%eax, %0")
30595 @end smallexample
30596
30597 but in the generated assembler file, this would come out as:
30598
30599 @smallexample
30600 #APP
30601    pushfl popl %eax movl %eax, -40(%ebp)
30602 #NO_APP
30603 @end smallexample
30604
30605 which is not so convenient for the human reader.
30606
30607 We use Ada comments
30608 at the end of each line to explain what the assembler instructions
30609 actually do.  This is a useful convention.
30610
30611 When writing Inline Assembler instructions, you need to precede each register
30612 and variable name with a percent sign.  Since the assembler already requires
30613 a percent sign at the beginning of a register name, you need two consecutive
30614 percent signs for such names in the Asm template string, thus @code{%%eax}.
30615 In the generated assembly code, one of the percent signs will be stripped off.
30616
30617 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
30618 variables: operands you later define using @code{Input} or @code{Output}
30619 parameters to @code{Asm}.
30620 An output variable is illustrated in
30621 the third statement in the Asm template string:
30622 @smallexample
30623 movl %%eax, %0
30624 @end smallexample
30625 The intent is to store the contents of the eax register in a variable that can
30626 be accessed in Ada.  Simply writing @code{movl %%eax, Flags} would not
30627 necessarily work, since the compiler might optimize by using a register
30628 to hold Flags, and the expansion of the @code{movl} instruction would not be
30629 aware of this optimization.  The solution is not to store the result directly
30630 but rather to advise the compiler to choose the correct operand form;
30631 that is the purpose of the @code{%0} output variable.
30632
30633 Information about the output variable is supplied in the @code{Outputs}
30634 parameter to @code{Asm}:
30635 @smallexample
30636 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
30637 @end smallexample
30638
30639 The output is defined by the @code{Asm_Output} attribute of the target type;
30640 the general format is
30641 @smallexample
30642 Type'Asm_Output (constraint_string, variable_name)
30643 @end smallexample
30644
30645 The constraint string directs the compiler how
30646 to store/access the associated variable.  In the example
30647 @smallexample
30648 Unsigned_32'Asm_Output ("=m", Flags);
30649 @end smallexample
30650 the @code{"m"} (memory) constraint tells the compiler that the variable
30651 @code{Flags} should be stored in a memory variable, thus preventing
30652 the optimizer from keeping it in a register.  In contrast,
30653 @smallexample
30654 Unsigned_32'Asm_Output ("=r", Flags);
30655 @end smallexample
30656 uses the @code{"r"} (register) constraint, telling the compiler to
30657 store the variable in a register.
30658
30659 If the constraint is preceded by the equal character (@strong{=}), it tells
30660 the compiler that the variable will be used to store data into it.
30661
30662 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
30663 allowing the optimizer to choose whatever it deems best.
30664
30665 There are a fairly large number of constraints, but the ones that are
30666 most useful (for the Intel x86 processor) are the following:
30667
30668 @table @code
30669 @item =
30670 output constraint
30671 @item g
30672 global (i.e.@: can be stored anywhere)
30673 @item m
30674 in memory
30675 @item I
30676 a constant
30677 @item a
30678 use eax
30679 @item b
30680 use ebx
30681 @item c
30682 use ecx
30683 @item d
30684 use edx
30685 @item S
30686 use esi
30687 @item D
30688 use edi
30689 @item r
30690 use one of eax, ebx, ecx or edx
30691 @item q
30692 use one of eax, ebx, ecx, edx, esi or edi
30693 @end table
30694
30695 The full set of constraints is described in the gcc and @emph{as}
30696 documentation; note that it is possible to combine certain constraints
30697 in one constraint string.
30698
30699 You specify the association of an output variable with an assembler operand
30700 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
30701 integer.  Thus in
30702 @smallexample @c ada
30703 @group
30704 Asm ("pushfl"          & LF & HT & -- push flags on stack
30705      "popl %%eax"      & LF & HT & -- load eax with flags
30706      "movl %%eax, %0",             -- store flags in variable
30707      Outputs => Unsigned_32'Asm_Output ("=g", Flags));
30708 @end group
30709 @end smallexample
30710 @noindent
30711 @code{%0} will be replaced in the expanded code by the appropriate operand,
30712 whatever
30713 the compiler decided for the @code{Flags} variable.
30714
30715 In general, you may have any number of output variables:
30716 @itemize @bullet
30717 @item
30718 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
30719 @item
30720 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
30721 of @code{Asm_Output} attributes
30722 @end itemize
30723
30724 For example:
30725 @smallexample @c ada
30726 @group
30727 Asm ("movl %%eax, %0" & LF & HT &
30728      "movl %%ebx, %1" & LF & HT &
30729      "movl %%ecx, %2",
30730      Outputs => (Unsigned_32'Asm_Output ("=g", Var_A),   --  %0 = Var_A
30731                  Unsigned_32'Asm_Output ("=g", Var_B),   --  %1 = Var_B
30732                  Unsigned_32'Asm_Output ("=g", Var_C))); --  %2 = Var_C
30733 @end group
30734 @end smallexample
30735 @noindent
30736 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
30737 in the Ada program.
30738
30739 As a variation on the @code{Get_Flags} example, we can use the constraints
30740 string to direct the compiler to store the eax register into the @code{Flags}
30741 variable, instead of including the store instruction explicitly in the
30742 @code{Asm} template string:
30743
30744 @smallexample @c ada
30745 @group
30746 with Interfaces; use Interfaces;
30747 with Ada.Text_IO; use Ada.Text_IO;
30748 with System.Machine_Code; use System.Machine_Code;
30749 procedure Get_Flags_2 is
30750    Flags : Unsigned_32;
30751    use ASCII;
30752 begin
30753    Asm ("pushfl"      & LF & HT & -- push flags on stack
30754         "popl %%eax",             -- save flags in eax
30755         Outputs => Unsigned_32'Asm_Output ("=a", Flags));
30756    Put_Line ("Flags register:" & Flags'Img);
30757 end Get_Flags_2;
30758 @end group
30759 @end smallexample
30760
30761 @noindent
30762 The @code{"a"} constraint tells the compiler that the @code{Flags}
30763 variable will come from the eax register. Here is the resulting code:
30764
30765 @smallexample
30766 @group
30767 #APP
30768    pushfl
30769    popl %eax
30770 #NO_APP
30771    movl %eax,-40(%ebp)
30772 @end group
30773 @end smallexample
30774
30775 @noindent
30776 The compiler generated the store of eax into Flags after
30777 expanding the assembler code.
30778
30779 Actually, there was no need to pop the flags into the eax register;
30780 more simply, we could just pop the flags directly into the program variable:
30781
30782 @smallexample @c ada
30783 @group
30784 with Interfaces; use Interfaces;
30785 with Ada.Text_IO; use Ada.Text_IO;
30786 with System.Machine_Code; use System.Machine_Code;
30787 procedure Get_Flags_3 is
30788    Flags : Unsigned_32;
30789    use ASCII;
30790 begin
30791    Asm ("pushfl"  & LF & HT & -- push flags on stack
30792         "pop %0",             -- save flags in Flags
30793         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
30794    Put_Line ("Flags register:" & Flags'Img);
30795 end Get_Flags_3;
30796 @end group
30797 @end smallexample
30798
30799 @c ---------------------------------------------------------------------------
30800 @node Input Variables in Inline Assembler
30801 @section Input Variables in Inline Assembler
30802
30803 @noindent
30804 The example in this section illustrates how to specify the source operands
30805 for assembly language statements.
30806 The program simply increments its input value by 1:
30807
30808 @smallexample @c ada
30809 @group
30810 with Interfaces; use Interfaces;
30811 with Ada.Text_IO; use Ada.Text_IO;
30812 with System.Machine_Code; use System.Machine_Code;
30813 procedure Increment is
30814
30815    function Incr (Value : Unsigned_32) return Unsigned_32 is
30816       Result : Unsigned_32;
30817    begin
30818       Asm ("incl %0",
30819            Inputs  => Unsigned_32'Asm_Input ("a", Value),
30820            Outputs => Unsigned_32'Asm_Output ("=a", Result));
30821       return Result;
30822    end Incr;
30823
30824    Value : Unsigned_32;
30825
30826 begin
30827    Value := 5;
30828    Put_Line ("Value before is" & Value'Img);
30829    Value := Incr (Value);
30830    Put_Line ("Value after is" & Value'Img);
30831 end Increment;
30832 @end group
30833 @end smallexample
30834
30835 The @code{Outputs} parameter to @code{Asm} specifies
30836 that the result will be in the eax register and that it is to be stored
30837 in the @code{Result} variable.
30838
30839 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
30840 but with an @code{Asm_Input} attribute.
30841 The @code{"="} constraint, indicating an output value, is not present.
30842
30843 You can have multiple input variables, in the same way that you can have more
30844 than one output variable.
30845
30846 The parameter count (%0, %1) etc, now starts at the first input
30847 statement, and continues with the output statements.
30848 When both parameters use the same variable, the
30849 compiler will treat them as the same %n operand, which is the case here.
30850
30851 Just as the @code{Outputs} parameter causes the register to be stored into the
30852 target variable after execution of the assembler statements, so does the
30853 @code{Inputs} parameter cause its variable to be loaded into the register
30854 before execution of the assembler statements.
30855
30856 Thus the effect of the @code{Asm} invocation is:
30857 @enumerate
30858 @item load the 32-bit value of @code{Value} into eax
30859 @item execute the @code{incl %eax} instruction
30860 @item store the contents of eax into the @code{Result} variable
30861 @end enumerate
30862
30863 The resulting assembler file (with @option{-O2} optimization) contains:
30864 @smallexample
30865 @group
30866 _increment__incr.1:
30867    subl $4,%esp
30868    movl 8(%esp),%eax
30869 #APP
30870    incl %eax
30871 #NO_APP
30872    movl %eax,%edx
30873    movl %ecx,(%esp)
30874    addl $4,%esp
30875    ret
30876 @end group
30877 @end smallexample
30878
30879 @c ---------------------------------------------------------------------------
30880 @node Inlining Inline Assembler Code
30881 @section Inlining Inline Assembler Code
30882
30883 @noindent
30884 For a short subprogram such as the @code{Incr} function in the previous
30885 section, the overhead of the call and return (creating / deleting the stack
30886 frame) can be significant, compared to the amount of code in the subprogram
30887 body.  A solution is to apply Ada's @code{Inline} pragma to the subprogram,
30888 which directs the compiler to expand invocations of the subprogram at the
30889 point(s) of call, instead of setting up a stack frame for out-of-line calls.
30890 Here is the resulting program:
30891
30892 @smallexample @c ada
30893 @group
30894 with Interfaces; use Interfaces;
30895 with Ada.Text_IO; use Ada.Text_IO;
30896 with System.Machine_Code; use System.Machine_Code;
30897 procedure Increment_2 is
30898
30899    function Incr (Value : Unsigned_32) return Unsigned_32 is
30900       Result : Unsigned_32;
30901    begin
30902       Asm ("incl %0",
30903            Inputs  => Unsigned_32'Asm_Input ("a", Value),
30904            Outputs => Unsigned_32'Asm_Output ("=a", Result));
30905       return Result;
30906    end Incr;
30907    pragma Inline (Increment);
30908
30909    Value : Unsigned_32;
30910
30911 begin
30912    Value := 5;
30913    Put_Line ("Value before is" & Value'Img);
30914    Value := Increment (Value);
30915    Put_Line ("Value after is" & Value'Img);
30916 end Increment_2;
30917 @end group
30918 @end smallexample
30919
30920 Compile the program with both optimization (@option{-O2}) and inlining
30921 (@option{-gnatn}) enabled.
30922
30923 The @code{Incr} function is still compiled as usual, but at the
30924 point in @code{Increment} where our function used to be called:
30925
30926 @smallexample
30927 @group
30928 pushl %edi
30929 call _increment__incr.1
30930 @end group
30931 @end smallexample
30932
30933 @noindent
30934 the code for the function body directly appears:
30935
30936 @smallexample
30937 @group
30938 movl %esi,%eax
30939 #APP
30940    incl %eax
30941 #NO_APP
30942    movl %eax,%edx
30943 @end group
30944 @end smallexample
30945
30946 @noindent
30947 thus saving the overhead of stack frame setup and an out-of-line call.
30948
30949 @c ---------------------------------------------------------------------------
30950 @node Other Asm Functionality
30951 @section Other @code{Asm} Functionality
30952
30953 @noindent
30954 This section describes two important parameters to the @code{Asm}
30955 procedure: @code{Clobber}, which identifies register usage;
30956 and @code{Volatile}, which inhibits unwanted optimizations.
30957
30958 @menu
30959 * The Clobber Parameter::
30960 * The Volatile Parameter::
30961 @end menu
30962
30963 @c ---------------------------------------------------------------------------
30964 @node The Clobber Parameter
30965 @subsection The @code{Clobber} Parameter
30966
30967 @noindent
30968 One of the dangers of intermixing assembly language and a compiled language
30969 such as Ada is that the compiler needs to be aware of which registers are
30970 being used by the assembly code.  In some cases, such as the earlier examples,
30971 the constraint string is sufficient to indicate register usage (e.g.,
30972 @code{"a"} for
30973 the eax register).  But more generally, the compiler needs an explicit
30974 identification of the registers that are used by the Inline Assembly
30975 statements.
30976
30977 Using a register that the compiler doesn't know about
30978 could be a side effect of an instruction (like @code{mull}
30979 storing its result in both eax and edx).
30980 It can also arise from explicit register usage in your
30981 assembly code; for example:
30982 @smallexample
30983 @group
30984 Asm ("movl %0, %%ebx" & LF & HT &
30985      "movl %%ebx, %1",
30986      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
30987      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out));
30988 @end group
30989 @end smallexample
30990 @noindent
30991 where the compiler (since it does not analyze the @code{Asm} template string)
30992 does not know you are using the ebx register.
30993
30994 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
30995 to identify the registers that will be used by your assembly code:
30996
30997 @smallexample
30998 @group
30999 Asm ("movl %0, %%ebx" & LF & HT &
31000      "movl %%ebx, %1",
31001      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
31002      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
31003      Clobber => "ebx");
31004 @end group
31005 @end smallexample
31006
31007 The Clobber parameter is a static string expression specifying the
31008 register(s) you are using.  Note that register names are @emph{not} prefixed
31009 by a percent sign. Also, if more than one register is used then their names
31010 are separated by commas; e.g., @code{"eax, ebx"}
31011
31012 The @code{Clobber} parameter has several additional uses:
31013 @enumerate
31014 @item Use ``register'' name @code{cc} to indicate that flags might have changed
31015 @item Use ``register'' name @code{memory} if you changed a memory location
31016 @end enumerate
31017
31018 @c ---------------------------------------------------------------------------
31019 @node The Volatile Parameter
31020 @subsection The @code{Volatile} Parameter
31021 @cindex Volatile parameter
31022
31023 @noindent
31024 Compiler optimizations in the presence of Inline Assembler may sometimes have
31025 unwanted effects.  For example, when an @code{Asm} invocation with an input
31026 variable is inside a loop, the compiler might move the loading of the input
31027 variable outside the loop, regarding it as a one-time initialization.
31028
31029 If this effect is not desired, you can disable such optimizations by setting
31030 the @code{Volatile} parameter to @code{True}; for example:
31031
31032 @smallexample @c ada
31033 @group
31034 Asm ("movl %0, %%ebx" & LF & HT &
31035      "movl %%ebx, %1",
31036      Inputs   => Unsigned_32'Asm_Input  ("g", Var_In),
31037      Outputs  => Unsigned_32'Asm_Output ("=g", Var_Out),
31038      Clobber  => "ebx",
31039      Volatile => True);
31040 @end group
31041 @end smallexample
31042
31043 By default, @code{Volatile} is set to @code{False} unless there is no
31044 @code{Outputs} parameter.
31045
31046 Although setting @code{Volatile} to @code{True} prevents unwanted
31047 optimizations, it will also disable other optimizations that might be
31048 important for efficiency. In general, you should set @code{Volatile}
31049 to @code{True} only if the compiler's optimizations have created
31050 problems.
31051 @c END OF INLINE ASSEMBLER CHAPTER
31052 @c ===============================
31053
31054 @c ***********************************
31055 @c * Compatibility and Porting Guide *
31056 @c ***********************************
31057 @node Compatibility and Porting Guide
31058 @appendix Compatibility and Porting Guide
31059
31060 @noindent
31061 This chapter describes the compatibility issues that may arise between
31062 GNAT and other Ada compilation systems (including those for Ada 83),
31063 and shows how GNAT can expedite porting
31064 applications developed in other Ada environments.
31065
31066 @menu
31067 * Compatibility with Ada 83::
31068 * Compatibility between Ada 95 and Ada 2005::
31069 * Implementation-dependent characteristics::
31070 * Compatibility with Other Ada Systems::
31071 * Representation Clauses::
31072 @ifclear vms
31073 @c Brief section is only in non-VMS version
31074 @c Full chapter is in VMS version
31075 * Compatibility with HP Ada 83::
31076 @end ifclear
31077 @ifset vms
31078 * Transitioning to 64-Bit GNAT for OpenVMS::
31079 @end ifset
31080 @end menu
31081
31082 @node Compatibility with Ada 83
31083 @section Compatibility with Ada 83
31084 @cindex Compatibility (between Ada 83 and Ada 95 / Ada 2005)
31085
31086 @noindent
31087 Ada 95 and Ada 2005 are highly upwards compatible with Ada 83.  In
31088 particular, the design intention was that the difficulties associated
31089 with moving from Ada 83 to Ada 95 or Ada 2005 should be no greater than those
31090 that occur when moving from one Ada 83 system to another.
31091
31092 However, there are a number of points at which there are minor
31093 incompatibilities.  The @cite{Ada 95 Annotated Reference Manual} contains
31094 full details of these issues,
31095 and should be consulted for a complete treatment.
31096 In practice the
31097 following subsections treat the most likely issues to be encountered.
31098
31099 @menu
31100 * Legal Ada 83 programs that are illegal in Ada 95::
31101 * More deterministic semantics::
31102 * Changed semantics::
31103 * Other language compatibility issues::
31104 @end menu
31105
31106 @node Legal Ada 83 programs that are illegal in Ada 95
31107 @subsection Legal Ada 83 programs that are illegal in Ada 95
31108
31109 Some legal Ada 83 programs are illegal (i.e., they will fail to compile) in
31110 Ada 95 and thus also in Ada 2005:
31111
31112 @table @emph
31113 @item Character literals
31114 Some uses of character literals are ambiguous.  Since Ada 95 has introduced
31115 @code{Wide_Character} as a new predefined character type, some uses of
31116 character literals that were legal in Ada 83 are illegal in Ada 95.
31117 For example:
31118 @smallexample @c ada
31119    for Char in 'A' .. 'Z' loop @dots{} end loop;
31120 @end smallexample
31121
31122 @noindent
31123 The problem is that @code{'A'} and @code{'Z'} could be from either
31124 @code{Character} or @code{Wide_Character}.  The simplest correction
31125 is to make the type explicit; e.g.:
31126 @smallexample @c ada
31127    for Char in Character range 'A' .. 'Z' loop @dots{} end loop;
31128 @end smallexample
31129
31130 @item New reserved words
31131 The identifiers @code{abstract}, @code{aliased}, @code{protected},
31132 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
31133 Existing Ada 83 code using any of these identifiers must be edited to
31134 use some alternative name.
31135
31136 @item Freezing rules
31137 The rules in Ada 95 are slightly different with regard to the point at
31138 which entities are frozen, and representation pragmas and clauses are
31139 not permitted past the freeze point.  This shows up most typically in
31140 the form of an error message complaining that a representation item
31141 appears too late, and the appropriate corrective action is to move
31142 the item nearer to the declaration of the entity to which it refers.
31143
31144 A particular case is that representation pragmas
31145 @ifset vms
31146 (including the
31147 extended HP Ada 83 compatibility pragmas such as @code{Export_Procedure})
31148 @end ifset
31149 cannot be applied to a subprogram body.  If necessary, a separate subprogram
31150 declaration must be introduced to which the pragma can be applied.
31151
31152 @item Optional bodies for library packages
31153 In Ada 83, a package that did not require a package body was nevertheless
31154 allowed to have one.  This lead to certain surprises in compiling large
31155 systems (situations in which the body could be unexpectedly ignored by the
31156 binder).  In Ada 95, if a package does not require a body then it is not
31157 permitted to have a body.  To fix this problem, simply remove a redundant
31158 body if it is empty, or, if it is non-empty, introduce a dummy declaration
31159 into the spec that makes the body required.  One approach is to add a private
31160 part to the package declaration (if necessary), and define a parameterless
31161 procedure called @code{Requires_Body}, which must then be given a dummy
31162 procedure body in the package body, which then becomes required.
31163 Another approach (assuming that this does not introduce elaboration
31164 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
31165 since one effect of this pragma is to require the presence of a package body.
31166
31167 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
31168 In Ada 95, the exception @code{Numeric_Error} is a renaming of
31169 @code{Constraint_Error}.
31170 This means that it is illegal to have separate exception handlers for
31171 the two exceptions.  The fix is simply to remove the handler for the
31172 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
31173 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
31174
31175 @item Indefinite subtypes in generics
31176 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
31177 as the actual for a generic formal private type, but then the instantiation
31178 would be illegal if there were any instances of declarations of variables
31179 of this type in the generic body.  In Ada 95, to avoid this clear violation
31180 of the methodological principle known as the ``contract model'',
31181 the generic declaration explicitly indicates whether
31182 or not such instantiations are permitted.  If a generic formal parameter
31183 has explicit unknown discriminants, indicated by using @code{(<>)} after the
31184 type name, then it can be instantiated with indefinite types, but no
31185 stand-alone variables can be declared of this type.  Any attempt to declare
31186 such a variable will result in an illegality at the time the generic is
31187 declared.  If the @code{(<>)} notation is not used, then it is illegal
31188 to instantiate the generic with an indefinite type.
31189 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
31190 It will show up as a compile time error, and
31191 the fix is usually simply to add the @code{(<>)} to the generic declaration.
31192 @end table
31193
31194 @node More deterministic semantics
31195 @subsection More deterministic semantics
31196
31197 @table @emph
31198 @item Conversions
31199 Conversions from real types to integer types round away from 0.  In Ada 83
31200 the conversion Integer(2.5) could deliver either 2 or 3 as its value.  This
31201 implementation freedom was intended to support unbiased rounding in
31202 statistical applications, but in practice it interfered with portability.
31203 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
31204 is required.  Numeric code may be affected by this change in semantics.
31205 Note, though, that this issue is no worse than already existed in Ada 83
31206 when porting code from one vendor to another.
31207
31208 @item Tasking
31209 The Real-Time Annex introduces a set of policies that define the behavior of
31210 features that were implementation dependent in Ada 83, such as the order in
31211 which open select branches are executed.
31212 @end table
31213
31214 @node Changed semantics
31215 @subsection Changed semantics
31216
31217 @noindent
31218 The worst kind of incompatibility is one where a program that is legal in
31219 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
31220 possible in Ada 83.  Fortunately this is extremely rare, but the one
31221 situation that you should be alert to is the change in the predefined type
31222 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
31223
31224 @table @emph
31225 @item Range of type @code{Character}
31226 The range of @code{Standard.Character} is now the full 256 characters
31227 of Latin-1, whereas in most Ada 83 implementations it was restricted
31228 to 128 characters. Although some of the effects of
31229 this change will be manifest in compile-time rejection of legal
31230 Ada 83 programs it is possible for a working Ada 83 program to have
31231 a different effect in Ada 95, one that was not permitted in Ada 83.
31232 As an example, the expression
31233 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
31234 delivers @code{255} as its value.
31235 In general, you should look at the logic of any
31236 character-processing Ada 83 program and see whether it needs to be adapted
31237 to work correctly with Latin-1.  Note that the predefined Ada 95 API has a
31238 character handling package that may be relevant if code needs to be adapted
31239 to account for the additional Latin-1 elements.
31240 The desirable fix is to
31241 modify the program to accommodate the full character set, but in some cases
31242 it may be convenient to define a subtype or derived type of Character that
31243 covers only the restricted range.
31244 @cindex Latin-1
31245 @end table
31246
31247 @node Other language compatibility issues
31248 @subsection Other language compatibility issues
31249
31250 @table @emph
31251 @item @option{-gnat83} switch
31252 All implementations of GNAT provide a switch that causes GNAT to operate
31253 in Ada 83 mode.  In this mode, some but not all compatibility problems
31254 of the type described above are handled automatically.  For example, the
31255 new reserved words introduced in Ada 95 and Ada 2005 are treated simply
31256 as identifiers as in Ada 83.
31257 However,
31258 in practice, it is usually advisable to make the necessary modifications
31259 to the program to remove the need for using this switch.
31260 See @ref{Compiling Different Versions of Ada}.
31261
31262 @item Support for removed Ada 83 pragmas and attributes
31263 A number of pragmas and attributes from Ada 83 were removed from Ada 95,
31264 generally because they were replaced by other mechanisms.  Ada 95 and Ada 2005
31265 compilers are allowed, but not required, to implement these missing
31266 elements.  In contrast with some other compilers, GNAT implements all
31267 such pragmas and attributes, eliminating this compatibility concern.  These
31268 include @code{pragma Interface} and the floating point type attributes
31269 (@code{Emax}, @code{Mantissa}, etc.), among other items.
31270 @end table
31271
31272
31273 @node Compatibility between Ada 95 and Ada 2005
31274 @section Compatibility between Ada 95 and Ada 2005
31275 @cindex Compatibility between Ada 95 and Ada 2005
31276
31277 @noindent
31278 Although Ada 2005 was designed to be upwards compatible with Ada 95, there are
31279 a number of incompatibilities. Several are enumerated below;
31280 for a complete description please see the
31281 Annotated Ada 2005 Reference Manual, or section 9.1.1 in
31282 @cite{Rationale for Ada 2005}.
31283
31284 @table @emph
31285 @item New reserved words.
31286 The words @code{interface}, @code{overriding} and @code{synchronized} are
31287 reserved in Ada 2005.
31288 A pre-Ada 2005 program that uses any of these as an identifier will be
31289 illegal.
31290
31291 @item New declarations in predefined packages.
31292 A number of packages in the predefined environment contain new declarations:
31293 @code{Ada.Exceptions}, @code{Ada.Real_Time}, @code{Ada.Strings},
31294 @code{Ada.Strings.Fixed}, @code{Ada.Strings.Bounded},
31295 @code{Ada.Strings.Unbounded}, @code{Ada.Strings.Wide_Fixed},
31296 @code{Ada.Strings.Wide_Bounded}, @code{Ada.Strings.Wide_Unbounded},
31297 @code{Ada.Tags}, @code{Ada.Text_IO}, and @code{Interfaces.C}.
31298 If an Ada 95 program does a @code{with} and @code{use} of any of these
31299 packages, the new declarations may cause name clashes.
31300
31301 @item Access parameters.
31302 A nondispatching subprogram with an access parameter cannot be renamed
31303 as a dispatching operation.  This was permitted in Ada 95.
31304
31305 @item Access types, discriminants, and constraints.
31306 Rule changes in this area have led to some incompatibilities; for example,
31307 constrained subtypes of some access types are not permitted in Ada 2005.
31308
31309 @item Aggregates for limited types.
31310 The allowance of aggregates for limited types in Ada 2005 raises the
31311 possibility of ambiguities in legal Ada 95 programs, since additional types
31312 now need to be considered in expression resolution.
31313
31314 @item Fixed-point multiplication and division.
31315 Certain expressions involving ``*'' or ``/'' for a fixed-point type, which
31316 were legal in Ada 95 and invoked the predefined versions of these operations,
31317 are now ambiguous.
31318 The ambiguity may be resolved either by applying a type conversion to the
31319 expression, or by explicitly invoking the operation from package
31320 @code{Standard}.
31321
31322 @item Return-by-reference types.
31323 The Ada 95 return-by-reference mechanism has been removed.  Instead, the user
31324 can declare a function returning a value from an anonymous access type.
31325 @end table
31326
31327
31328 @node Implementation-dependent characteristics
31329 @section Implementation-dependent characteristics
31330 @noindent
31331 Although the Ada language defines the semantics of each construct as
31332 precisely as practical, in some situations (for example for reasons of
31333 efficiency, or where the effect is heavily dependent on the host or target
31334 platform) the implementation is allowed some freedom.  In porting Ada 83
31335 code to GNAT, you need to be aware of whether / how the existing code
31336 exercised such implementation dependencies.  Such characteristics fall into
31337 several categories, and GNAT offers specific support in assisting the
31338 transition from certain Ada 83 compilers.
31339
31340 @menu
31341 * Implementation-defined pragmas::
31342 * Implementation-defined attributes::
31343 * Libraries::
31344 * Elaboration order::
31345 * Target-specific aspects::
31346 @end menu
31347
31348 @node Implementation-defined pragmas
31349 @subsection Implementation-defined pragmas
31350
31351 @noindent
31352 Ada compilers are allowed to supplement the language-defined pragmas, and
31353 these are a potential source of non-portability.  All GNAT-defined pragmas
31354 are described in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT
31355 Reference Manual}, and these include several that are specifically
31356 intended to correspond to other vendors' Ada 83 pragmas.
31357 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
31358 For compatibility with HP Ada 83, GNAT supplies the pragmas
31359 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
31360 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
31361 and @code{Volatile}.
31362 Other relevant pragmas include @code{External} and @code{Link_With}.
31363 Some vendor-specific
31364 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
31365 recognized, thus
31366 avoiding compiler rejection of units that contain such pragmas; they are not
31367 relevant in a GNAT context and hence are not otherwise implemented.
31368
31369 @node Implementation-defined attributes
31370 @subsection Implementation-defined attributes
31371
31372 Analogous to pragmas, the set of attributes may be extended by an
31373 implementation.  All GNAT-defined attributes are described in
31374 @ref{Implementation Defined Attributes,,, gnat_rm, GNAT Reference
31375 Manual}, and these include several that are specifically intended
31376 to correspond to other vendors' Ada 83 attributes.  For migrating from VADS,
31377 the attribute @code{VADS_Size} may be useful.  For compatibility with HP
31378 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
31379 @code{Type_Class}.
31380
31381 @node Libraries
31382 @subsection Libraries
31383 @noindent
31384 Vendors may supply libraries to supplement the standard Ada API.  If Ada 83
31385 code uses vendor-specific libraries then there are several ways to manage
31386 this in Ada 95 or Ada 2005:
31387 @enumerate
31388 @item
31389 If the source code for the libraries (specs and bodies) are
31390 available, then the libraries can be migrated in the same way as the
31391 application.
31392 @item
31393 If the source code for the specs but not the bodies are
31394 available, then you can reimplement the bodies.
31395 @item
31396 Some features introduced by Ada 95 obviate the need for library support.  For
31397 example most Ada 83 vendors supplied a package for unsigned integers.  The
31398 Ada 95 modular type feature is the preferred way to handle this need, so
31399 instead of migrating or reimplementing the unsigned integer package it may
31400 be preferable to retrofit the application using modular types.
31401 @end enumerate
31402
31403 @node Elaboration order
31404 @subsection Elaboration order
31405 @noindent
31406 The implementation can choose any elaboration order consistent with the unit
31407 dependency relationship.  This freedom means that some orders can result in
31408 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
31409 to invoke a subprogram its body has been elaborated, or to instantiate a
31410 generic before the generic body has been elaborated.  By default GNAT
31411 attempts to choose a safe order (one that will not encounter access before
31412 elaboration problems) by implicitly inserting @code{Elaborate} or
31413 @code{Elaborate_All} pragmas where
31414 needed.  However, this can lead to the creation of elaboration circularities
31415 and a resulting rejection of the program by gnatbind.  This issue is
31416 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
31417 In brief, there are several
31418 ways to deal with this situation:
31419
31420 @itemize @bullet
31421 @item
31422 Modify the program to eliminate the circularities, e.g.@: by moving
31423 elaboration-time code into explicitly-invoked procedures
31424 @item
31425 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
31426 @code{Elaborate} pragmas, and then inhibit the generation of implicit
31427 @code{Elaborate_All}
31428 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
31429 (by selectively suppressing elaboration checks via pragma
31430 @code{Suppress(Elaboration_Check)} when it is safe to do so).
31431 @end itemize
31432
31433 @node Target-specific aspects
31434 @subsection Target-specific aspects
31435 @noindent
31436 Low-level applications need to deal with machine addresses, data
31437 representations, interfacing with assembler code, and similar issues.  If
31438 such an Ada 83 application is being ported to different target hardware (for
31439 example where the byte endianness has changed) then you will need to
31440 carefully examine the program logic; the porting effort will heavily depend
31441 on the robustness of the original design.  Moreover, Ada 95 (and thus
31442 Ada 2005) are sometimes
31443 incompatible with typical Ada 83 compiler practices regarding implicit
31444 packing, the meaning of the Size attribute, and the size of access values.
31445 GNAT's approach to these issues is described in @ref{Representation Clauses}.
31446
31447 @node Compatibility with Other Ada Systems
31448 @section Compatibility with Other Ada Systems
31449
31450 @noindent
31451 If programs avoid the use of implementation dependent and
31452 implementation defined features, as documented in the @cite{Ada
31453 Reference Manual}, there should be a high degree of portability between
31454 GNAT and other Ada systems.  The following are specific items which
31455 have proved troublesome in moving Ada 95 programs from GNAT to other Ada 95
31456 compilers, but do not affect porting code to GNAT@.
31457 (As of @value{NOW}, GNAT is the only compiler available for Ada 2005;
31458 the following issues may or may not arise for Ada 2005 programs
31459 when other compilers appear.)
31460
31461 @table @emph
31462 @item Ada 83 Pragmas and Attributes
31463 Ada 95 compilers are allowed, but not required, to implement the missing
31464 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
31465 GNAT implements all such pragmas and attributes, eliminating this as
31466 a compatibility concern, but some other Ada 95 compilers reject these
31467 pragmas and attributes.
31468
31469 @item Specialized Needs Annexes
31470 GNAT implements the full set of special needs annexes.  At the
31471 current time, it is the only Ada 95 compiler to do so.  This means that
31472 programs making use of these features may not be portable to other Ada
31473 95 compilation systems.
31474
31475 @item Representation Clauses
31476 Some other Ada 95 compilers implement only the minimal set of
31477 representation clauses required by the Ada 95 reference manual.  GNAT goes
31478 far beyond this minimal set, as described in the next section.
31479 @end table
31480
31481 @node Representation Clauses
31482 @section Representation Clauses
31483
31484 @noindent
31485 The Ada 83 reference manual was quite vague in describing both the minimal
31486 required implementation of representation clauses, and also their precise
31487 effects.  Ada 95 (and thus also Ada 2005) are much more explicit, but the
31488 minimal set of capabilities required is still quite limited.
31489
31490 GNAT implements the full required set of capabilities in
31491 Ada 95 and Ada 2005, but also goes much further, and in particular
31492 an effort has been made to be compatible with existing Ada 83 usage to the
31493 greatest extent possible.
31494
31495 A few cases exist in which Ada 83 compiler behavior is incompatible with
31496 the requirements in Ada 95 (and thus also Ada 2005).  These are instances of
31497 intentional or accidental dependence on specific implementation dependent
31498 characteristics of these Ada 83 compilers.  The following is a list of
31499 the cases most likely to arise in existing Ada 83 code.
31500
31501 @table @emph
31502 @item Implicit Packing
31503 Some Ada 83 compilers allowed a Size specification to cause implicit
31504 packing of an array or record.  This could cause expensive implicit
31505 conversions for change of representation in the presence of derived
31506 types, and the Ada design intends to avoid this possibility.
31507 Subsequent AI's were issued to make it clear that such implicit
31508 change of representation in response to a Size clause is inadvisable,
31509 and this recommendation is represented explicitly in the Ada 95 (and Ada 2005)
31510 Reference Manuals as implementation advice that is followed by GNAT@.
31511 The problem will show up as an error
31512 message rejecting the size clause.  The fix is simply to provide
31513 the explicit pragma @code{Pack}, or for more fine tuned control, provide
31514 a Component_Size clause.
31515
31516 @item Meaning of Size Attribute
31517 The Size attribute in Ada 95 (and Ada 2005) for discrete types is defined as
31518 the minimal number of bits required to hold values of the type.  For example,
31519 on a 32-bit machine, the size of @code{Natural} will typically be 31 and not
31520 32 (since no sign bit is required).  Some Ada 83 compilers gave 31, and
31521 some 32 in this situation.  This problem will usually show up as a compile
31522 time error, but not always.  It is a good idea to check all uses of the
31523 'Size attribute when porting Ada 83 code.  The GNAT specific attribute
31524 Object_Size can provide a useful way of duplicating the behavior of
31525 some Ada 83 compiler systems.
31526
31527 @item Size of Access Types
31528 A common assumption in Ada 83 code is that an access type is in fact a pointer,
31529 and that therefore it will be the same size as a System.Address value.  This
31530 assumption is true for GNAT in most cases with one exception.  For the case of
31531 a pointer to an unconstrained array type (where the bounds may vary from one
31532 value of the access type to another), the default is to use a ``fat pointer'',
31533 which is represented as two separate pointers, one to the bounds, and one to
31534 the array.  This representation has a number of advantages, including improved
31535 efficiency.  However, it may cause some difficulties in porting existing Ada 83
31536 code which makes the assumption that, for example, pointers fit in 32 bits on
31537 a machine with 32-bit addressing.
31538
31539 To get around this problem, GNAT also permits the use of ``thin pointers'' for
31540 access types in this case (where the designated type is an unconstrained array
31541 type).  These thin pointers are indeed the same size as a System.Address value.
31542 To specify a thin pointer, use a size clause for the type, for example:
31543
31544 @smallexample @c ada
31545 type X is access all String;
31546 for X'Size use Standard'Address_Size;
31547 @end smallexample
31548
31549 @noindent
31550 which will cause the type X to be represented using a single pointer.
31551 When using this representation, the bounds are right behind the array.
31552 This representation is slightly less efficient, and does not allow quite
31553 such flexibility in the use of foreign pointers or in using the
31554 Unrestricted_Access attribute to create pointers to non-aliased objects.
31555 But for any standard portable use of the access type it will work in
31556 a functionally correct manner and allow porting of existing code.
31557 Note that another way of forcing a thin pointer representation
31558 is to use a component size clause for the element size in an array,
31559 or a record representation clause for an access field in a record.
31560 @end table
31561
31562 @ifclear vms
31563 @c This brief section is only in the non-VMS version
31564 @c The complete chapter on HP Ada is in the VMS version
31565 @node Compatibility with HP Ada 83
31566 @section Compatibility with HP Ada 83
31567
31568 @noindent
31569 The VMS version of GNAT fully implements all the pragmas and attributes
31570 provided by HP Ada 83, as well as providing the standard HP Ada 83
31571 libraries, including Starlet.  In addition, data layouts and parameter
31572 passing conventions are highly compatible.  This means that porting
31573 existing HP Ada 83 code to GNAT in VMS systems should be easier than
31574 most other porting efforts.  The following are some of the most
31575 significant differences between GNAT and HP Ada 83.
31576
31577 @table @emph
31578 @item Default floating-point representation
31579 In GNAT, the default floating-point format is IEEE, whereas in HP Ada 83,
31580 it is VMS format.  GNAT does implement the necessary pragmas
31581 (Long_Float, Float_Representation) for changing this default.
31582
31583 @item System
31584 The package System in GNAT exactly corresponds to the definition in the
31585 Ada 95 reference manual, which means that it excludes many of the
31586 HP Ada 83 extensions.  However, a separate package Aux_DEC is provided
31587 that contains the additional definitions, and a special pragma,
31588 Extend_System allows this package to be treated transparently as an
31589 extension of package System.
31590
31591 @item To_Address
31592 The definitions provided by Aux_DEC are exactly compatible with those
31593 in the HP Ada 83 version of System, with one exception.
31594 HP Ada provides the following declarations:
31595
31596 @smallexample @c ada
31597 TO_ADDRESS (INTEGER)
31598 TO_ADDRESS (UNSIGNED_LONGWORD)
31599 TO_ADDRESS (@i{universal_integer})
31600 @end smallexample
31601
31602 @noindent
31603 The version of TO_ADDRESS taking a @i{universal integer} argument is in fact
31604 an extension to Ada 83 not strictly compatible with the reference manual.
31605 In GNAT, we are constrained to be exactly compatible with the standard,
31606 and this means we cannot provide this capability.  In HP Ada 83, the
31607 point of this definition is to deal with a call like:
31608
31609 @smallexample @c ada
31610 TO_ADDRESS (16#12777#);
31611 @end smallexample
31612
31613 @noindent
31614 Normally, according to the Ada 83 standard, one would expect this to be
31615 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
31616 of TO_ADDRESS@.  However, in HP Ada 83, there is no ambiguity, since the
31617 definition using @i{universal_integer} takes precedence.
31618
31619 In GNAT, since the version with @i{universal_integer} cannot be supplied, it
31620 is not possible to be 100% compatible.  Since there are many programs using
31621 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
31622 to change the name of the function in the UNSIGNED_LONGWORD case, so the
31623 declarations provided in the GNAT version of AUX_Dec are:
31624
31625 @smallexample @c ada
31626 function To_Address (X : Integer) return Address;
31627 pragma Pure_Function (To_Address);
31628
31629 function To_Address_Long (X : Unsigned_Longword)
31630  return Address;
31631 pragma Pure_Function (To_Address_Long);
31632 @end smallexample
31633
31634 @noindent
31635 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
31636 change the name to TO_ADDRESS_LONG@.
31637
31638 @item Task_Id values
31639 The Task_Id values assigned will be different in the two systems, and GNAT
31640 does not provide a specified value for the Task_Id of the environment task,
31641 which in GNAT is treated like any other declared task.
31642 @end table
31643
31644 @noindent
31645 For full details on these and other less significant compatibility issues,
31646 see appendix E of the HP publication entitled @cite{HP Ada, Technical
31647 Overview and Comparison on HP Platforms}.
31648
31649 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
31650 attributes are recognized, although only a subset of them can sensibly
31651 be implemented.  The description of pragmas in @ref{Implementation
31652 Defined Pragmas,,, gnat_rm, GNAT Reference Manual}
31653 indicates whether or not they are applicable to non-VMS systems.
31654 @end ifclear
31655
31656 @ifset vms
31657 @node Transitioning to 64-Bit GNAT for OpenVMS
31658 @section Transitioning to 64-Bit @value{EDITION} for OpenVMS
31659
31660 @noindent
31661 This section is meant to assist users of pre-2006 @value{EDITION}
31662 for Alpha OpenVMS who are transitioning to 64-bit @value{EDITION},
31663 the version of the GNAT technology supplied in 2006 and later for
31664 OpenVMS on both Alpha and I64.
31665
31666 @menu
31667 * Introduction to transitioning::
31668 * Migration of 32 bit code::
31669 * Taking advantage of 64 bit addressing::
31670 * Technical details::
31671 @end menu
31672
31673 @node Introduction to transitioning
31674 @subsection Introduction
31675
31676 @noindent
31677 64-bit @value{EDITION} for Open VMS has been designed to meet
31678 three main goals:
31679
31680 @enumerate
31681 @item
31682 Providing a full conforming implementation of Ada 95 and Ada 2005
31683
31684 @item
31685 Allowing maximum backward compatibility, thus easing migration of existing
31686 Ada source code
31687
31688 @item
31689 Supplying a path for exploiting the full 64-bit address range
31690 @end enumerate
31691
31692 @noindent
31693 Ada's strong typing semantics has made it
31694 impractical to have different 32-bit and 64-bit modes. As soon as
31695 one object could possibly be outside the 32-bit address space, this
31696 would make it necessary for the @code{System.Address} type to be 64 bits.
31697 In particular, this would cause inconsistencies if 32-bit code is
31698 called from 64-bit code that raises an exception.
31699
31700 This issue has been resolved by always using 64-bit addressing
31701 at the system level, but allowing for automatic conversions between
31702 32-bit and 64-bit addresses where required. Thus users who
31703 do not currently require 64-bit addressing capabilities, can
31704 recompile their code with only minimal changes (and indeed
31705 if the code is written in portable Ada, with no assumptions about
31706 the size of the @code{Address} type, then no changes at all are necessary).
31707 At the same time,
31708 this approach provides a simple, gradual upgrade path to future
31709 use of larger memories than available for 32-bit systems.
31710 Also, newly written applications or libraries will by default
31711 be fully compatible with future systems exploiting 64-bit
31712 addressing capabilities.
31713
31714 @ref{Migration of 32 bit code}, will focus on porting applications
31715 that do not require more than 2 GB of
31716 addressable memory. This code will be referred to as
31717 @emph{32-bit code}.
31718 For applications intending to exploit the full 64-bit address space,
31719 @ref{Taking advantage of 64 bit addressing},
31720 will consider further changes that may be required.
31721 Such code will be referred to below as @emph{64-bit code}.
31722
31723 @node Migration of 32 bit code
31724 @subsection Migration of 32-bit code
31725
31726 @menu
31727 * Address types::
31728 * Access types::
31729 * Unchecked conversions::
31730 * Predefined constants::
31731 * Interfacing with C::
31732 * Experience with source compatibility::
31733 @end menu
31734
31735 @node Address types
31736 @subsubsection Address types
31737
31738 @noindent
31739 To solve the problem of mixing 64-bit and 32-bit addressing,
31740 while maintaining maximum backward compatibility, the following
31741 approach has been taken:
31742
31743 @itemize @bullet
31744 @item
31745 @code{System.Address} always has a size of 64 bits
31746
31747 @item
31748 @code{System.Short_Address} is a 32-bit subtype of @code{System.Address}
31749 @end itemize
31750
31751 @noindent
31752 Since @code{System.Short_Address} is a subtype of @code{System.Address},
31753 a @code{Short_Address}
31754 may be used where an @code{Address} is required, and vice versa, without
31755 needing explicit type conversions.
31756 By virtue of the Open VMS parameter passing conventions,
31757 even imported
31758 and exported subprograms that have 32-bit address parameters are
31759 compatible with those that have 64-bit address parameters.
31760 (See @ref{Making code 64 bit clean} for details.)
31761
31762 The areas that may need attention are those where record types have
31763 been defined that contain components of the type @code{System.Address}, and
31764 where objects of this type are passed to code expecting a record layout with
31765 32-bit addresses.
31766
31767 Different compilers on different platforms cannot be
31768 expected to represent the same type in the same way,
31769 since alignment constraints
31770 and other system-dependent properties affect the compiler's decision.
31771 For that reason, Ada code
31772 generally uses representation clauses to specify the expected
31773 layout where required.
31774
31775 If such a representation clause uses 32 bits for a component having
31776 the type @code{System.Address}, 64-bit @value{EDITION} for OpenVMS
31777 will detect that error and produce a specific diagnostic message.
31778 The developer should then determine whether the representation
31779 should be 64 bits or not and make either of two changes:
31780 change the size to 64 bits and leave the type as @code{System.Address}, or
31781 leave the size as 32 bits and change the type to @code{System.Short_Address}.
31782 Since @code{Short_Address} is a subtype of @code{Address}, no changes are
31783 required in any code setting or accessing the field; the compiler will
31784 automatically perform any needed conversions between address
31785 formats.
31786
31787 @node Access types
31788 @subsubsection Access types
31789
31790 @noindent
31791 By default, objects designated by access values are always
31792 allocated in the 32-bit
31793 address space. Thus legacy code will never contain
31794 any objects that are not addressable with 32-bit addresses, and
31795 the compiler will never raise exceptions as result of mixing
31796 32-bit and 64-bit addresses.
31797
31798 However, the access values themselves are represented in 64 bits, for optimum
31799 performance and future compatibility with 64-bit code. As was
31800 the case with @code{System.Address}, the compiler will give an error message
31801 if an object or record component has a representation clause that
31802 requires the access value to fit in 32 bits. In such a situation,
31803 an explicit size clause for the access type, specifying 32 bits,
31804 will have the desired effect.
31805
31806 General access types (declared with @code{access all}) can never be
31807 32 bits, as values of such types must be able to refer to any object
31808 of the  designated type,
31809 including objects residing outside the 32-bit address range.
31810 Existing Ada 83 code will not contain such type definitions,
31811 however, since general access types were introduced in Ada 95.
31812
31813 @node Unchecked conversions
31814 @subsubsection Unchecked conversions
31815
31816 @noindent
31817 In the case of an @code{Unchecked_Conversion} where the source type is a
31818 64-bit access type or the type @code{System.Address}, and the target
31819 type is a 32-bit type, the compiler will generate a warning.
31820 Even though the generated code will still perform the required
31821 conversions, it is highly recommended in these cases to use
31822 respectively a 32-bit access type or @code{System.Short_Address}
31823 as the source type.
31824
31825 @node Predefined constants
31826 @subsubsection Predefined constants
31827
31828 @noindent
31829 The following table shows the correspondence between pre-2006 versions of
31830 @value{EDITION} on Alpha OpenVMS (``Old'') and 64-bit @value{EDITION}
31831 (``New''):
31832
31833 @multitable {@code{System.Short_Memory_Size}} {2**32} {2**64}
31834 @item   @b{Constant}                     @tab @b{Old} @tab @b{New}
31835 @item   @code{System.Word_Size}          @tab 32      @tab 64
31836 @item   @code{System.Memory_Size}        @tab 2**32   @tab 2**64
31837 @item   @code{System.Short_Memory_Size}  @tab 2**32   @tab 2**32
31838 @item   @code{System.Address_Size}       @tab 32      @tab 64
31839 @end multitable
31840
31841 @noindent
31842 If you need to refer to the specific
31843 memory size of a 32-bit implementation, instead of the
31844 actual memory size, use @code{System.Short_Memory_Size}
31845 rather than @code{System.Memory_Size}.
31846 Similarly, references to @code{System.Address_Size} may need
31847 to be replaced by @code{System.Short_Address'Size}.
31848 The program @command{gnatfind} may be useful for locating
31849 references to the above constants, so that you can verify that they
31850 are still correct.
31851
31852 @node Interfacing with C
31853 @subsubsection Interfacing with C
31854
31855 @noindent
31856 In order to minimize the impact of the transition to 64-bit addresses on
31857 legacy programs, some fundamental types in the @code{Interfaces.C}
31858 package hierarchy continue to be represented in 32 bits.
31859 These types are: @code{ptrdiff_t}, @code{size_t}, and @code{chars_ptr}.
31860 This eases integration with the default HP C layout choices, for example
31861 as found in the system routines in @code{DECC$SHR.EXE}.
31862 Because of this implementation choice, the type fully compatible with
31863 @code{chars_ptr} is now @code{Short_Address} and not @code{Address}.
31864 Depending on the context the compiler will issue a
31865 warning or an error when type @code{Address} is used, alerting the user to a
31866 potential problem. Otherwise 32-bit programs that use
31867 @code{Interfaces.C} should normally not require code modifications
31868
31869 The other issue arising with C interfacing concerns pragma @code{Convention}.
31870 For VMS 64-bit systems, there is an issue of the appropriate default size
31871 of C convention pointers in the absence of an explicit size clause. The HP
31872 C compiler can choose either 32 or 64 bits depending on compiler options.
31873 GNAT chooses 32-bits rather than 64-bits in the default case where no size
31874 clause is given. This proves a better choice for porting 32-bit legacy
31875 applications. In order to have a 64-bit representation, it is necessary to
31876 specify a size representation clause. For example:
31877
31878 @smallexample @c ada
31879 type int_star is access Interfaces.C.int;
31880 pragma Convention(C, int_star);
31881 for int_star'Size use 64;  -- Necessary to get 64 and not 32 bits
31882 @end smallexample
31883
31884 @node Experience with source compatibility
31885 @subsubsection Experience with source compatibility
31886
31887 @noindent
31888 The Security Server and STARLET on I64 provide an interesting ``test case''
31889 for source compatibility issues, since it is in such system code
31890 where assumptions about @code{Address} size might be expected to occur.
31891 Indeed, there were a small number of occasions in the Security Server
31892 file @file{jibdef.ads}
31893 where a representation clause for a record type specified
31894 32 bits for a component of type @code{Address}.
31895 All of these errors were detected by the compiler.
31896 The repair was obvious and immediate; to simply replace @code{Address} by
31897 @code{Short_Address}.
31898
31899 In the case of STARLET, there were several record types that should
31900 have had representation clauses but did not.  In these record types
31901 there was an implicit assumption that an @code{Address} value occupied
31902 32 bits.
31903 These compiled without error, but their usage resulted in run-time error
31904 returns from STARLET system calls.
31905 Future GNAT technology enhancements may include a tool that detects and flags
31906 these sorts of potential source code porting problems.
31907
31908 @c ****************************************
31909 @node Taking advantage of 64 bit addressing
31910 @subsection Taking advantage of 64-bit addressing
31911
31912 @menu
31913 * Making code 64 bit clean::
31914 * Allocating memory from the 64 bit storage pool::
31915 * Restrictions on use of 64 bit objects::
31916 * Using 64 bit storage pools by default::
31917 * General access types::
31918 * STARLET and other predefined libraries::
31919 @end menu
31920
31921 @node Making code 64 bit clean
31922 @subsubsection Making code 64-bit clean
31923
31924 @noindent
31925 In order to prevent problems that may occur when (parts of) a
31926 system start using memory outside the 32-bit address range,
31927 we recommend some additional guidelines:
31928
31929 @itemize @bullet
31930 @item
31931 For imported subprograms that take parameters of the
31932 type @code{System.Address}, ensure that these subprograms can
31933 indeed handle 64-bit addresses. If not, or when in doubt,
31934 change the subprogram declaration to specify
31935 @code{System.Short_Address} instead.
31936
31937 @item
31938 Resolve all warnings related to size mismatches in
31939 unchecked conversions. Failing to do so causes
31940 erroneous execution if the source object is outside
31941 the 32-bit address space.
31942
31943 @item
31944 (optional) Explicitly use the 32-bit storage pool
31945 for access types used in a 32-bit context, or use
31946 generic access types where possible
31947 (@pxref{Restrictions on use of 64 bit objects}).
31948 @end itemize
31949
31950 @noindent
31951 If these rules are followed, the compiler will automatically insert
31952 any necessary checks to ensure that no addresses or access values
31953 passed to 32-bit code ever refer to objects outside the 32-bit
31954 address range.
31955 Any attempt to do this will raise @code{Constraint_Error}.
31956
31957 @node Allocating memory from the 64 bit storage pool
31958 @subsubsection Allocating memory from the 64-bit storage pool
31959
31960 @noindent
31961 For any access type @code{T} that potentially requires memory allocations
31962 beyond the 32-bit address space,
31963 use the following representation clause:
31964
31965 @smallexample @c ada
31966    for T'Storage_Pool use System.Pool_64;
31967 @end smallexample
31968
31969 @node Restrictions on use of 64 bit objects
31970 @subsubsection Restrictions on use of 64-bit objects
31971
31972 @noindent
31973 Taking the address of an object allocated from a 64-bit storage pool,
31974 and then passing this address to a subprogram expecting
31975 @code{System.Short_Address},
31976 or assigning it to a variable of type @code{Short_Address}, will cause
31977 @code{Constraint_Error} to be raised. In case the code is not 64-bit clean
31978 (@pxref{Making code 64 bit clean}), or checks are suppressed,
31979 no exception is raised and execution
31980 will become erroneous.
31981
31982 @node Using 64 bit storage pools by default
31983 @subsubsection Using 64-bit storage pools by default
31984
31985 @noindent
31986 In some cases it may be desirable to have the compiler allocate
31987 from 64-bit storage pools by default. This may be the case for
31988 libraries that are 64-bit clean, but may be used in both 32-bit
31989 and 64-bit contexts. For these cases the following configuration
31990 pragma may be specified:
31991
31992 @smallexample @c ada
31993   pragma Pool_64_Default;
31994 @end smallexample
31995
31996 @noindent
31997 Any code compiled in the context of this pragma will by default
31998 use the @code{System.Pool_64} storage pool. This default may be overridden
31999 for a specific access type @code{T} by the representation clause:
32000
32001 @smallexample @c ada
32002    for T'Storage_Pool use System.Pool_32;
32003 @end smallexample
32004
32005 @noindent
32006 Any object whose address may be passed to a subprogram with a
32007 @code{Short_Address} argument, or assigned to a variable of type
32008 @code{Short_Address}, needs to be allocated from this pool.
32009
32010 @node General access types
32011 @subsubsection General access types
32012
32013 @noindent
32014 Objects designated by access values from a
32015 general access type (declared with @code{access all}) are never allocated
32016 from a 64-bit storage pool. Code that uses general access types will
32017 accept objects allocated in either 32-bit or 64-bit address spaces,
32018 but never allocate objects outside the 32-bit address space.
32019 Using general access types ensures maximum compatibility with both
32020 32-bit and 64-bit code.
32021
32022 @node STARLET and other predefined libraries
32023 @subsubsection STARLET and other predefined libraries
32024
32025 @noindent
32026 All code that comes as part of GNAT is 64-bit clean, but the
32027 restrictions given in @ref{Restrictions on use of 64 bit objects},
32028 still apply. Look at the package
32029 specs to see in which contexts objects allocated
32030 in 64-bit address space are acceptable.
32031
32032 @node Technical details
32033 @subsection Technical details
32034
32035 @noindent
32036 64-bit @value{EDITION} for Open VMS takes advantage of the freedom given in the
32037 Ada standard with respect to the type of @code{System.Address}. Previous
32038 versions of GNAT Pro have defined this type as private and implemented it as a
32039 modular type.
32040
32041 In order to allow defining @code{System.Short_Address} as a proper subtype,
32042 and to match the implicit sign extension in parameter passing,
32043 in 64-bit @value{EDITION} for Open VMS, @code{System.Address} is defined as a
32044 visible (i.e., non-private) integer type.
32045 Standard operations on the type, such as the binary operators ``+'', ``-'',
32046 etc., that take @code{Address} operands and return an @code{Address} result,
32047 have been hidden by declaring these
32048 @code{abstract}, a feature introduced in Ada 95 that helps avoid the potential
32049 ambiguities that would otherwise result from overloading.
32050 (Note that, although @code{Address} is a visible integer type,
32051 good programming practice dictates against exploiting the type's
32052 integer properties such as literals, since this will compromise
32053 code portability.)
32054
32055 Defining @code{Address} as a visible integer type helps achieve
32056 maximum compatibility for existing Ada code,
32057 without sacrificing the capabilities of the 64-bit architecture.
32058 @end ifset
32059
32060 @c ************************************************
32061 @ifset unw
32062 @node Microsoft Windows Topics
32063 @appendix Microsoft Windows Topics
32064 @cindex Windows NT
32065 @cindex Windows 95
32066 @cindex Windows 98
32067
32068 @noindent
32069 This chapter describes topics that are specific to the Microsoft Windows
32070 platforms (NT, 2000, and XP Professional).
32071
32072 @menu
32073 * Using GNAT on Windows::
32074 * Using a network installation of GNAT::
32075 * CONSOLE and WINDOWS subsystems::
32076 * Temporary Files::
32077 * Mixed-Language Programming on Windows::
32078 * Windows Calling Conventions::
32079 * Introduction to Dynamic Link Libraries (DLLs)::
32080 * Using DLLs with GNAT::
32081 * Building DLLs with GNAT::
32082 * Building DLLs with GNAT Project files::
32083 * Building DLLs with gnatdll::
32084 * GNAT and Windows Resources::
32085 * Debugging a DLL::
32086 * Setting Stack Size from gnatlink::
32087 * Setting Heap Size from gnatlink::
32088 @end menu
32089
32090 @node Using GNAT on Windows
32091 @section Using GNAT on Windows
32092
32093 @noindent
32094 One of the strengths of the GNAT technology is that its tool set
32095 (@command{gcc}, @command{gnatbind}, @command{gnatlink}, @command{gnatmake}, the
32096 @code{gdb} debugger, etc.) is used in the same way regardless of the
32097 platform.
32098
32099 On Windows this tool set is complemented by a number of Microsoft-specific
32100 tools that have been provided to facilitate interoperability with Windows
32101 when this is required. With these tools:
32102
32103 @itemize @bullet
32104
32105 @item
32106 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
32107 subsystems.
32108
32109 @item
32110 You can use any Dynamically Linked Library (DLL) in your Ada code (both
32111 relocatable and non-relocatable DLLs are supported).
32112
32113 @item
32114 You can build Ada DLLs for use in other applications. These applications
32115 can be written in a language other than Ada (e.g., C, C++, etc). Again both
32116 relocatable and non-relocatable Ada DLLs are supported.
32117
32118 @item
32119 You can include Windows resources in your Ada application.
32120
32121 @item
32122 You can use or create COM/DCOM objects.
32123 @end itemize
32124
32125 @noindent
32126 Immediately below are listed all known general GNAT-for-Windows restrictions.
32127 Other restrictions about specific features like Windows Resources and DLLs
32128 are listed in separate sections below.
32129
32130 @itemize @bullet
32131
32132 @item
32133 It is not possible to use @code{GetLastError} and @code{SetLastError}
32134 when tasking, protected records, or exceptions are used. In these
32135 cases, in order to implement Ada semantics, the GNAT run-time system
32136 calls certain Win32 routines that set the last error variable to 0 upon
32137 success. It should be possible to use @code{GetLastError} and
32138 @code{SetLastError} when tasking, protected record, and exception
32139 features are not used, but it is not guaranteed to work.
32140
32141 @item
32142 It is not possible to link against Microsoft libraries except for
32143 import libraries. The library must be built to be compatible with
32144 @file{MSVCRT.LIB} (/MD Microsoft compiler option), @file{LIBC.LIB} and
32145 @file{LIBCMT.LIB} (/ML or /MT Microsoft compiler options) are known to
32146 not be compatible with the GNAT runtime. Even if the library is
32147 compatible with @file{MSVCRT.LIB} it is not guaranteed to work.
32148
32149 @item
32150 When the compilation environment is located on FAT32 drives, users may
32151 experience recompilations of the source files that have not changed if
32152 Daylight Saving Time (DST) state has changed since the last time files
32153 were compiled. NTFS drives do not have this problem.
32154
32155 @item
32156 No components of the GNAT toolset use any entries in the Windows
32157 registry. The only entries that can be created are file associations and
32158 PATH settings, provided the user has chosen to create them at installation
32159 time, as well as some minimal book-keeping information needed to correctly
32160 uninstall or integrate different GNAT products.
32161 @end itemize
32162
32163 @node Using a network installation of GNAT
32164 @section Using a network installation of GNAT
32165
32166 @noindent
32167 Make sure the system on which GNAT is installed is accessible from the
32168 current machine, i.e., the install location is shared over the network.
32169 Shared resources are accessed on Windows by means of UNC paths, which
32170 have the format @code{\\server\sharename\path}
32171
32172 In order to use such a network installation, simply add the UNC path of the
32173 @file{bin} directory of your GNAT installation in front of your PATH. For
32174 example, if GNAT is installed in @file{\GNAT} directory of a share location
32175 called @file{c-drive} on a machine @file{LOKI}, the following command will
32176 make it available:
32177
32178 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
32179
32180 Be aware that every compilation using the network installation results in the
32181 transfer of large amounts of data across the network and will likely cause
32182 serious performance penalty.
32183
32184 @node CONSOLE and WINDOWS subsystems
32185 @section CONSOLE and WINDOWS subsystems
32186 @cindex CONSOLE Subsystem
32187 @cindex WINDOWS Subsystem
32188 @cindex -mwindows
32189
32190 @noindent
32191 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
32192 (which is the default subsystem) will always create a console when
32193 launching the application. This is not something desirable when the
32194 application has a Windows GUI. To get rid of this console the
32195 application must be using the @code{WINDOWS} subsystem. To do so
32196 the @option{-mwindows} linker option must be specified.
32197
32198 @smallexample
32199 $ gnatmake winprog -largs -mwindows
32200 @end smallexample
32201
32202 @node Temporary Files
32203 @section Temporary Files
32204 @cindex Temporary files
32205
32206 @noindent
32207 It is possible to control where temporary files gets created by setting
32208 the @env{TMP} environment variable. The file will be created:
32209
32210 @itemize
32211 @item Under the directory pointed to by the @env{TMP} environment variable if
32212 this directory exists.
32213
32214 @item Under @file{c:\temp}, if the @env{TMP} environment variable is not
32215 set (or not pointing to a directory) and if this directory exists.
32216
32217 @item Under the current working directory otherwise.
32218 @end itemize
32219
32220 @noindent
32221 This allows you to determine exactly where the temporary
32222 file will be created. This is particularly useful in networked
32223 environments where you may not have write access to some
32224 directories.
32225
32226 @node Mixed-Language Programming on Windows
32227 @section Mixed-Language Programming on Windows
32228
32229 @noindent
32230 Developing pure Ada applications on Windows is no different than on
32231 other GNAT-supported platforms. However, when developing or porting an
32232 application that contains a mix of Ada and C/C++, the choice of your
32233 Windows C/C++ development environment conditions your overall
32234 interoperability strategy.
32235
32236 If you use @command{gcc} to compile the non-Ada part of your application,
32237 there are no Windows-specific restrictions that affect the overall
32238 interoperability with your Ada code. If you plan to use
32239 Microsoft tools (e.g.@: Microsoft Visual C/C++), you should be aware of
32240 the following limitations:
32241
32242 @itemize @bullet
32243 @item
32244 You cannot link your Ada code with an object or library generated with
32245 Microsoft tools if these use the @code{.tls} section (Thread Local
32246 Storage section) since the GNAT linker does not yet support this section.
32247
32248 @item
32249 You cannot link your Ada code with an object or library generated with
32250 Microsoft tools if these use I/O routines other than those provided in
32251 the Microsoft DLL: @code{msvcrt.dll}. This is because the GNAT run time
32252 uses the services of @code{msvcrt.dll} for its I/Os. Use of other I/O
32253 libraries can cause a conflict with @code{msvcrt.dll} services. For
32254 instance Visual C++ I/O stream routines conflict with those in
32255 @code{msvcrt.dll}.
32256 @end itemize
32257
32258 @noindent
32259 If you do want to use the Microsoft tools for your non-Ada code and hit one
32260 of the above limitations, you have two choices:
32261
32262 @enumerate
32263 @item
32264 Encapsulate your non-Ada code in a DLL to be linked with your Ada
32265 application. In this case, use the Microsoft or whatever environment to
32266 build the DLL and use GNAT to build your executable
32267 (@pxref{Using DLLs with GNAT}).
32268
32269 @item
32270 Or you can encapsulate your Ada code in a DLL to be linked with the
32271 other part of your application. In this case, use GNAT to build the DLL
32272 (@pxref{Building DLLs with GNAT}) and use the Microsoft or whatever
32273 environment to build your executable.
32274 @end enumerate
32275
32276 @node Windows Calling Conventions
32277 @section Windows Calling Conventions
32278 @findex Stdcall
32279 @findex APIENTRY
32280
32281 @menu
32282 * C Calling Convention::
32283 * Stdcall Calling Convention::
32284 * Win32 Calling Convention::
32285 * DLL Calling Convention::
32286 @end menu
32287
32288 @noindent
32289 When a subprogram @code{F} (caller) calls a subprogram @code{G}
32290 (callee), there are several ways to push @code{G}'s parameters on the
32291 stack and there are several possible scenarios to clean up the stack
32292 upon @code{G}'s return. A calling convention is an agreed upon software
32293 protocol whereby the responsibilities between the caller (@code{F}) and
32294 the callee (@code{G}) are clearly defined. Several calling conventions
32295 are available for Windows:
32296
32297 @itemize @bullet
32298 @item
32299 @code{C} (Microsoft defined)
32300
32301 @item
32302 @code{Stdcall} (Microsoft defined)
32303
32304 @item
32305 @code{Win32} (GNAT specific)
32306
32307 @item
32308 @code{DLL} (GNAT specific)
32309 @end itemize
32310
32311 @node C Calling Convention
32312 @subsection @code{C} Calling Convention
32313
32314 @noindent
32315 This is the default calling convention used when interfacing to C/C++
32316 routines compiled with either @command{gcc} or Microsoft Visual C++.
32317
32318 In the @code{C} calling convention subprogram parameters are pushed on the
32319 stack by the caller from right to left. The caller itself is in charge of
32320 cleaning up the stack after the call. In addition, the name of a routine
32321 with @code{C} calling convention is mangled by adding a leading underscore.
32322
32323 The name to use on the Ada side when importing (or exporting) a routine
32324 with @code{C} calling convention is the name of the routine. For
32325 instance the C function:
32326
32327 @smallexample
32328 int get_val (long);
32329 @end smallexample
32330
32331 @noindent
32332 should be imported from Ada as follows:
32333
32334 @smallexample @c ada
32335 @group
32336 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
32337 pragma Import (C, Get_Val, External_Name => "get_val");
32338 @end group
32339 @end smallexample
32340
32341 @noindent
32342 Note that in this particular case the @code{External_Name} parameter could
32343 have been omitted since, when missing, this parameter is taken to be the
32344 name of the Ada entity in lower case. When the @code{Link_Name} parameter
32345 is missing, as in the above example, this parameter is set to be the
32346 @code{External_Name} with a leading underscore.
32347
32348 When importing a variable defined in C, you should always use the @code{C}
32349 calling convention unless the object containing the variable is part of a
32350 DLL (in which case you should use the @code{Stdcall} calling
32351 convention, @pxref{Stdcall Calling Convention}).
32352
32353 @node Stdcall Calling Convention
32354 @subsection @code{Stdcall} Calling Convention
32355
32356 @noindent
32357 This convention, which was the calling convention used for Pascal
32358 programs, is used by Microsoft for all the routines in the Win32 API for
32359 efficiency reasons. It must be used to import any routine for which this
32360 convention was specified.
32361
32362 In the @code{Stdcall} calling convention subprogram parameters are pushed
32363 on the stack by the caller from right to left. The callee (and not the
32364 caller) is in charge of cleaning the stack on routine exit. In addition,
32365 the name of a routine with @code{Stdcall} calling convention is mangled by
32366 adding a leading underscore (as for the @code{C} calling convention) and a
32367 trailing @code{@@}@code{@var{nn}}, where @var{nn} is the overall size (in
32368 bytes) of the parameters passed to the routine.
32369
32370 The name to use on the Ada side when importing a C routine with a
32371 @code{Stdcall} calling convention is the name of the C routine. The leading
32372 underscore and trailing @code{@@}@code{@var{nn}} are added automatically by
32373 the compiler. For instance the Win32 function:
32374
32375 @smallexample
32376 @b{APIENTRY} int get_val (long);
32377 @end smallexample
32378
32379 @noindent
32380 should be imported from Ada as follows:
32381
32382 @smallexample @c ada
32383 @group
32384 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
32385 pragma Import (Stdcall, Get_Val);
32386 --  On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
32387 @end group
32388 @end smallexample
32389
32390 @noindent
32391 As for the @code{C} calling convention, when the @code{External_Name}
32392 parameter is missing, it is taken to be the name of the Ada entity in lower
32393 case. If instead of writing the above import pragma you write:
32394
32395 @smallexample @c ada
32396 @group
32397 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
32398 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
32399 @end group
32400 @end smallexample
32401
32402 @noindent
32403 then the imported routine is @code{_retrieve_val@@4}. However, if instead
32404 of specifying the @code{External_Name} parameter you specify the
32405 @code{Link_Name} as in the following example:
32406
32407 @smallexample @c ada
32408 @group
32409 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
32410 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
32411 @end group
32412 @end smallexample
32413
32414 @noindent
32415 then the imported routine is @code{retrieve_val}, that is, there is no
32416 decoration at all. No leading underscore and no Stdcall suffix
32417 @code{@@}@code{@var{nn}}.
32418
32419 @noindent
32420 This is especially important as in some special cases a DLL's entry
32421 point name lacks a trailing @code{@@}@code{@var{nn}} while the exported
32422 name generated for a call has it.
32423
32424 @noindent
32425 It is also possible to import variables defined in a DLL by using an
32426 import pragma for a variable. As an example, if a DLL contains a
32427 variable defined as:
32428
32429 @smallexample
32430 int my_var;
32431 @end smallexample
32432
32433 @noindent
32434 then, to access this variable from Ada you should write:
32435
32436 @smallexample @c ada
32437 @group
32438 My_Var : Interfaces.C.int;
32439 pragma Import (Stdcall, My_Var);
32440 @end group
32441 @end smallexample
32442
32443 @noindent
32444 Note that to ease building cross-platform bindings this convention
32445 will be handled as a @code{C} calling convention on non-Windows platforms.
32446
32447 @node Win32 Calling Convention
32448 @subsection @code{Win32} Calling Convention
32449
32450 @noindent
32451 This convention, which is GNAT-specific is fully equivalent to the
32452 @code{Stdcall} calling convention described above.
32453
32454 @node DLL Calling Convention
32455 @subsection @code{DLL} Calling Convention
32456
32457 @noindent
32458 This convention, which is GNAT-specific is fully equivalent to the
32459 @code{Stdcall} calling convention described above.
32460
32461 @node Introduction to Dynamic Link Libraries (DLLs)
32462 @section Introduction to Dynamic Link Libraries (DLLs)
32463 @findex DLL
32464
32465 @noindent
32466 A Dynamically Linked Library (DLL) is a library that can be shared by
32467 several applications running under Windows. A DLL can contain any number of
32468 routines and variables.
32469
32470 One advantage of DLLs is that you can change and enhance them without
32471 forcing all the applications that depend on them to be relinked or
32472 recompiled. However, you should be aware than all calls to DLL routines are
32473 slower since, as you will understand below, such calls are indirect.
32474
32475 To illustrate the remainder of this section, suppose that an application
32476 wants to use the services of a DLL @file{API.dll}. To use the services
32477 provided by @file{API.dll} you must statically link against the DLL or
32478 an import library which contains a jump table with an entry for each
32479 routine and variable exported by the DLL. In the Microsoft world this
32480 import library is called @file{API.lib}. When using GNAT this import
32481 library is called either @file{libAPI.dll.a}, @file{libapi.dll.a},
32482 @file{libAPI.a} or @file{libapi.a} (names are case insensitive).
32483
32484 After you have linked your application with the DLL or the import library
32485 and you run your application, here is what happens:
32486
32487 @enumerate
32488 @item
32489 Your application is loaded into memory.
32490
32491 @item
32492 The DLL @file{API.dll} is mapped into the address space of your
32493 application. This means that:
32494
32495 @itemize @bullet
32496 @item
32497 The DLL will use the stack of the calling thread.
32498
32499 @item
32500 The DLL will use the virtual address space of the calling process.
32501
32502 @item
32503 The DLL will allocate memory from the virtual address space of the calling
32504 process.
32505
32506 @item
32507 Handles (pointers) can be safely exchanged between routines in the DLL
32508 routines and routines in the application using the DLL.
32509 @end itemize
32510
32511 @item
32512 The entries in the jump table (from the import library @file{libAPI.dll.a}
32513 or @file{API.lib} or automatically created when linking against a DLL)
32514 which is part of your application are initialized with the addresses
32515 of the routines and variables in @file{API.dll}.
32516
32517 @item
32518 If present in @file{API.dll}, routines @code{DllMain} or
32519 @code{DllMainCRTStartup} are invoked. These routines typically contain
32520 the initialization code needed for the well-being of the routines and
32521 variables exported by the DLL.
32522 @end enumerate
32523
32524 @noindent
32525 There is an additional point which is worth mentioning. In the Windows
32526 world there are two kind of DLLs: relocatable and non-relocatable
32527 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
32528 in the target application address space. If the addresses of two
32529 non-relocatable DLLs overlap and these happen to be used by the same
32530 application, a conflict will occur and the application will run
32531 incorrectly. Hence, when possible, it is always preferable to use and
32532 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
32533 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
32534 User's Guide) removes the debugging symbols from the DLL but the DLL can
32535 still be relocated.
32536
32537 As a side note, an interesting difference between Microsoft DLLs and
32538 Unix shared libraries, is the fact that on most Unix systems all public
32539 routines are exported by default in a Unix shared library, while under
32540 Windows it is possible (but not required) to list exported routines in
32541 a definition file (@pxref{The Definition File}).
32542
32543 @node Using DLLs with GNAT
32544 @section Using DLLs with GNAT
32545
32546 @menu
32547 * Creating an Ada Spec for the DLL Services::
32548 * Creating an Import Library::
32549 @end menu
32550
32551 @noindent
32552 To use the services of a DLL, say @file{API.dll}, in your Ada application
32553 you must have:
32554
32555 @enumerate
32556 @item
32557 The Ada spec for the routines and/or variables you want to access in
32558 @file{API.dll}. If not available this Ada spec must be built from the C/C++
32559 header files provided with the DLL.
32560
32561 @item
32562 The import library (@file{libAPI.dll.a} or @file{API.lib}). As previously
32563 mentioned an import library is a statically linked library containing the
32564 import table which will be filled at load time to point to the actual
32565 @file{API.dll} routines. Sometimes you don't have an import library for the
32566 DLL you want to use. The following sections will explain how to build
32567 one. Note that this is optional.
32568
32569 @item
32570 The actual DLL, @file{API.dll}.
32571 @end enumerate
32572
32573 @noindent
32574 Once you have all the above, to compile an Ada application that uses the
32575 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
32576 you simply issue the command
32577
32578 @smallexample
32579 $ gnatmake my_ada_app -largs -lAPI
32580 @end smallexample
32581
32582 @noindent
32583 The argument @option{-largs -lAPI} at the end of the @command{gnatmake} command
32584 tells the GNAT linker to look first for a library named @file{API.lib}
32585 (Microsoft-style name) and if not found for a libraries named
32586 @file{libAPI.dll.a}, @file{API.dll.a} or @file{libAPI.a}.
32587 (GNAT-style name). Note that if the Ada package spec for @file{API.dll}
32588 contains the following pragma
32589
32590 @smallexample @c ada
32591 pragma Linker_Options ("-lAPI");
32592 @end smallexample
32593
32594 @noindent
32595 you do not have to add @option{-largs -lAPI} at the end of the
32596 @command{gnatmake} command.
32597
32598 If any one of the items above is missing you will have to create it
32599 yourself. The following sections explain how to do so using as an
32600 example a fictitious DLL called @file{API.dll}.
32601
32602 @node Creating an Ada Spec for the DLL Services
32603 @subsection Creating an Ada Spec for the DLL Services
32604
32605 @noindent
32606 A DLL typically comes with a C/C++ header file which provides the
32607 definitions of the routines and variables exported by the DLL. The Ada
32608 equivalent of this header file is a package spec that contains definitions
32609 for the imported entities. If the DLL you intend to use does not come with
32610 an Ada spec you have to generate one such spec yourself. For example if
32611 the header file of @file{API.dll} is a file @file{api.h} containing the
32612 following two definitions:
32613
32614 @smallexample
32615 @group
32616 @cartouche
32617 int some_var;
32618 int get (char *);
32619 @end cartouche
32620 @end group
32621 @end smallexample
32622
32623 @noindent
32624 then the equivalent Ada spec could be:
32625
32626 @smallexample @c ada
32627 @group
32628 @cartouche
32629 with Interfaces.C.Strings;
32630 package API is
32631    use Interfaces;
32632
32633    Some_Var : C.int;
32634    function Get (Str : C.Strings.Chars_Ptr) return C.int;
32635
32636 private
32637    pragma Import (C, Get);
32638    pragma Import (DLL, Some_Var);
32639 end API;
32640 @end cartouche
32641 @end group
32642 @end smallexample
32643
32644 @noindent
32645 Note that a variable is
32646 @strong{always imported with a Stdcall convention}. A function
32647 can have @code{C} or @code{Stdcall} convention.
32648 (@pxref{Windows Calling Conventions}).
32649
32650 @node Creating an Import Library
32651 @subsection Creating an Import Library
32652 @cindex Import library
32653
32654 @menu
32655 * The Definition File::
32656 * GNAT-Style Import Library::
32657 * Microsoft-Style Import Library::
32658 @end menu
32659
32660 @noindent
32661 If a Microsoft-style import library @file{API.lib} or a GNAT-style
32662 import library @file{libAPI.dll.a} or @file{libAPI.a} is available
32663 with @file{API.dll} you can skip this section. You can also skip this
32664 section if @file{API.dll} or @file{libAPI.dll} is built with GNU tools
32665 as in this case it is possible to link directly against the
32666 DLL. Otherwise read on.
32667
32668 @node The Definition File
32669 @subsubsection The Definition File
32670 @cindex Definition file
32671 @findex .def
32672
32673 @noindent
32674 As previously mentioned, and unlike Unix systems, the list of symbols
32675 that are exported from a DLL must be provided explicitly in Windows.
32676 The main goal of a definition file is precisely that: list the symbols
32677 exported by a DLL. A definition file (usually a file with a @code{.def}
32678 suffix) has the following structure:
32679
32680 @smallexample
32681 @group
32682 @cartouche
32683 @r{[}LIBRARY @var{name}@r{]}
32684 @r{[}DESCRIPTION @var{string}@r{]}
32685 EXPORTS
32686    @var{symbol1}
32687    @var{symbol2}
32688    @dots{}
32689 @end cartouche
32690 @end group
32691 @end smallexample
32692
32693 @table @code
32694 @item LIBRARY @var{name}
32695 This section, which is optional, gives the name of the DLL.
32696
32697 @item DESCRIPTION @var{string}
32698 This section, which is optional, gives a description string that will be
32699 embedded in the import library.
32700
32701 @item EXPORTS
32702 This section gives the list of exported symbols (procedures, functions or
32703 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
32704 section of @file{API.def} looks like:
32705
32706 @smallexample
32707 @group
32708 @cartouche
32709 EXPORTS
32710    some_var
32711    get
32712 @end cartouche
32713 @end group
32714 @end smallexample
32715 @end table
32716
32717 @noindent
32718 Note that you must specify the correct suffix (@code{@@}@code{@var{nn}})
32719 (@pxref{Windows Calling Conventions}) for a Stdcall
32720 calling convention function in the exported symbols list.
32721
32722 @noindent
32723 There can actually be other sections in a definition file, but these
32724 sections are not relevant to the discussion at hand.
32725
32726 @node GNAT-Style Import Library
32727 @subsubsection GNAT-Style Import Library
32728
32729 @noindent
32730 To create a static import library from @file{API.dll} with the GNAT tools
32731 you should proceed as follows:
32732
32733 @enumerate
32734 @item
32735 Create the definition file @file{API.def} (@pxref{The Definition File}).
32736 For that use the @code{dll2def} tool as follows:
32737
32738 @smallexample
32739 $ dll2def API.dll > API.def
32740 @end smallexample
32741
32742 @noindent
32743 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
32744 to standard output the list of entry points in the DLL. Note that if
32745 some routines in the DLL have the @code{Stdcall} convention
32746 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@var{nn}
32747 suffix then you'll have to edit @file{api.def} to add it, and specify
32748 @option{-k} to @command{gnatdll} when creating the import library.
32749
32750 @noindent
32751 Here are some hints to find the right @code{@@}@var{nn} suffix.
32752
32753 @enumerate
32754 @item
32755 If you have the Microsoft import library (.lib), it is possible to get
32756 the right symbols by using Microsoft @code{dumpbin} tool (see the
32757 corresponding Microsoft documentation for further details).
32758
32759 @smallexample
32760 $ dumpbin /exports api.lib
32761 @end smallexample
32762
32763 @item
32764 If you have a message about a missing symbol at link time the compiler
32765 tells you what symbol is expected. You just have to go back to the
32766 definition file and add the right suffix.
32767 @end enumerate
32768
32769 @item
32770 Build the import library @code{libAPI.dll.a}, using @code{gnatdll}
32771 (@pxref{Using gnatdll}) as follows:
32772
32773 @smallexample
32774 $ gnatdll -e API.def -d API.dll
32775 @end smallexample
32776
32777 @noindent
32778 @code{gnatdll} takes as input a definition file @file{API.def} and the
32779 name of the DLL containing the services listed in the definition file
32780 @file{API.dll}. The name of the static import library generated is
32781 computed from the name of the definition file as follows: if the
32782 definition file name is @var{xyz}@code{.def}, the import library name will
32783 be @code{lib}@var{xyz}@code{.a}. Note that in the previous example option
32784 @option{-e} could have been removed because the name of the definition
32785 file (before the ``@code{.def}'' suffix) is the same as the name of the
32786 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
32787 @end enumerate
32788
32789 @node Microsoft-Style Import Library
32790 @subsubsection Microsoft-Style Import Library
32791
32792 @noindent
32793 With GNAT you can either use a GNAT-style or Microsoft-style import
32794 library. A Microsoft import library is needed only if you plan to make an
32795 Ada DLL available to applications developed with Microsoft
32796 tools (@pxref{Mixed-Language Programming on Windows}).
32797
32798 To create a Microsoft-style import library for @file{API.dll} you
32799 should proceed as follows:
32800
32801 @enumerate
32802 @item
32803 Create the definition file @file{API.def} from the DLL. For this use either
32804 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
32805 tool (see the corresponding Microsoft documentation for further details).
32806
32807 @item
32808 Build the actual import library using Microsoft's @code{lib} utility:
32809
32810 @smallexample
32811 $ lib -machine:IX86 -def:API.def -out:API.lib
32812 @end smallexample
32813
32814 @noindent
32815 If you use the above command the definition file @file{API.def} must
32816 contain a line giving the name of the DLL:
32817
32818 @smallexample
32819 LIBRARY      "API"
32820 @end smallexample
32821
32822 @noindent
32823 See the Microsoft documentation for further details about the usage of
32824 @code{lib}.
32825 @end enumerate
32826
32827 @node Building DLLs with GNAT
32828 @section Building DLLs with GNAT
32829 @cindex DLLs, building
32830
32831 @noindent
32832 This section explain how to build DLLs using the GNAT built-in DLL
32833 support. With the following procedure it is straight forward to build
32834 and use DLLs with GNAT.
32835
32836 @enumerate
32837
32838 @item building object files
32839
32840 The first step is to build all objects files that are to be included
32841 into the DLL. This is done by using the standard @command{gnatmake} tool.
32842
32843 @item building the DLL
32844
32845 To build the DLL you must use @command{gcc}'s @option{-shared}
32846 option. It is quite simple to use this method:
32847
32848 @smallexample
32849 $ gcc -shared -o api.dll obj1.o obj2.o @dots{}
32850 @end smallexample
32851
32852 It is important to note that in this case all symbols found in the
32853 object files are automatically exported. It is possible to restrict
32854 the set of symbols to export by passing to @command{gcc} a definition
32855 file, @pxref{The Definition File}. For example:
32856
32857 @smallexample
32858 $ gcc -shared -o api.dll api.def obj1.o obj2.o @dots{}
32859 @end smallexample
32860
32861 If you use a definition file you must export the elaboration procedures
32862 for every package that required one. Elaboration procedures are named
32863 using the package name followed by "_E".
32864
32865 @item preparing DLL to be used
32866
32867 For the DLL to be used by client programs the bodies must be hidden
32868 from it and the .ali set with read-only attribute. This is very important
32869 otherwise GNAT will recompile all packages and will not actually use
32870 the code in the DLL. For example:
32871
32872 @smallexample
32873 $ mkdir apilib
32874 $ copy *.ads *.ali api.dll apilib
32875 $ attrib +R apilib\*.ali
32876 @end smallexample
32877
32878 @end enumerate
32879
32880 At this point it is possible to use the DLL by directly linking
32881 against it. Note that you must use the GNAT shared runtime when using
32882 GNAT shared libraries. This is achieved by using @option{-shared} binder's
32883 option.
32884
32885 @smallexample
32886 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
32887 @end smallexample
32888
32889 @node Building DLLs with GNAT Project files
32890 @section Building DLLs with GNAT Project files
32891 @cindex DLLs, building
32892
32893 @noindent
32894 There is nothing specific to Windows in the build process.
32895 @pxref{Library Projects}.
32896
32897 @noindent
32898 Due to a system limitation, it is not possible under Windows to create threads
32899 when inside the @code{DllMain} routine which is used for auto-initialization
32900 of shared libraries, so it is not possible to have library level tasks in SALs.
32901
32902 @node Building DLLs with gnatdll
32903 @section Building DLLs with gnatdll
32904 @cindex DLLs, building
32905
32906 @menu
32907 * Limitations When Using Ada DLLs from Ada::
32908 * Exporting Ada Entities::
32909 * Ada DLLs and Elaboration::
32910 * Ada DLLs and Finalization::
32911 * Creating a Spec for Ada DLLs::
32912 * Creating the Definition File::
32913 * Using gnatdll::
32914 @end menu
32915
32916 @noindent
32917 Note that it is preferred to use the built-in GNAT DLL support
32918 (@pxref{Building DLLs with GNAT}) or GNAT Project files
32919 (@pxref{Building DLLs with GNAT Project files}) to build DLLs.
32920
32921 This section explains how to build DLLs containing Ada code using
32922 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
32923 remainder of this section.
32924
32925 The steps required to build an Ada DLL that is to be used by Ada as well as
32926 non-Ada applications are as follows:
32927
32928 @enumerate
32929 @item
32930 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
32931 @code{Stdcall} calling convention to avoid any Ada name mangling for the
32932 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
32933 skip this step if you plan to use the Ada DLL only from Ada applications.
32934
32935 @item
32936 Your Ada code must export an initialization routine which calls the routine
32937 @code{adainit} generated by @command{gnatbind} to perform the elaboration of
32938 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
32939 routine exported by the Ada DLL must be invoked by the clients of the DLL
32940 to initialize the DLL.
32941
32942 @item
32943 When useful, the DLL should also export a finalization routine which calls
32944 routine @code{adafinal} generated by @command{gnatbind} to perform the
32945 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
32946 The finalization routine exported by the Ada DLL must be invoked by the
32947 clients of the DLL when the DLL services are no further needed.
32948
32949 @item
32950 You must provide a spec for the services exported by the Ada DLL in each
32951 of the programming languages to which you plan to make the DLL available.
32952
32953 @item
32954 You must provide a definition file listing the exported entities
32955 (@pxref{The Definition File}).
32956
32957 @item
32958 Finally you must use @code{gnatdll} to produce the DLL and the import
32959 library (@pxref{Using gnatdll}).
32960 @end enumerate
32961
32962 @noindent
32963 Note that a relocatable DLL stripped using the @code{strip}
32964 binutils tool will not be relocatable anymore. To build a DLL without
32965 debug information pass @code{-largs -s} to @code{gnatdll}. This
32966 restriction does not apply to a DLL built using a Library Project.
32967 @pxref{Library Projects}.
32968
32969 @node Limitations When Using Ada DLLs from Ada
32970 @subsection Limitations When Using Ada DLLs from Ada
32971
32972 @noindent
32973 When using Ada DLLs from Ada applications there is a limitation users
32974 should be aware of. Because on Windows the GNAT run time is not in a DLL of
32975 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
32976 each Ada DLL includes the services of the GNAT run time that are necessary
32977 to the Ada code inside the DLL. As a result, when an Ada program uses an
32978 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
32979 one in the main program.
32980
32981 It is therefore not possible to exchange GNAT run-time objects between the
32982 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
32983 handles (e.g.@: @code{Text_IO.File_Type}), tasks types, protected objects
32984 types, etc.
32985
32986 It is completely safe to exchange plain elementary, array or record types,
32987 Windows object handles, etc.
32988
32989 @node Exporting Ada Entities
32990 @subsection Exporting Ada Entities
32991 @cindex Export table
32992
32993 @noindent
32994 Building a DLL is a way to encapsulate a set of services usable from any
32995 application. As a result, the Ada entities exported by a DLL should be
32996 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
32997 any Ada name mangling. As an example here is an Ada package
32998 @code{API}, spec and body, exporting two procedures, a function, and a
32999 variable:
33000
33001 @smallexample @c ada
33002 @group
33003 @cartouche
33004 with Interfaces.C; use Interfaces;
33005 package API is
33006    Count : C.int := 0;
33007    function Factorial (Val : C.int) return C.int;
33008
33009    procedure Initialize_API;
33010    procedure Finalize_API;
33011    --  Initialization & Finalization routines. More in the next section.
33012 private
33013    pragma Export (C, Initialize_API);
33014    pragma Export (C, Finalize_API);
33015    pragma Export (C, Count);
33016    pragma Export (C, Factorial);
33017 end API;
33018 @end cartouche
33019 @end group
33020 @end smallexample
33021
33022 @smallexample @c ada
33023 @group
33024 @cartouche
33025 package body API is
33026    function Factorial (Val : C.int) return C.int is
33027       Fact : C.int := 1;
33028    begin
33029       Count := Count + 1;
33030       for K in 1 .. Val loop
33031          Fact := Fact * K;
33032       end loop;
33033       return Fact;
33034    end Factorial;
33035
33036    procedure Initialize_API is
33037       procedure Adainit;
33038       pragma Import (C, Adainit);
33039    begin
33040       Adainit;
33041    end Initialize_API;
33042
33043    procedure Finalize_API is
33044       procedure Adafinal;
33045       pragma Import (C, Adafinal);
33046    begin
33047       Adafinal;
33048    end Finalize_API;
33049 end API;
33050 @end cartouche
33051 @end group
33052 @end smallexample
33053
33054 @noindent
33055 If the Ada DLL you are building will only be used by Ada applications
33056 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
33057 convention. As an example, the previous package could be written as
33058 follows:
33059
33060 @smallexample @c ada
33061 @group
33062 @cartouche
33063 package API is
33064    Count : Integer := 0;
33065    function Factorial (Val : Integer) return Integer;
33066
33067    procedure Initialize_API;
33068    procedure Finalize_API;
33069    --  Initialization and Finalization routines.
33070 end API;
33071 @end cartouche
33072 @end group
33073 @end smallexample
33074
33075 @smallexample @c ada
33076 @group
33077 @cartouche
33078 package body API is
33079    function Factorial (Val : Integer) return Integer is
33080       Fact : Integer := 1;
33081    begin
33082       Count := Count + 1;
33083       for K in 1 .. Val loop
33084          Fact := Fact * K;
33085       end loop;
33086       return Fact;
33087    end Factorial;
33088
33089    @dots{}
33090    --  The remainder of this package body is unchanged.
33091 end API;
33092 @end cartouche
33093 @end group
33094 @end smallexample
33095
33096 @noindent
33097 Note that if you do not export the Ada entities with a @code{C} or
33098 @code{Stdcall} convention you will have to provide the mangled Ada names
33099 in the definition file of the Ada DLL
33100 (@pxref{Creating the Definition File}).
33101
33102 @node Ada DLLs and Elaboration
33103 @subsection Ada DLLs and Elaboration
33104 @cindex DLLs and elaboration
33105
33106 @noindent
33107 The DLL that you are building contains your Ada code as well as all the
33108 routines in the Ada library that are needed by it. The first thing a
33109 user of your DLL must do is elaborate the Ada code
33110 (@pxref{Elaboration Order Handling in GNAT}).
33111
33112 To achieve this you must export an initialization routine
33113 (@code{Initialize_API} in the previous example), which must be invoked
33114 before using any of the DLL services. This elaboration routine must call
33115 the Ada elaboration routine @code{adainit} generated by the GNAT binder
33116 (@pxref{Binding with Non-Ada Main Programs}). See the body of
33117 @code{Initialize_Api} for an example. Note that the GNAT binder is
33118 automatically invoked during the DLL build process by the @code{gnatdll}
33119 tool (@pxref{Using gnatdll}).
33120
33121 When a DLL is loaded, Windows systematically invokes a routine called
33122 @code{DllMain}. It would therefore be possible to call @code{adainit}
33123 directly from @code{DllMain} without having to provide an explicit
33124 initialization routine. Unfortunately, it is not possible to call
33125 @code{adainit} from the @code{DllMain} if your program has library level
33126 tasks because access to the @code{DllMain} entry point is serialized by
33127 the system (that is, only a single thread can execute ``through'' it at a
33128 time), which means that the GNAT run time will deadlock waiting for the
33129 newly created task to complete its initialization.
33130
33131 @node Ada DLLs and Finalization
33132 @subsection Ada DLLs and Finalization
33133 @cindex DLLs and finalization
33134
33135 @noindent
33136 When the services of an Ada DLL are no longer needed, the client code should
33137 invoke the DLL finalization routine, if available. The DLL finalization
33138 routine is in charge of releasing all resources acquired by the DLL. In the
33139 case of the Ada code contained in the DLL, this is achieved by calling
33140 routine @code{adafinal} generated by the GNAT binder
33141 (@pxref{Binding with Non-Ada Main Programs}).
33142 See the body of @code{Finalize_Api} for an
33143 example. As already pointed out the GNAT binder is automatically invoked
33144 during the DLL build process by the @code{gnatdll} tool
33145 (@pxref{Using gnatdll}).
33146
33147 @node Creating a Spec for Ada DLLs
33148 @subsection Creating a Spec for Ada DLLs
33149
33150 @noindent
33151 To use the services exported by the Ada DLL from another programming
33152 language (e.g.@: C), you have to translate the specs of the exported Ada
33153 entities in that language. For instance in the case of @code{API.dll},
33154 the corresponding C header file could look like:
33155
33156 @smallexample
33157 @group
33158 @cartouche
33159 extern int *_imp__count;
33160 #define count (*_imp__count)
33161 int factorial (int);
33162 @end cartouche
33163 @end group
33164 @end smallexample
33165
33166 @noindent
33167 It is important to understand that when building an Ada DLL to be used by
33168 other Ada applications, you need two different specs for the packages
33169 contained in the DLL: one for building the DLL and the other for using
33170 the DLL. This is because the @code{DLL} calling convention is needed to
33171 use a variable defined in a DLL, but when building the DLL, the variable
33172 must have either the @code{Ada} or @code{C} calling convention. As an
33173 example consider a DLL comprising the following package @code{API}:
33174
33175 @smallexample @c ada
33176 @group
33177 @cartouche
33178 package API is
33179    Count : Integer := 0;
33180    @dots{}
33181    --  Remainder of the package omitted.
33182 end API;
33183 @end cartouche
33184 @end group
33185 @end smallexample
33186
33187 @noindent
33188 After producing a DLL containing package @code{API}, the spec that
33189 must be used to import @code{API.Count} from Ada code outside of the
33190 DLL is:
33191
33192 @smallexample @c ada
33193 @group
33194 @cartouche
33195 package API is
33196    Count : Integer;
33197    pragma Import (DLL, Count);
33198 end API;
33199 @end cartouche
33200 @end group
33201 @end smallexample
33202
33203 @node Creating the Definition File
33204 @subsection Creating the Definition File
33205
33206 @noindent
33207 The definition file is the last file needed to build the DLL. It lists
33208 the exported symbols. As an example, the definition file for a DLL
33209 containing only package @code{API} (where all the entities are exported
33210 with a @code{C} calling convention) is:
33211
33212 @smallexample
33213 @group
33214 @cartouche
33215 EXPORTS
33216     count
33217     factorial
33218     finalize_api
33219     initialize_api
33220 @end cartouche
33221 @end group
33222 @end smallexample
33223
33224 @noindent
33225 If the @code{C} calling convention is missing from package @code{API},
33226 then the definition file contains the mangled Ada names of the above
33227 entities, which in this case are:
33228
33229 @smallexample
33230 @group
33231 @cartouche
33232 EXPORTS
33233     api__count
33234     api__factorial
33235     api__finalize_api
33236     api__initialize_api
33237 @end cartouche
33238 @end group
33239 @end smallexample
33240
33241 @node Using gnatdll
33242 @subsection Using @code{gnatdll}
33243 @findex gnatdll
33244
33245 @menu
33246 * gnatdll Example::
33247 * gnatdll behind the Scenes::
33248 * Using dlltool::
33249 @end menu
33250
33251 @noindent
33252 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
33253 and non-Ada sources that make up your DLL have been compiled.
33254 @code{gnatdll} is actually in charge of two distinct tasks: build the
33255 static import library for the DLL and the actual DLL. The form of the
33256 @code{gnatdll} command is
33257
33258 @smallexample
33259 @cartouche
33260 $ gnatdll @ovar{switches} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
33261 @end cartouche
33262 @end smallexample
33263
33264 @noindent
33265 where @var{list-of-files} is a list of ALI and object files. The object
33266 file list must be the exact list of objects corresponding to the non-Ada
33267 sources whose services are to be included in the DLL. The ALI file list
33268 must be the exact list of ALI files for the corresponding Ada sources
33269 whose services are to be included in the DLL. If @var{list-of-files} is
33270 missing, only the static import library is generated.
33271
33272 @noindent
33273 You may specify any of the following switches to @code{gnatdll}:
33274
33275 @table @code
33276 @item -a@ovar{address}
33277 @cindex @option{-a} (@code{gnatdll})
33278 Build a non-relocatable DLL at @var{address}. If @var{address} is not
33279 specified the default address @var{0x11000000} will be used. By default,
33280 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
33281 advise the reader to build relocatable DLL.
33282
33283 @item -b @var{address}
33284 @cindex @option{-b} (@code{gnatdll})
33285 Set the relocatable DLL base address. By default the address is
33286 @code{0x11000000}.
33287
33288 @item -bargs @var{opts}
33289 @cindex @option{-bargs} (@code{gnatdll})
33290 Binder options. Pass @var{opts} to the binder.
33291
33292 @item -d @var{dllfile}
33293 @cindex @option{-d} (@code{gnatdll})
33294 @var{dllfile} is the name of the DLL. This switch must be present for
33295 @code{gnatdll} to do anything. The name of the generated import library is
33296 obtained algorithmically from @var{dllfile} as shown in the following
33297 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
33298 @code{libxyz.dll.a}. The name of the definition file to use (if not specified
33299 by option @option{-e}) is obtained algorithmically from @var{dllfile}
33300 as shown in the following example:
33301 if @var{dllfile} is @code{xyz.dll}, the definition
33302 file used is @code{xyz.def}.
33303
33304 @item -e @var{deffile}
33305 @cindex @option{-e} (@code{gnatdll})
33306 @var{deffile} is the name of the definition file.
33307
33308 @item -g
33309 @cindex @option{-g} (@code{gnatdll})
33310 Generate debugging information. This information is stored in the object
33311 file and copied from there to the final DLL file by the linker,
33312 where it can be read by the debugger. You must use the
33313 @option{-g} switch if you plan on using the debugger or the symbolic
33314 stack traceback.
33315
33316 @item -h
33317 @cindex @option{-h} (@code{gnatdll})
33318 Help mode. Displays @code{gnatdll} switch usage information.
33319
33320 @item -Idir
33321 @cindex @option{-I} (@code{gnatdll})
33322 Direct @code{gnatdll} to search the @var{dir} directory for source and
33323 object files needed to build the DLL.
33324 (@pxref{Search Paths and the Run-Time Library (RTL)}).
33325
33326 @item -k
33327 @cindex @option{-k} (@code{gnatdll})
33328 Removes the @code{@@}@var{nn} suffix from the import library's exported
33329 names, but keeps them for the link names. You must specify this
33330 option if you want to use a @code{Stdcall} function in a DLL for which
33331 the @code{@@}@var{nn} suffix has been removed. This is the case for most
33332 of the Windows NT DLL for example. This option has no effect when
33333 @option{-n} option is specified.
33334
33335 @item -l @var{file}
33336 @cindex @option{-l} (@code{gnatdll})
33337 The list of ALI and object files used to build the DLL are listed in
33338 @var{file}, instead of being given in the command line. Each line in
33339 @var{file} contains the name of an ALI or object file.
33340
33341 @item -n
33342 @cindex @option{-n} (@code{gnatdll})
33343 No Import. Do not create the import library.
33344
33345 @item -q
33346 @cindex @option{-q} (@code{gnatdll})
33347 Quiet mode. Do not display unnecessary messages.
33348
33349 @item -v
33350 @cindex @option{-v} (@code{gnatdll})
33351 Verbose mode. Display extra information.
33352
33353 @item -largs @var{opts}
33354 @cindex @option{-largs} (@code{gnatdll})
33355 Linker options. Pass @var{opts} to the linker.
33356 @end table
33357
33358 @node gnatdll Example
33359 @subsubsection @code{gnatdll} Example
33360
33361 @noindent
33362 As an example the command to build a relocatable DLL from @file{api.adb}
33363 once @file{api.adb} has been compiled and @file{api.def} created is
33364
33365 @smallexample
33366 $ gnatdll -d api.dll api.ali
33367 @end smallexample
33368
33369 @noindent
33370 The above command creates two files: @file{libapi.dll.a} (the import
33371 library) and @file{api.dll} (the actual DLL). If you want to create
33372 only the DLL, just type:
33373
33374 @smallexample
33375 $ gnatdll -d api.dll -n api.ali
33376 @end smallexample
33377
33378 @noindent
33379 Alternatively if you want to create just the import library, type:
33380
33381 @smallexample
33382 $ gnatdll -d api.dll
33383 @end smallexample
33384
33385 @node gnatdll behind the Scenes
33386 @subsubsection @code{gnatdll} behind the Scenes
33387
33388 @noindent
33389 This section details the steps involved in creating a DLL. @code{gnatdll}
33390 does these steps for you. Unless you are interested in understanding what
33391 goes on behind the scenes, you should skip this section.
33392
33393 We use the previous example of a DLL containing the Ada package @code{API},
33394 to illustrate the steps necessary to build a DLL. The starting point is a
33395 set of objects that will make up the DLL and the corresponding ALI
33396 files. In the case of this example this means that @file{api.o} and
33397 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
33398 the following:
33399
33400 @enumerate
33401 @item
33402 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
33403 the information necessary to generate relocation information for the
33404 DLL.
33405
33406 @smallexample
33407 @group
33408 $ gnatbind -n api
33409 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
33410 @end group
33411 @end smallexample
33412
33413 @noindent
33414 In addition to the base file, the @command{gnatlink} command generates an
33415 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
33416 asks @command{gnatlink} to generate the routines @code{DllMain} and
33417 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
33418 is loaded into memory.
33419
33420 @item
33421 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
33422 export table (@file{api.exp}). The export table contains the relocation
33423 information in a form which can be used during the final link to ensure
33424 that the Windows loader is able to place the DLL anywhere in memory.
33425
33426 @smallexample
33427 @group
33428 $ dlltool --dllname api.dll --def api.def --base-file api.base \
33429           --output-exp api.exp
33430 @end group
33431 @end smallexample
33432
33433 @item
33434 @code{gnatdll} builds the base file using the new export table. Note that
33435 @command{gnatbind} must be called once again since the binder generated file
33436 has been deleted during the previous call to @command{gnatlink}.
33437
33438 @smallexample
33439 @group
33440 $ gnatbind -n api
33441 $ gnatlink api -o api.jnk api.exp -mdll
33442       -Wl,--base-file,api.base
33443 @end group
33444 @end smallexample
33445
33446 @item
33447 @code{gnatdll} builds the new export table using the new base file and
33448 generates the DLL import library @file{libAPI.dll.a}.
33449
33450 @smallexample
33451 @group
33452 $ dlltool --dllname api.dll --def api.def --base-file api.base \
33453           --output-exp api.exp --output-lib libAPI.a
33454 @end group
33455 @end smallexample
33456
33457 @item
33458 Finally @code{gnatdll} builds the relocatable DLL using the final export
33459 table.
33460
33461 @smallexample
33462 @group
33463 $ gnatbind -n api
33464 $ gnatlink api api.exp -o api.dll -mdll
33465 @end group
33466 @end smallexample
33467 @end enumerate
33468
33469 @node Using dlltool
33470 @subsubsection Using @code{dlltool}
33471
33472 @noindent
33473 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
33474 DLLs and static import libraries. This section summarizes the most
33475 common @code{dlltool} switches. The form of the @code{dlltool} command
33476 is
33477
33478 @smallexample
33479 $ dlltool @ovar{switches}
33480 @end smallexample
33481
33482 @noindent
33483 @code{dlltool} switches include:
33484
33485 @table @option
33486 @item --base-file @var{basefile}
33487 @cindex @option{--base-file} (@command{dlltool})
33488 Read the base file @var{basefile} generated by the linker. This switch
33489 is used to create a relocatable DLL.
33490
33491 @item --def @var{deffile}
33492 @cindex @option{--def} (@command{dlltool})
33493 Read the definition file.
33494
33495 @item --dllname @var{name}
33496 @cindex @option{--dllname} (@command{dlltool})
33497 Gives the name of the DLL. This switch is used to embed the name of the
33498 DLL in the static import library generated by @code{dlltool} with switch
33499 @option{--output-lib}.
33500
33501 @item -k
33502 @cindex @option{-k} (@command{dlltool})
33503 Kill @code{@@}@var{nn} from exported names
33504 (@pxref{Windows Calling Conventions}
33505 for a discussion about @code{Stdcall}-style symbols.
33506
33507 @item --help
33508 @cindex @option{--help} (@command{dlltool})
33509 Prints the @code{dlltool} switches with a concise description.
33510
33511 @item --output-exp @var{exportfile}
33512 @cindex @option{--output-exp} (@command{dlltool})
33513 Generate an export file @var{exportfile}. The export file contains the
33514 export table (list of symbols in the DLL) and is used to create the DLL.
33515
33516 @item --output-lib @var{libfile}
33517 @cindex @option{--output-lib} (@command{dlltool})
33518 Generate a static import library @var{libfile}.
33519
33520 @item -v
33521 @cindex @option{-v} (@command{dlltool})
33522 Verbose mode.
33523
33524 @item --as @var{assembler-name}
33525 @cindex @option{--as} (@command{dlltool})
33526 Use @var{assembler-name} as the assembler. The default is @code{as}.
33527 @end table
33528
33529 @node GNAT and Windows Resources
33530 @section GNAT and Windows Resources
33531 @cindex Resources, windows
33532
33533 @menu
33534 * Building Resources::
33535 * Compiling Resources::
33536 * Using Resources::
33537 @end menu
33538
33539 @noindent
33540 Resources are an easy way to add Windows specific objects to your
33541 application. The objects that can be added as resources include:
33542
33543 @itemize @bullet
33544 @item
33545 menus
33546
33547 @item
33548 accelerators
33549
33550 @item
33551 dialog boxes
33552
33553 @item
33554 string tables
33555
33556 @item
33557 bitmaps
33558
33559 @item
33560 cursors
33561
33562 @item
33563 icons
33564
33565 @item
33566 fonts
33567 @end itemize
33568
33569 @noindent
33570 This section explains how to build, compile and use resources.
33571
33572 @node Building Resources
33573 @subsection Building Resources
33574 @cindex Resources, building
33575
33576 @noindent
33577 A resource file is an ASCII file. By convention resource files have an
33578 @file{.rc} extension.
33579 The easiest way to build a resource file is to use Microsoft tools
33580 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
33581 @code{dlgedit.exe} to build dialogs.
33582 It is always possible to build an @file{.rc} file yourself by writing a
33583 resource script.
33584
33585 It is not our objective to explain how to write a resource file. A
33586 complete description of the resource script language can be found in the
33587 Microsoft documentation.
33588
33589 @node Compiling Resources
33590 @subsection Compiling Resources
33591 @findex rc
33592 @findex windres
33593 @cindex Resources, compiling
33594
33595 @noindent
33596 This section describes how to build a GNAT-compatible (COFF) object file
33597 containing the resources. This is done using the Resource Compiler
33598 @code{windres} as follows:
33599
33600 @smallexample
33601 $ windres -i myres.rc -o myres.o
33602 @end smallexample
33603
33604 @noindent
33605 By default @code{windres} will run @command{gcc} to preprocess the @file{.rc}
33606 file. You can specify an alternate preprocessor (usually named
33607 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
33608 parameter. A list of all possible options may be obtained by entering
33609 the command @code{windres} @option{--help}.
33610
33611 It is also possible to use the Microsoft resource compiler @code{rc.exe}
33612 to produce a @file{.res} file (binary resource file). See the
33613 corresponding Microsoft documentation for further details. In this case
33614 you need to use @code{windres} to translate the @file{.res} file to a
33615 GNAT-compatible object file as follows:
33616
33617 @smallexample
33618 $ windres -i myres.res -o myres.o
33619 @end smallexample
33620
33621 @node Using Resources
33622 @subsection Using Resources
33623 @cindex Resources, using
33624
33625 @noindent
33626 To include the resource file in your program just add the
33627 GNAT-compatible object file for the resource(s) to the linker
33628 arguments. With @command{gnatmake} this is done by using the @option{-largs}
33629 option:
33630
33631 @smallexample
33632 $ gnatmake myprog -largs myres.o
33633 @end smallexample
33634
33635 @node Debugging a DLL
33636 @section Debugging a DLL
33637 @cindex DLL debugging
33638
33639 @menu
33640 * Program and DLL Both Built with GCC/GNAT::
33641 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
33642 @end menu
33643
33644 @noindent
33645 Debugging a DLL is similar to debugging a standard program. But
33646 we have to deal with two different executable parts: the DLL and the
33647 program that uses it. We have the following four possibilities:
33648
33649 @enumerate 1
33650 @item
33651 The program and the DLL are built with @code{GCC/GNAT}.
33652 @item
33653 The program is built with foreign tools and the DLL is built with
33654 @code{GCC/GNAT}.
33655 @item
33656 The program is built with @code{GCC/GNAT} and the DLL is built with
33657 foreign tools.
33658 @item
33659 @end enumerate
33660
33661 @noindent
33662 In this section we address only cases one and two above.
33663 There is no point in trying to debug
33664 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
33665 information in it. To do so you must use a debugger compatible with the
33666 tools suite used to build the DLL.
33667
33668 @node Program and DLL Both Built with GCC/GNAT
33669 @subsection Program and DLL Both Built with GCC/GNAT
33670
33671 @noindent
33672 This is the simplest case. Both the DLL and the program have @code{GDB}
33673 compatible debugging information. It is then possible to break anywhere in
33674 the process. Let's suppose here that the main procedure is named
33675 @code{ada_main} and that in the DLL there is an entry point named
33676 @code{ada_dll}.
33677
33678 @noindent
33679 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
33680 program must have been built with the debugging information (see GNAT -g
33681 switch). Here are the step-by-step instructions for debugging it:
33682
33683 @enumerate 1
33684 @item Launch @code{GDB} on the main program.
33685
33686 @smallexample
33687 $ gdb -nw ada_main
33688 @end smallexample
33689
33690 @item Start the program and stop at the beginning of the main procedure
33691
33692 @smallexample
33693 (gdb) start
33694 @end smallexample
33695
33696 @noindent
33697 This step is required to be able to set a breakpoint inside the DLL. As long
33698 as the program is not run, the DLL is not loaded. This has the
33699 consequence that the DLL debugging information is also not loaded, so it is not
33700 possible to set a breakpoint in the DLL.
33701
33702 @item Set a breakpoint inside the DLL
33703
33704 @smallexample
33705 (gdb) break ada_dll
33706 (gdb) cont
33707 @end smallexample
33708
33709 @end enumerate
33710
33711 @noindent
33712 At this stage a breakpoint is set inside the DLL. From there on
33713 you can use the standard approach to debug the whole program
33714 (@pxref{Running and Debugging Ada Programs}).
33715
33716 @ignore
33717 @c This used to work, probably because the DLLs were non-relocatable
33718 @c keep this section around until the problem is sorted out.
33719
33720 To break on the @code{DllMain} routine it is not possible to follow
33721 the procedure above. At the time the program stop on @code{ada_main}
33722 the @code{DllMain} routine as already been called. Either you can use
33723 the procedure below @pxref{Debugging the DLL Directly} or this procedure:
33724
33725 @enumerate 1
33726 @item Launch @code{GDB} on the main program.
33727
33728 @smallexample
33729 $ gdb ada_main
33730 @end smallexample
33731
33732 @item Load DLL symbols
33733
33734 @smallexample
33735 (gdb) add-sym api.dll
33736 @end smallexample
33737
33738 @item Set a breakpoint inside the DLL
33739
33740 @smallexample
33741 (gdb) break ada_dll.adb:45
33742 @end smallexample
33743
33744 Note that at this point it is not possible to break using the routine symbol
33745 directly as the program is not yet running. The solution is to break
33746 on the proper line (break in @file{ada_dll.adb} line 45).
33747
33748 @item Start the program
33749
33750 @smallexample
33751 (gdb) run
33752 @end smallexample
33753
33754 @end enumerate
33755 @end ignore
33756
33757 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
33758 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
33759
33760 @menu
33761 * Debugging the DLL Directly::
33762 * Attaching to a Running Process::
33763 @end menu
33764
33765 @noindent
33766 In this case things are slightly more complex because it is not possible to
33767 start the main program and then break at the beginning to load the DLL and the
33768 associated DLL debugging information. It is not possible to break at the
33769 beginning of the program because there is no @code{GDB} debugging information,
33770 and therefore there is no direct way of getting initial control. This
33771 section addresses this issue by describing some methods that can be used
33772 to break somewhere in the DLL to debug it.
33773
33774 @noindent
33775 First suppose that the main procedure is named @code{main} (this is for
33776 example some C code built with Microsoft Visual C) and that there is a
33777 DLL named @code{test.dll} containing an Ada entry point named
33778 @code{ada_dll}.
33779
33780 @noindent
33781 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
33782 been built with debugging information (see GNAT -g option).
33783
33784 @node Debugging the DLL Directly
33785 @subsubsection Debugging the DLL Directly
33786
33787 @enumerate 1
33788 @item
33789 Find out the executable starting address
33790
33791 @smallexample
33792 $ objdump --file-header main.exe
33793 @end smallexample
33794
33795 The starting address is reported on the last line. For example:
33796
33797 @smallexample
33798 main.exe:     file format pei-i386
33799 architecture: i386, flags 0x0000010a:
33800 EXEC_P, HAS_DEBUG, D_PAGED
33801 start address 0x00401010
33802 @end smallexample
33803
33804 @item
33805 Launch the debugger on the executable.
33806
33807 @smallexample
33808 $ gdb main.exe
33809 @end smallexample
33810
33811 @item
33812 Set a breakpoint at the starting address, and launch the program.
33813
33814 @smallexample
33815 $ (gdb) break *0x00401010
33816 $ (gdb) run
33817 @end smallexample
33818
33819 The program will stop at the given address.
33820
33821 @item
33822 Set a breakpoint on a DLL subroutine.
33823
33824 @smallexample
33825 (gdb) break ada_dll.adb:45
33826 @end smallexample
33827
33828 Or if you want to break using a symbol on the DLL, you need first to
33829 select the Ada language (language used by the DLL).
33830
33831 @smallexample
33832 (gdb) set language ada
33833 (gdb) break ada_dll
33834 @end smallexample
33835
33836 @item
33837 Continue the program.
33838
33839 @smallexample
33840 (gdb) cont
33841 @end smallexample
33842
33843 @noindent
33844 This will run the program until it reaches the breakpoint that has been
33845 set. From that point you can use the standard way to debug a program
33846 as described in (@pxref{Running and Debugging Ada Programs}).
33847
33848 @end enumerate
33849
33850 @noindent
33851 It is also possible to debug the DLL by attaching to a running process.
33852
33853 @node Attaching to a Running Process
33854 @subsubsection Attaching to a Running Process
33855 @cindex DLL debugging, attach to process
33856
33857 @noindent
33858 With @code{GDB} it is always possible to debug a running process by
33859 attaching to it. It is possible to debug a DLL this way. The limitation
33860 of this approach is that the DLL must run long enough to perform the
33861 attach operation. It may be useful for instance to insert a time wasting
33862 loop in the code of the DLL to meet this criterion.
33863
33864 @enumerate 1
33865
33866 @item Launch the main program @file{main.exe}.
33867
33868 @smallexample
33869 $ main
33870 @end smallexample
33871
33872 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
33873 that the process PID for @file{main.exe} is 208.
33874
33875 @item Launch gdb.
33876
33877 @smallexample
33878 $ gdb
33879 @end smallexample
33880
33881 @item Attach to the running process to be debugged.
33882
33883 @smallexample
33884 (gdb) attach 208
33885 @end smallexample
33886
33887 @item Load the process debugging information.
33888
33889 @smallexample
33890 (gdb) symbol-file main.exe
33891 @end smallexample
33892
33893 @item Break somewhere in the DLL.
33894
33895 @smallexample
33896 (gdb) break ada_dll
33897 @end smallexample
33898
33899 @item Continue process execution.
33900
33901 @smallexample
33902 (gdb) cont
33903 @end smallexample
33904
33905 @end enumerate
33906
33907 @noindent
33908 This last step will resume the process execution, and stop at
33909 the breakpoint we have set. From there you can use the standard
33910 approach to debug a program as described in
33911 (@pxref{Running and Debugging Ada Programs}).
33912
33913 @node Setting Stack Size from gnatlink
33914 @section Setting Stack Size from @command{gnatlink}
33915
33916 @noindent
33917 It is possible to specify the program stack size at link time. On modern
33918 versions of Windows, starting with XP, this is mostly useful to set the size of
33919 the main stack (environment task). The other task stacks are set with pragma
33920 Storage_Size or with the @command{gnatbind -d} command.
33921
33922 Since older versions of Windows (2000, NT4, etc.) do not allow setting the
33923 reserve size of individual tasks, the link-time stack size applies to all
33924 tasks, and pragma Storage_Size has no effect.
33925 In particular, Stack Overflow checks are made against this
33926 link-time specified size.
33927
33928 This setting can be done with
33929 @command{gnatlink} using either:
33930
33931 @itemize @bullet
33932
33933 @item using @option{-Xlinker} linker option
33934
33935 @smallexample
33936 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
33937 @end smallexample
33938
33939 This sets the stack reserve size to 0x10000 bytes and the stack commit
33940 size to 0x1000 bytes.
33941
33942 @item using @option{-Wl} linker option
33943
33944 @smallexample
33945 $ gnatlink hello -Wl,--stack=0x1000000
33946 @end smallexample
33947
33948 This sets the stack reserve size to 0x1000000 bytes. Note that with
33949 @option{-Wl} option it is not possible to set the stack commit size
33950 because the coma is a separator for this option.
33951
33952 @end itemize
33953
33954 @node Setting Heap Size from gnatlink
33955 @section Setting Heap Size from @command{gnatlink}
33956
33957 @noindent
33958 Under Windows systems, it is possible to specify the program heap size from
33959 @command{gnatlink} using either:
33960
33961 @itemize @bullet
33962
33963 @item using @option{-Xlinker} linker option
33964
33965 @smallexample
33966 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
33967 @end smallexample
33968
33969 This sets the heap reserve size to 0x10000 bytes and the heap commit
33970 size to 0x1000 bytes.
33971
33972 @item using @option{-Wl} linker option
33973
33974 @smallexample
33975 $ gnatlink hello -Wl,--heap=0x1000000
33976 @end smallexample
33977
33978 This sets the heap reserve size to 0x1000000 bytes. Note that with
33979 @option{-Wl} option it is not possible to set the heap commit size
33980 because the coma is a separator for this option.
33981
33982 @end itemize
33983
33984 @end ifset
33985
33986 @c **********************************
33987 @c * GNU Free Documentation License *
33988 @c **********************************
33989 @include fdl.texi
33990 @c GNU Free Documentation License
33991
33992 @node Index,,GNU Free Documentation License, Top
33993 @unnumbered Index
33994
33995 @printindex cp
33996
33997 @contents
33998 @c Put table of contents at end, otherwise it precedes the "title page" in
33999 @c the .txt version
34000 @c Edit the pdf file to move the contents to the beginning, after the title
34001 @c page
34002
34003 @bye